qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,498,262
|
<p>So the code worked for the guy on the tutorial.</p>
<p>I then checked my code from his git repos but couldn't find any mistakes.</p>
<p>It's a very simple website where it just saves the values which you input in the field as a list item. It showed an error.</p>
<p><a href="https://i.stack.imgur.com/p7bKN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p7bKN.png" alt="enter image description here" /></a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let myLeads = []
const inputEl = document.getElementById("input-el")
const inputBtn = document.getElementById("input-btn")
const ulEl = document.getElementById("ul-el")
inputBtn.addEventListener("click", function(){
myLeads.push(inputEl.value)
console.log(myLeads)
})
for (let i = 0; i < myLeads.length; i++) {
ulEl.innerHTML += "<li>" + myLeads[i] + "</li>"
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
margin: 0;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
}
input{
height: 50px;
width: 100%;
border: 1px solid green;
margin-top: 10px;
margin-bottom: 10px;
padding-left: 10px;
padding-right: 10px;
box-sizing: border-box;
}
button{
background-color: green;
color: antiquewhite;
height: 50px;
width: 150px;
border: 0ch;
border-radius: 10px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="ChromeEx.css">
</head>
<body>
<input type="text" id="input-el">
<button class="input-btn">SAVE INPUT</button>
<ul id="ul-el"></ul>
<script src="ChromeEx.js" defer></script>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74498273,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 1,
"selected": false,
"text": "const inputBtn = document.getElementById(\"input-btn\") <button class=\"input-btn\">SAVE INPUT</button>\n <button id=\"input-btn\" class=\"input-btn\">SAVE INPUT</button>\n"
},
{
"answer_id": 74498804,
"author": "Jamesfo",
"author_id": 6216687,
"author_profile": "https://Stackoverflow.com/users/6216687",
"pm_score": 0,
"selected": false,
"text": "null inputBtn null getElementById() null id"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330909/"
] |
74,498,283
|
<p>I'm trying to access S3 from AWS lambda and I keep getting an access denied. The lambda code has been deployed, and I run an application on my PC that invokes said lambda. The lambda is meant to read 1 files from S3, modify it, and write it to a different location in S3.</p>
<p>I have run this code without the lambda i.e. the logic that goes into the lambda can reside on my PC. That works i.e. I run the code on my PC. The code fetches the file from S3, modifies it, and saves it, successfully. However, the problem occurs when this same logic is deployed as a lambda. I therefore believe it to be some configuration problem, but I have no idea what.</p>
<p>Here's my inline s3 policy for the lambda execution role:</p>
<pre><code>{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::MY_BUCKET/*"
}
]
}
</code></pre>
<p>Here's the policty configuration for the S3 bucket:</p>
<pre><code>{
"Version": "2012-10-17",
"Id": "PolicyNumber",
"Statement": [
{
"Sid": "Statement1",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::ACCOUNT_ID:role/web_functions"
},
"Action": "s3:*",
"Resource": "arn:aws:s3:::MY_BUCKET/*"
}
]
}
</code></pre>
<p>Note that I'm using "s3:*" for now. I've been trying various combinations and s3:* is only being used until I can get something to work.</p>
<p>Additionally (if it matters):</p>
<ul>
<li>The runtime is Go 1.x</li>
<li>Arch: x86_64</li>
<li>There is no VPC configured</li>
<li>For the lambda execution role, there are 2 other policies. 1 is the default policy added at function creation time for logging. The other was added when I enabled X-Ray monitoring.</li>
<li>My S3 bucket is not publicly accessible.</li>
<li>The app on my PC runs using an IAM role with admin permissions. This is different from the lambda execution role.</li>
</ul>
<p>I've looked at other posts answering this question and I think I've covered everything, but something is still wrong. Please let me know if you find any problem I missed.</p>
<p>Any help will be greatly appreciated</p>
<p>Edit: As requested, I'm sharing a portion of the code and the error message:</p>
<pre><code>func getS3Client(region string) *s3.Client {
//region is a string (not aws.String()): "us-east-2"
client := s3.New(s3.Options{
Region: region,
})
return client
}
func getFile(bucket string, filename string) {
client := getS3Client(region)
object, err := client.GetObject(context.TODO(), &s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(filename),
})
if err != nil {
return nil, errors.New(fmt.Sprintf("Error reading s3 object: %v (bucket=%s, filename=%s)\n", err, bucket, filename))
}
}
</code></pre>
<p>And here's the error as reported by golang:</p>
<pre><code>{"errorMessage":"Error reading s3 object: operation error S3: GetObject, https response error StatusCode: 403, RequestID: QEWV1F12YHCT862X, HostID: knxgns9O+oCTJ9G2p+hXNEyZJqjeTup/25Ab6Ih6jOrN/FAZvH7gjxKb0JEp3rGQMVyzqdgu30s=, api error AccessDenied: Access Denied (bucket=MY_BUCKET, filename=DCIM/061121/DSC01033.JPG)\n","errorType":"errorString"}
</code></pre>
<p>And here's a sample log from testing the lambda within the AWS console:</p>
<pre><code>START RequestId: 33fe5480-bbfc-42e6-bce8-e5d3589d1187 Version: $LATEST
bucket: MY_BUCKET, filename: DCIM/061121/DSC01423.JPG, region: us-east-2
Error reading s3 object: operation error S3: GetObject, https response error StatusCode: 403, RequestID: KDCZ6XBVSNHX6HE1, HostID: FG1nTNI9MAwh2HhwBfRCE0Xj355RefzsSy1ludhM52rls6yzu+/ElgCeB27Q4i6enjPlX8HaGQ8=, api error AccessDenied: Access Denied (bucket=MY_BUCKET, filename=DCIM/061121/DSC01423.JPG)
: errorString
null
END RequestId: 33fe5480-bbfc-42e6-bce8-e5d3589d1187
REPORT RequestId: 33fe5480-bbfc-42e6-bce8-e5d3589d1187 Duration: 132.27 ms Billed Duration: 133 ms Memory Size: 512 MB Max Memory Used: 39 MB Init Duration: 98.39 ms
</code></pre>
|
[
{
"answer_id": 74500374,
"author": "Ayush Ganatra",
"author_id": 13222431,
"author_profile": "https://Stackoverflow.com/users/13222431",
"pm_score": -1,
"selected": false,
"text": "arn:aws:iam::ACCOUNT_ID:role/web_functions s3:ListBucket s3:ListBucket {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"VisualEditor0\",\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:GetObject\",\n \"s3:PutObject\"\n ],\n \"Resource\": \"arn:aws:s3:::MY_BUCKET/*\"\n },\n {\n \"Sid\": \"VisualEditor1\",\n \"Effect\": \"Allow\",\n \"Action\": \"s3:ListBucket\"\n \"Resource\": \"*\"\n }\n ]\n}"
},
{
"answer_id": 74503275,
"author": "Faeem Ali",
"author_id": 4572360,
"author_profile": "https://Stackoverflow.com/users/4572360",
"pm_score": 0,
"selected": false,
"text": "client := s3.New()\n cfg, _ := config.LoadDefaultConfig(context.TODO())\nclient := s3.NewFromConfig(cfg)\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4572360/"
] |
74,498,296
|
<p>I am somewhat confused regarding <strong>exactly when</strong> the context of a called function gets deleted. I have read that the stackframe of the called function is popped off when it returns. I am trying to apply that knowledge to the following scenario where function <code>foo</code> calls function <code>bar</code>, which return a structure. The code could look something like this:</p>
<pre><code>//...
struct Bill
{
float amount;
int id;
char address[100];
};
//...
Bill bar(int);
//...
void foo() {
// ...
Bill billRecord = bar(56);
//...
}
Bill bar(int i) {
//...
Bill bill = {123.56, 2347890, "123 Main Street"};
//...
return bill;
}
</code></pre>
<p>The memory for <code>bill</code> object in the function <code>bar</code> is from the stackframe of <code>bar</code>, which is popped off when <code>bar</code> returns. It appears to be still valid when the assignment of the returned structure is made to <code>billRecord</code> in <code>foo</code>.</p>
<hr />
<p>So does it mean that the stackframe for <code>bar</code> is not deleted the instant it returns but only after the value returned by <code>bar</code> is used in <code>foo</code>?</p>
|
[
{
"answer_id": 74500374,
"author": "Ayush Ganatra",
"author_id": 13222431,
"author_profile": "https://Stackoverflow.com/users/13222431",
"pm_score": -1,
"selected": false,
"text": "arn:aws:iam::ACCOUNT_ID:role/web_functions s3:ListBucket s3:ListBucket {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"VisualEditor0\",\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:GetObject\",\n \"s3:PutObject\"\n ],\n \"Resource\": \"arn:aws:s3:::MY_BUCKET/*\"\n },\n {\n \"Sid\": \"VisualEditor1\",\n \"Effect\": \"Allow\",\n \"Action\": \"s3:ListBucket\"\n \"Resource\": \"*\"\n }\n ]\n}"
},
{
"answer_id": 74503275,
"author": "Faeem Ali",
"author_id": 4572360,
"author_profile": "https://Stackoverflow.com/users/4572360",
"pm_score": 0,
"selected": false,
"text": "client := s3.New()\n cfg, _ := config.LoadDefaultConfig(context.TODO())\nclient := s3.NewFromConfig(cfg)\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5651468/"
] |
74,498,317
|
<p>I'm trying to access an endpoint and i get the above error in my springboot server, using post i can access the endpoint so the problem i guess is from my front end</p>
<p>Auth service</p>
<pre><code>const api = 'http://locahost:8080/api/auth/'
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
login(username: string, password: string): Observable<any> {
return this.http.post(api + 'signin', {
username,
password
}, httpOptions);
}
}
</code></pre>
<p>UserService</p>
<pre><code>const apiUrl = 'http://localhost:8080/api/test/'
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http : HttpClient) { }
getAdminContent() :Observable <any> {
return this.http.get(apiUrl + 'patients', {responseType :'text'})
}
}
</code></pre>
<p>TokenStorageService</p>
<pre><code>const tokenKey = 'auth-token';
const userKey = 'auth-user';
@Injectable({
providedIn: 'root'
})
export class TokenStorageService {
constructor(private router:Router) { }
signOut() : void {
window.sessionStorage.clear();
}
public saveToken(token:string) :void {
window.sessionStorage.removeItem(tokenKey);
window.sessionStorage.setItem(tokenKey, token)
}
public getToken() :string | null {
return sessionStorage.getItem(tokenKey)
}
public saveUser( user : any) : void {
window.sessionStorage.removeItem(userKey)
window.sessionStorage.setItem(userKey , JSON.stringify(user))
}
public getUser(): any {
const user = window.sessionStorage.getItem(userKey);
if (user) {
return JSON.parse(user);
}
return {};
}
}
</code></pre>
<p>AuthInterceptor</p>
<pre><code>const TOKEN_HEADER_KEY = 'Authorization';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private token: TokenStorageService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let authReq = req;
const token = this.token.getToken();
if (token != null) {
authReq = req.clone({ headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token) });
}
return next.handle(authReq);
}
}
export const authInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
];
</code></pre>
<p>LoginComponent</p>
<pre><code>export class LoginComponent implements OnInit {
form : any = {
username : null,
password: null
};
isLoggedIn = false;
isLoginFailed = false;
errorMessage = '';
roles : string [] = [ ];
constructor(private authService: AuthService ,
private tokenStorage: TokenStorageService , private router: Router,
private location: LocationStrategy) {
history.pushState(null, "null", window.location.href);
this.location.onPopState(() => {
history.pushState(null, "null", window.location.href);
});
}
ngOnInit(): void {
if (this.tokenStorage.getToken()) {
this.isLoggedIn = true;
this.roles = this.tokenStorage.getUser().roles;
}
}
onSubmit(): void {
const { username, password } = this.form;
this.authService.login(username, password).subscribe(
data => {
this.tokenStorage.saveToken(data.accessToken);
this.tokenStorage.saveUser(data);
this.isLoginFailed = false;
this.isLoggedIn = true;
this.roles = this.tokenStorage.getUser().roles;
this.router.navigate(['/home']).then(()=> window.location.reload());
},
err => {
this.errorMessage = err.error.message;
this.isLoginFailed = true;
}
);
}
reloadPage() {
window.location.reload();
}
}
</code></pre>
<p>i think the problem is at <code>const token = this.token.getToken();</code> which on <code>consloe.log(token)</code> returns <code>undefined</code> , but still i can't figure out why</p>
<p>I'm trying to GET <code>http://localhost:8080/api/test/patients</code> for the user logged in as admin</p>
<p>Checking the request in dev tools i get
<a href="https://i.stack.imgur.com/ej6xh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ej6xh.jpg" alt="image" /></a></p>
<p>Can somebody help out here please</p>
<p>checking session storage on devtools
<a href="https://i.stack.imgur.com/ygdhQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ygdhQ.jpg" alt="enter image description here" /></a>
and
<a href="https://i.stack.imgur.com/2WHux.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2WHux.jpg" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74500374,
"author": "Ayush Ganatra",
"author_id": 13222431,
"author_profile": "https://Stackoverflow.com/users/13222431",
"pm_score": -1,
"selected": false,
"text": "arn:aws:iam::ACCOUNT_ID:role/web_functions s3:ListBucket s3:ListBucket {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"VisualEditor0\",\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:GetObject\",\n \"s3:PutObject\"\n ],\n \"Resource\": \"arn:aws:s3:::MY_BUCKET/*\"\n },\n {\n \"Sid\": \"VisualEditor1\",\n \"Effect\": \"Allow\",\n \"Action\": \"s3:ListBucket\"\n \"Resource\": \"*\"\n }\n ]\n}"
},
{
"answer_id": 74503275,
"author": "Faeem Ali",
"author_id": 4572360,
"author_profile": "https://Stackoverflow.com/users/4572360",
"pm_score": 0,
"selected": false,
"text": "client := s3.New()\n cfg, _ := config.LoadDefaultConfig(context.TODO())\nclient := s3.NewFromConfig(cfg)\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19022141/"
] |
74,498,318
|
<p>So I decided to play with Amazon AWS and created a PHP application on Elastic Beanstalk. I went with the sample application which is automatically created for you.
My instance started fine, I could see the sample website but I also noticed the sample php file had another functionality: if you would send a POST request it would log it in a file.</p>
<p><a href="https://i.stack.imgur.com/9wetE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9wetE.png" alt="enter image description here" /></a></p>
<p>This would be saved to /tmp/sample-app.log.</p>
<p>So I used curl to send some POST requests to my application (ie. curl -X POST )
Then I used putty to log into the EC2 instance associated to the Beanstalk instance (by creating a key pair) and looked in the /tmp folder, there was no sample-app.log.
Actually I did a search in / for all files ending with log and I couldn't find sample-app.log.</p>
<p>What am I doing wrong?</p>
|
[
{
"answer_id": 74500374,
"author": "Ayush Ganatra",
"author_id": 13222431,
"author_profile": "https://Stackoverflow.com/users/13222431",
"pm_score": -1,
"selected": false,
"text": "arn:aws:iam::ACCOUNT_ID:role/web_functions s3:ListBucket s3:ListBucket {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"VisualEditor0\",\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:GetObject\",\n \"s3:PutObject\"\n ],\n \"Resource\": \"arn:aws:s3:::MY_BUCKET/*\"\n },\n {\n \"Sid\": \"VisualEditor1\",\n \"Effect\": \"Allow\",\n \"Action\": \"s3:ListBucket\"\n \"Resource\": \"*\"\n }\n ]\n}"
},
{
"answer_id": 74503275,
"author": "Faeem Ali",
"author_id": 4572360,
"author_profile": "https://Stackoverflow.com/users/4572360",
"pm_score": 0,
"selected": false,
"text": "client := s3.New()\n cfg, _ := config.LoadDefaultConfig(context.TODO())\nclient := s3.NewFromConfig(cfg)\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1833601/"
] |
74,498,330
|
<p>I looked for and tested many similar questions/answers/possible duplicates here on SO and other sites but I'm interested specifically in using the solution below for simplicity's sake and minimal reproducible example constraint satisfaction.</p>
<p>Why does the following modification of <a href="https://stackoverflow.com/a/52769334/10789707">this previous answer's</a> code does not work/how to make it work?</p>
<pre><code>import tkinter as tk
from tkinter import ttk
root = tk.Tk()
tree = ttk.Treeview(root)
tree.pack(fill="both", expand=True)
items = []
for i in range(10):
item = tree.insert("", "end", text="Item {}".format(i+1))
items.append(item)
items_to_select = items[:]
def select_all_items(event):
tree.selection_set(items_to_select)
tree.bind('<Button-1>', select_all_items)
root.mainloop()
</code></pre>
<p>The <a href="https://stackoverflow.com/a/52769334/10789707">original answer</a> works as is.</p>
<p>I'm looking for a way to make it work with mouse event Button-1 click.
The result should execute the selection of all items in the treeview when users click on any one item with the left mouse button (Button-1).</p>
|
[
{
"answer_id": 74500374,
"author": "Ayush Ganatra",
"author_id": 13222431,
"author_profile": "https://Stackoverflow.com/users/13222431",
"pm_score": -1,
"selected": false,
"text": "arn:aws:iam::ACCOUNT_ID:role/web_functions s3:ListBucket s3:ListBucket {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"VisualEditor0\",\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:GetObject\",\n \"s3:PutObject\"\n ],\n \"Resource\": \"arn:aws:s3:::MY_BUCKET/*\"\n },\n {\n \"Sid\": \"VisualEditor1\",\n \"Effect\": \"Allow\",\n \"Action\": \"s3:ListBucket\"\n \"Resource\": \"*\"\n }\n ]\n}"
},
{
"answer_id": 74503275,
"author": "Faeem Ali",
"author_id": 4572360,
"author_profile": "https://Stackoverflow.com/users/4572360",
"pm_score": 0,
"selected": false,
"text": "client := s3.New()\n cfg, _ := config.LoadDefaultConfig(context.TODO())\nclient := s3.NewFromConfig(cfg)\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10789707/"
] |
74,498,354
|
<p>I have a WordPress site, I need to change the "We are now open " text in my HTML site. Since my editor is not working I used CSS to replace the text. I found the correct class and applied the following changes, but the problem is the changed text is repeating. It applies twice I only need the bigger one. How do I stop repeating?</p>
<p>The view once I applied the custom CSS</p>
<p><img src="https://i.stack.imgur.com/rcdO6.jpg" alt="This is how it looks now" /></p>
<p>Custom CSS I applied</p>
<pre><code>.elementor-element-4756de9 {
visibility:hidden;
position:relative;
}
.elementor-element-4756de9 :after {
visibility:visible;
position: absolute;
top: 0;
left: 0;
content: "We are closed for the season";
}
HTML Code
<div class="elementor-element elementor-element-4756de9 elementor-widget elementor-widget-heading" data-id="4756de9" data-element_type="widget" data-widget_type="heading.default">
<div class="elementor-widget-container">
<h2 class="elementor-heading-title elementor-size-default">We are now open for the 2022 Season</h2>
</div>
</div>
</code></pre>
<p>I tried to use the text inside the <span> but it didn't work. Any idea to stop the repeat?</p>
|
[
{
"answer_id": 74498522,
"author": "Gutsy Creatives",
"author_id": 19439458,
"author_profile": "https://Stackoverflow.com/users/19439458",
"pm_score": 0,
"selected": false,
"text": ".elementor-element-4756de9 h2:after {\n visibility:visible;\n position: absolute;\n top: 0;\n left: 0;\n content: \"We are closed for the season\";\n \n \n} \n"
},
{
"answer_id": 74498538,
"author": "ksav",
"author_id": 5385381,
"author_profile": "https://Stackoverflow.com/users/5385381",
"pm_score": 2,
"selected": true,
"text": ".elementor-element-4756de9 {\n visibility: hidden;\n position: relative;\n}\n\n.elementor-element-4756de9 :after {\n visibility: visible;\n position: absolute;\n top: 0;\n left: 0;\n content: \"We are closed for the season\";\n}\n\n.elementor-element-4756de9 .elementor-heading-title {\n display: none;\n} <div class=\"elementor-element elementor-element-4756de9 elementor-widget elementor-widget-heading\" data-id=\"4756de9\" data-element_type=\"widget\" data-widget_type=\"heading.default\">\n <div class=\"elementor-widget-container\">\n <h2 class=\"elementor-heading-title elementor-size-default\">We are now open for the 2022 Season</h2>\n </div>\n</div>"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19439458/"
] |
74,498,372
|
<p>I want to store the input values from a user, that is its name, age and gender to local storage and then display it to UI.</p>
<p>What happens right now is that after displaying a newly registered student at the UI and storing the data locally (which both works) but then reloading the page the student data disappears from the UI. I don't want this to happen; how do I go about it?</p>
<p>This is some of the code I came up with so far ...</p>
<pre class="lang-html prettyprint-override"><code><main>
<div class="container">
<h1>student's info</h1>
<form class="input-form">
<input type="text"class="full-name" name="name" placeholder="Enter Full Name">
<input type="number"class="age" name="name" placeholder="Age">
<input type="text" class = "gender"name="name" placeholder="gender">
<button class="submit-btn" type="submit">submit</button>
</form>
</div>
<div class="con">
<div class="student">
</div>
</div>
</main>
</code></pre>
<pre class="lang-js prettyprint-override"><code>// GLOBAL VARIABLES
var submitBtn, student, fullName, age, gender;
submitBtn = document.querySelector('.submit-btn');
student = document.querySelector('.student');
fullName = document.querySelector('.full-name');
age = document.querySelector('.age');
gender = document.querySelector('.gender');
var arr = [];
// EVENTLISTENERS
submitBtn.addEventListener('click', addStudent);
// FUNCTIONS
function addStudent(e) {
e.preventDefault();
let div = document.createElement('div');
div.classList.add('student-box');
let nameSpan = document.createElement('span');
nameSpan.classList.add('student-name');
nameSpan.innerText = fullName.value;
let ageSpan = document.createElement('span');
ageSpan.classList.add('student-age');
ageSpan.innerText = age.value;
let genderSpan = document.createElement('span');
genderSpan.classList.add('student-gender');
genderSpan.innerText = gender.value;
saveToLocal();
div.append(nameSpan, ageSpan, genderSpan);
student.appendChild(div);
fullName.value = '';
age.value = '';
gender.value = '';
}
function saveToLocal() {
getData();
arr.push({
name: fullName.value,
ages: age.value,
genders: gender.value,
});
localStorage.setItem('student', JSON.stringify(arr));
}
function getData() {
if (localStorage.getItem('student') !== null) {
JSON.parse(localStorage.getItem('student'));
//localStorage.setItem('student', JSON.stringify(arr));
//var dis = JSON.Parse(localStorage.getItem('student'));
//student.appendChild();
//arr = JSON.parse();
//console.log(arr);
}/* else {
}*/
}
</code></pre>
|
[
{
"answer_id": 74498503,
"author": "MAYUR SANCHETI",
"author_id": 12238257,
"author_profile": "https://Stackoverflow.com/users/12238257",
"pm_score": -1,
"selected": false,
"text": "document.getElementById(\"buttotton\").onclick = function() { \nfun() \n}; \nfunction fun()\n{\n var arr = [];\n arr.push({\n name:document.getElementsByClassName(\"full-name\")[0].value,\n ages:\"25\",\n genders:\"male\"\n \n });\n localStorage.setItem('student', JSON.stringify(arr));\n}\nif(localStorage.getItem('student') !== null) {\n\n let text = localStorage.getItem(\"student\");\n const obj = JSON.parse(text);\n // const studentData = JSON.parse(localStorage.getItem('student'));\n fullName = obj[0].name;\n \n \n document.getElementsByClassName(\"full-name\")[0].value = fullName;\n \n \n} <input type=\"text\"class=\"full-name\" name=\"name\" placeholder=\"Enter Full Name\">\n<input type=\"button\" id=\"buttotton\" value=\"save\">"
},
{
"answer_id": 74498596,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 0,
"selected": false,
"text": "if(localStorage.getItem('student') !== null) {\n try {\n const studentData = JSON.parse(localStorage.getItem('student'))[0];\n fullName = studentData.name;\n age = studentData.age;\n gender = studentData.gender;\n document.getElementsByClassName(\"full-name\")[0].value = fullName;\n document.getElementsByClassName(\"age\")[0].value = age;\n document.getElementsByClassName(\"gender\")[0].value = gender;\n } catch() {}\n}\n"
},
{
"answer_id": 74520608,
"author": "Peter Seliger",
"author_id": 2627243,
"author_profile": "https://Stackoverflow.com/users/2627243",
"pm_score": 0,
"selected": false,
"text": "localStorage localStorage getRegisteredStudentData putRegisteredStudentData Map name gender age values sanitizeRegisteredStudentData createMapOfUniqueStudentItems parseJSON JSON.parse renderRegisteredStudentData dataParent studentList name gender age createRegisteredStudentViewItem 'submit' getRegisteredStudentData renderRegisteredStudentData 'submit' FormData entries this const { dataRoot, studentList, studentMap } = this;\n dataRoot studentList studentMap push set localStorage function parseJSON(value) {\n let result;\n try { result = JSON.parse(String(value)); } catch (err) {}\n return result;\n}\n\nfunction createMapOfUniqueStudentItems(studentList) {\n return new Map(\n studentList\n .map(({ name, gender, age }) => [\n // create any student's unique key for a map ...\n [name.toLowerCase(), gender.toLowerCase(), age].join('_'),\n // ... of unique student items.\n { name, gender, age }\n ])\n );\n}\nfunction sanitizeRegisteredStudentData(studentList) {\n return Array.isArray(studentList)\n && [\n // get rid of possible duplicate data items.\n ...createMapOfUniqueStudentItems(studentList).values()\n ] || [];\n}\n\nfunction getRegisteredStudentData() {\n return sanitizeRegisteredStudentData(\n parseJSON(\n localStorage\n .getItem('registered-students')\n )\n );\n}\nfunction putRegisteredStudentData(value) {\n return localStorage\n .setItem('registered-students', JSON.stringify(value));\n}\n\nfunction createRegisteredStudentViewItem({ name, gender, age }) {\n return [name, gender, age]\n .reduce((itemRoot, value) => {\n \n const valueNode = document.createElement('td');\n valueNode.appendChild(\n document.createTextNode(value)\n );\n itemRoot.appendChild(valueNode);\n\n return itemRoot;\n\n }, document.createElement('tr'));\n}\nfunction renderRegisteredStudentData(dataParent, studentList) {\n console.log({ get: studentList });\n\n const dataRoot = (new DOMParser)\n .parseFromString(\n '<table><thead></thead><tbody></tbody></table>',\n \"text/html\",\n )\n .querySelector('table')\n .cloneNode(true);\n\n dataRoot\n .querySelector('thead')\n .appendChild(createRegisteredStudentViewItem({\n name: 'Full Name', gender: 'Gender', age: 'Age',\n }));\n\n studentList\n .reduce((itemParent, studentData) => {\n\n itemParent.appendChild(\n createRegisteredStudentViewItem(studentData)\n );\n return itemParent;\n\n }, dataRoot.querySelector('tbody'));\n\n dataParent.appendChild(dataRoot);\n}\n\nfunction registerNewStudentFromBoundContext(evt) {\n evt.preventDefault();\n const { dataRoot, studentList, studentMap } = this;\n\n const formData = new FormData(evt.currentTarget);\n const itemData = [\n ...formData.entries()\n ]\n .reduce((result, [key, value]) =>\n Object.assign(result, { [ key ]: value }), {}\n );\n const { name, gender, age } = itemData;\n\n // create a student items unique key for a map lookup.\n const uniqueStudentKey = [\n name.toLowerCase(), gender.toLowerCase(), age\n ].join('_');\n\n // prevent duplicates.\n if (!studentMap.has(uniqueStudentKey)) {\n\n // add non duplicate item data to list or registered students ...\n studentList.push(itemData);\n\n // ... update the lookup map accordingly ...\n studentMap.set(uniqueStudentKey, itemData);\n\n // ... and update the local storage.\n putRegisteredStudentData(studentList);\n\n console.log({ put: studentList });\n\n // render the newly registered student's data.\n dataRoot\n .querySelector('tbody') \n .appendChild(\n createRegisteredStudentViewItem(itemData)\n );\n }\n}\n\nfunction initStudentRegistry(rootNode) {\n const formNode = rootNode.querySelector('form');\n const overviewNode = rootNode.querySelector('.registry-overview');\n\n const studentList = getRegisteredStudentData();\n const studentMap = createMapOfUniqueStudentItems(studentList);\n\n renderRegisteredStudentData(overviewNode, studentList);\n\n formNode\n .addEventListener(\n 'submit', registerNewStudentFromBoundContext.bind({\n dataRoot: overviewNode, studentList, studentMap,\n }),\n );\n\n // additional helpers for local storage \n // related demonstration purposes only.\n\n formNode\n .querySelector('[data-clear-table]')\n .addEventListener('click', evt => {\n evt.preventDefault();\n\n [...overviewNode.querySelector('tbody').childNodes]\n .forEach(child => child.remove());\n });\n formNode\n .querySelector('[data-rerender-table]')\n .addEventListener('click', evt => {\n evt.preventDefault();\n\n [...overviewNode.childNodes]\n .forEach(child => child.remove());\n\n renderRegisteredStudentData(\n overviewNode, getRegisteredStudentData(),\n );\n });\n}\n\nfunction main() {\n initStudentRegistry(\n document\n .querySelector('.student-registry')\n );\n}\nmain(); body { margin: 0; }\nform, h1 { position: fixed; right: 45%; }\nh1 { margin: 0; font-size: 1.2em; width: 7.9em; } \nform { top: 1.5em; width: 9.5em; }\ntable { width: 30%; margin: 0; }\nfieldset { margin: 0; padding: 0; border: none; }\nbutton { margin: 4px 0; }\nfieldset button { display: block; }\n.as-console-wrapper { left: auto!important; min-height: 100%; width: 45%; } <script>\n // mock for the SO specific stack snippet\n // due to the policies and environment are\n // not allowing an original storage access.\n const localStorage = (function () {\n\n // https://developer.mozilla.org/en-US/docs/Web/API/Storage\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\n const storage = new Map;\n\n function key(int) {\n return [\n ...storage.keys()\n ][parseInt(int, 10)];\n }\n\n function setItem(key, value) {\n return storage.set(String(key), String(value));\n }\n function getItem(key) {\n return storage.get(String(key));\n }\n\n function removeItem(key) {\n return storage.delete(String(key));\n }\n\n function clear() {\n return storage.clear();\n }\n\n return {\n get length() {\n return storage.size;\n },\n key,\n getItem,\n setItem,\n removeItem,\n clear, \n };\n\n }());\n</script>\n\n<main>\n <div class=\"student-registry\">\n <h1>student's info</h1>\n\n <form method=\"post\" action=\"\">\n <input type=\"text\" name=\"name\" placeholder=\"Enter Full Name\"/>\n <input type=\"number\" name=\"age\" placeholder=\"Age\" value=\"6\" min=\"6\" max=\"120\"/>\n <input type=\"text\" name=\"gender\" placeholder=\"Gender\"/>\n\n <button type=\"submit\">\n register student\n </button>\n\n <fieldset>\n <button data-clear-table>\n clear table\n </button>\n <button data-rerender-table>\n rerender table<br/>from (mocked)<br/>local storage\n </button>\n </fieldset>\n </form>\n\n <div class=\"con\"> \n <div class=\"registry-overview\">\n </div>\n </div>\n </div>\n</main>"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14648309/"
] |
74,498,402
|
<p>So in my current app setting a certain process running inside a container runs another process. I need to set the nice value of the new process to be higher.</p>
<p>When ran on the OS I could just do
<code>nice -n19 second_task</code>. How does this work in the context of the docker container?</p>
|
[
{
"answer_id": 74498503,
"author": "MAYUR SANCHETI",
"author_id": 12238257,
"author_profile": "https://Stackoverflow.com/users/12238257",
"pm_score": -1,
"selected": false,
"text": "document.getElementById(\"buttotton\").onclick = function() { \nfun() \n}; \nfunction fun()\n{\n var arr = [];\n arr.push({\n name:document.getElementsByClassName(\"full-name\")[0].value,\n ages:\"25\",\n genders:\"male\"\n \n });\n localStorage.setItem('student', JSON.stringify(arr));\n}\nif(localStorage.getItem('student') !== null) {\n\n let text = localStorage.getItem(\"student\");\n const obj = JSON.parse(text);\n // const studentData = JSON.parse(localStorage.getItem('student'));\n fullName = obj[0].name;\n \n \n document.getElementsByClassName(\"full-name\")[0].value = fullName;\n \n \n} <input type=\"text\"class=\"full-name\" name=\"name\" placeholder=\"Enter Full Name\">\n<input type=\"button\" id=\"buttotton\" value=\"save\">"
},
{
"answer_id": 74498596,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 0,
"selected": false,
"text": "if(localStorage.getItem('student') !== null) {\n try {\n const studentData = JSON.parse(localStorage.getItem('student'))[0];\n fullName = studentData.name;\n age = studentData.age;\n gender = studentData.gender;\n document.getElementsByClassName(\"full-name\")[0].value = fullName;\n document.getElementsByClassName(\"age\")[0].value = age;\n document.getElementsByClassName(\"gender\")[0].value = gender;\n } catch() {}\n}\n"
},
{
"answer_id": 74520608,
"author": "Peter Seliger",
"author_id": 2627243,
"author_profile": "https://Stackoverflow.com/users/2627243",
"pm_score": 0,
"selected": false,
"text": "localStorage localStorage getRegisteredStudentData putRegisteredStudentData Map name gender age values sanitizeRegisteredStudentData createMapOfUniqueStudentItems parseJSON JSON.parse renderRegisteredStudentData dataParent studentList name gender age createRegisteredStudentViewItem 'submit' getRegisteredStudentData renderRegisteredStudentData 'submit' FormData entries this const { dataRoot, studentList, studentMap } = this;\n dataRoot studentList studentMap push set localStorage function parseJSON(value) {\n let result;\n try { result = JSON.parse(String(value)); } catch (err) {}\n return result;\n}\n\nfunction createMapOfUniqueStudentItems(studentList) {\n return new Map(\n studentList\n .map(({ name, gender, age }) => [\n // create any student's unique key for a map ...\n [name.toLowerCase(), gender.toLowerCase(), age].join('_'),\n // ... of unique student items.\n { name, gender, age }\n ])\n );\n}\nfunction sanitizeRegisteredStudentData(studentList) {\n return Array.isArray(studentList)\n && [\n // get rid of possible duplicate data items.\n ...createMapOfUniqueStudentItems(studentList).values()\n ] || [];\n}\n\nfunction getRegisteredStudentData() {\n return sanitizeRegisteredStudentData(\n parseJSON(\n localStorage\n .getItem('registered-students')\n )\n );\n}\nfunction putRegisteredStudentData(value) {\n return localStorage\n .setItem('registered-students', JSON.stringify(value));\n}\n\nfunction createRegisteredStudentViewItem({ name, gender, age }) {\n return [name, gender, age]\n .reduce((itemRoot, value) => {\n \n const valueNode = document.createElement('td');\n valueNode.appendChild(\n document.createTextNode(value)\n );\n itemRoot.appendChild(valueNode);\n\n return itemRoot;\n\n }, document.createElement('tr'));\n}\nfunction renderRegisteredStudentData(dataParent, studentList) {\n console.log({ get: studentList });\n\n const dataRoot = (new DOMParser)\n .parseFromString(\n '<table><thead></thead><tbody></tbody></table>',\n \"text/html\",\n )\n .querySelector('table')\n .cloneNode(true);\n\n dataRoot\n .querySelector('thead')\n .appendChild(createRegisteredStudentViewItem({\n name: 'Full Name', gender: 'Gender', age: 'Age',\n }));\n\n studentList\n .reduce((itemParent, studentData) => {\n\n itemParent.appendChild(\n createRegisteredStudentViewItem(studentData)\n );\n return itemParent;\n\n }, dataRoot.querySelector('tbody'));\n\n dataParent.appendChild(dataRoot);\n}\n\nfunction registerNewStudentFromBoundContext(evt) {\n evt.preventDefault();\n const { dataRoot, studentList, studentMap } = this;\n\n const formData = new FormData(evt.currentTarget);\n const itemData = [\n ...formData.entries()\n ]\n .reduce((result, [key, value]) =>\n Object.assign(result, { [ key ]: value }), {}\n );\n const { name, gender, age } = itemData;\n\n // create a student items unique key for a map lookup.\n const uniqueStudentKey = [\n name.toLowerCase(), gender.toLowerCase(), age\n ].join('_');\n\n // prevent duplicates.\n if (!studentMap.has(uniqueStudentKey)) {\n\n // add non duplicate item data to list or registered students ...\n studentList.push(itemData);\n\n // ... update the lookup map accordingly ...\n studentMap.set(uniqueStudentKey, itemData);\n\n // ... and update the local storage.\n putRegisteredStudentData(studentList);\n\n console.log({ put: studentList });\n\n // render the newly registered student's data.\n dataRoot\n .querySelector('tbody') \n .appendChild(\n createRegisteredStudentViewItem(itemData)\n );\n }\n}\n\nfunction initStudentRegistry(rootNode) {\n const formNode = rootNode.querySelector('form');\n const overviewNode = rootNode.querySelector('.registry-overview');\n\n const studentList = getRegisteredStudentData();\n const studentMap = createMapOfUniqueStudentItems(studentList);\n\n renderRegisteredStudentData(overviewNode, studentList);\n\n formNode\n .addEventListener(\n 'submit', registerNewStudentFromBoundContext.bind({\n dataRoot: overviewNode, studentList, studentMap,\n }),\n );\n\n // additional helpers for local storage \n // related demonstration purposes only.\n\n formNode\n .querySelector('[data-clear-table]')\n .addEventListener('click', evt => {\n evt.preventDefault();\n\n [...overviewNode.querySelector('tbody').childNodes]\n .forEach(child => child.remove());\n });\n formNode\n .querySelector('[data-rerender-table]')\n .addEventListener('click', evt => {\n evt.preventDefault();\n\n [...overviewNode.childNodes]\n .forEach(child => child.remove());\n\n renderRegisteredStudentData(\n overviewNode, getRegisteredStudentData(),\n );\n });\n}\n\nfunction main() {\n initStudentRegistry(\n document\n .querySelector('.student-registry')\n );\n}\nmain(); body { margin: 0; }\nform, h1 { position: fixed; right: 45%; }\nh1 { margin: 0; font-size: 1.2em; width: 7.9em; } \nform { top: 1.5em; width: 9.5em; }\ntable { width: 30%; margin: 0; }\nfieldset { margin: 0; padding: 0; border: none; }\nbutton { margin: 4px 0; }\nfieldset button { display: block; }\n.as-console-wrapper { left: auto!important; min-height: 100%; width: 45%; } <script>\n // mock for the SO specific stack snippet\n // due to the policies and environment are\n // not allowing an original storage access.\n const localStorage = (function () {\n\n // https://developer.mozilla.org/en-US/docs/Web/API/Storage\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\n const storage = new Map;\n\n function key(int) {\n return [\n ...storage.keys()\n ][parseInt(int, 10)];\n }\n\n function setItem(key, value) {\n return storage.set(String(key), String(value));\n }\n function getItem(key) {\n return storage.get(String(key));\n }\n\n function removeItem(key) {\n return storage.delete(String(key));\n }\n\n function clear() {\n return storage.clear();\n }\n\n return {\n get length() {\n return storage.size;\n },\n key,\n getItem,\n setItem,\n removeItem,\n clear, \n };\n\n }());\n</script>\n\n<main>\n <div class=\"student-registry\">\n <h1>student's info</h1>\n\n <form method=\"post\" action=\"\">\n <input type=\"text\" name=\"name\" placeholder=\"Enter Full Name\"/>\n <input type=\"number\" name=\"age\" placeholder=\"Age\" value=\"6\" min=\"6\" max=\"120\"/>\n <input type=\"text\" name=\"gender\" placeholder=\"Gender\"/>\n\n <button type=\"submit\">\n register student\n </button>\n\n <fieldset>\n <button data-clear-table>\n clear table\n </button>\n <button data-rerender-table>\n rerender table<br/>from (mocked)<br/>local storage\n </button>\n </fieldset>\n </form>\n\n <div class=\"con\"> \n <div class=\"registry-overview\">\n </div>\n </div>\n </div>\n</main>"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17843694/"
] |
74,498,418
|
<p>I have a controller class with the ActionResult of a post request.</p>
<pre class="lang-cs prettyprint-override"><code>public ActionResult Test()
{
return View()
}
[HttpPost]
public ActionResult Test()
{
Service1Client o = new Service1Client();
bool result = o.Test(); // returns a True boolean
System.Diagnostics.Debug.WriteLine(result); // True
return View()
}
</code></pre>
<p>In my <code>.cshtml</code> file, I want to display this boolean. Or if the result from the controller class is a string, I want to display it. How do I do it? I tried <code>ViewBag</code> and it doesn't work because <code>ViewBag</code> only renders it for the first time. Please help!</p>
<pre class="lang-html prettyprint-override"><code><p>@result</p>
</code></pre>
|
[
{
"answer_id": 74498479,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 1,
"selected": false,
"text": "obj Test return View(obj); @Model.<YourPropertyName> @model <NameSpaceName>.<YouModelClassName>\n"
},
{
"answer_id": 74502432,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": 0,
"selected": false,
"text": "[HttpPost]\npublic ActionResult Test()\n{\n Service1Client o = new Service1Client();\n bool result = o.Test(); // returns a True boolean\n\n System.Diagnostics.Debug.WriteLine(result); // True\n\n return View(result)\n}\n @model boolean\n\n....\n\n<p>@Model.ToString()</p>\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19561210/"
] |
74,498,419
|
<p>The following code can be compiled with g++ 8.1.0 and clang 10.0.0.</p>
<pre><code>#include <memory>
#include <iostream>
#include <functional>
int main() {
auto dereference = std::bind(
&std::shared_ptr<int>::operator*,
std::placeholders::_1);
std::shared_ptr<int> sp = std::make_shared<int>(10);
std::cout << dereference(sp) << std::endl;
return 0;
}
</code></pre>
<p>However, msvc in vs2022 reports the following error:</p>
<pre><code>example.cpp<source>(6): error C2672: 'std::bind': no matching overloaded function foundC:/data/msvc/14.34.31931-Pre/include\functional(2029): note: could be 'std::_Binder<_Ret,_Fx,_Types...> std::bind(_Fx &&,_Types &&...)'<source>(8):
note: 'std::_Binder<_Ret,_Fx,_Types...> std::bind(_Fx &&,_Types &&...)': could not deduce template argument for '_Ret'<source>(8): note: 'std::_Binder<_Ret,_Fx,_Types...> std::bind(_Fx &&,_Types &&...)': could not deduce template argument for '_Fx'C:/data/msvc/14.34.31931-Pre/include\functional(2024): note: or 'std::_Binder<std::_Unforced,_Fx,_Types...> std::bind(_Fx &&,_Types &&...)'<source>(8): note: 'std::_Binder<std::_Unforced,_Fx,_Types...> std::bind(_Fx &&,_Types &&...)': could not deduce template argument for '_Fx'<source>(11): error C3536: 'dereference': cannot be used before it is initialized<source>(11): error C2064: term does not evaluate to a function taking 1 argumentsCompiler returned: 2
</code></pre>
<p>Is it a bug of msvc compiler or the above code can be fixed?</p>
<p>To reproduce the compile error, you can go to <a href="https://godbolt.org/" rel="nofollow noreferrer">https://godbolt.org/</a> for details.</p>
|
[
{
"answer_id": 74499236,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 3,
"selected": true,
"text": "operator* std::bind std::bind std::bind auto dereference = [](auto&& p)->decltype(auto){ return *decltype(p)(p); };\n auto decltype(p)(p) p noexcept ->decltype(auto) operator*"
},
{
"answer_id": 74499796,
"author": "felix",
"author_id": 7038446,
"author_profile": "https://Stackoverflow.com/users/7038446",
"pm_score": 1,
"selected": false,
"text": "std::bind auto addr = &std::shared_ptr<int>::operator*;\n static_cast<int &(std::shared_ptr<int>::*)() const noexcept>(&std::shared_ptr<int>::operator*) std::shared_ptr<int>::operator* T& operator*() const noexcept #include <memory>\n#include <iostream>\n#include <functional>\n\nint main() {\n auto dereference = std::bind(\n static_cast<int &(std::shared_ptr<int>::*)() const noexcept>(&std::shared_ptr<int>::operator*),\n std::placeholders::_1);\n\n std::shared_ptr<int> sp = std::make_shared<int>(10);\n std::cout << dereference(sp) << std::endl;\n\n return 0;\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14704583/"
] |
74,498,470
|
<p>Let say I have class like this</p>
<pre><code>class OrderInfo {
final String orderId;
final String status;
final DateTime orderDateTime;
final DateTime? deliverDateTime;
final String? restaurantTitle;
OrderInfo({
required this.orderId,
required this.status,
required this.orderDateTime,
required this.deliverDateTime,
required this.restaurantTitle,
});
// and a getter
Something get something {
// Very long code that I don't want to recalculate
return something;
};
}
</code></pre>
<p>Since all fields is <code>final</code>, so there's no point to recalculate (return value will be the same).</p>
<p>I tried create field like this.</p>
<pre><code>late Something something = () {
// Very long code that I don't want to recalculate
return something;
}();
</code></pre>
<p>But I'm not sure this is correct way to do.
Is there other method or this is fine?</p>
|
[
{
"answer_id": 74499346,
"author": "lrn",
"author_id": 2156621,
"author_profile": "https://Stackoverflow.com/users/2156621",
"pm_score": 3,
"selected": true,
"text": "final class OrderInfo {\n late final Something something = _computeSomething();\n ...\n Something _computeSomething() {\n // Very long code that I don't want to recalculate\n return something;\n }\n}\n _computeSomething Something null class OrderInfo {\n Something? _something;\n ...\n Something get something => _something ??= _computeSomething();\n ...\n}\n late final .. = ... _something late late late late late final something = ...; late final late final late final"
},
{
"answer_id": 74499787,
"author": "Sayyid J",
"author_id": 15366030,
"author_profile": "https://Stackoverflow.com/users/15366030",
"pm_score": 0,
"selected": false,
"text": "class OrderInfo {\n final String orderId;\n final String status;\n final DateTime orderDateTime;\n final DateTime? deliverDateTime;\n final String? restaurantTitle;\n\n late final Something _somethingFinal;\n\n OrderInfo({\n required this.orderId,\n required this.status,\n required this.orderDateTime,\n required this.deliverDateTime,\n required this.restaurantTitle,\n }){\n _somethingFinal = _calculateSomthing();\n }\n\n // and a getter\n Something get something {\n // Very long code that I don't want to recalculate\n return _somethingFinal;\n }\n\n Something _calculateSomthing(){\n return Something();\n }\n\n}\n\nclass Something{\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14468940/"
] |
74,498,485
|
<p>This is the code I have used from a tutorial</p>
<pre><code>def view():
with open('My coding stuff\\passwords.txt', 'r') as f:
for line in f.readlines():
data = line.rstrip()
user, passw = data.split("|")
print("User:",user, ", password:", passw)
</code></pre>
<p>I have no idea what is wrong with the code
I was trying to make a password manager by following a tutorial and i am just confused</p>
|
[
{
"answer_id": 74499346,
"author": "lrn",
"author_id": 2156621,
"author_profile": "https://Stackoverflow.com/users/2156621",
"pm_score": 3,
"selected": true,
"text": "final class OrderInfo {\n late final Something something = _computeSomething();\n ...\n Something _computeSomething() {\n // Very long code that I don't want to recalculate\n return something;\n }\n}\n _computeSomething Something null class OrderInfo {\n Something? _something;\n ...\n Something get something => _something ??= _computeSomething();\n ...\n}\n late final .. = ... _something late late late late late final something = ...; late final late final late final"
},
{
"answer_id": 74499787,
"author": "Sayyid J",
"author_id": 15366030,
"author_profile": "https://Stackoverflow.com/users/15366030",
"pm_score": 0,
"selected": false,
"text": "class OrderInfo {\n final String orderId;\n final String status;\n final DateTime orderDateTime;\n final DateTime? deliverDateTime;\n final String? restaurantTitle;\n\n late final Something _somethingFinal;\n\n OrderInfo({\n required this.orderId,\n required this.status,\n required this.orderDateTime,\n required this.deliverDateTime,\n required this.restaurantTitle,\n }){\n _somethingFinal = _calculateSomthing();\n }\n\n // and a getter\n Something get something {\n // Very long code that I don't want to recalculate\n return _somethingFinal;\n }\n\n Something _calculateSomthing(){\n return Something();\n }\n\n}\n\nclass Something{\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20546084/"
] |
74,498,496
|
<p>I want to get all of the id1 where id2 is equal to <strong>2 and 3</strong>. Consider the sample table given below</p>
<p><strong>Sample Table-</strong></p>
<pre><code>| id1 | id2 |
| --- | --- |
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 2 | 2 |
| 2 | 4 |
</code></pre>
<p>In this case, expected output is as mentioned below because <strong>2 is only mapped to 2 and not to 3</strong>, and hence only 1 result comes in output.</p>
<p><strong>Expected output-</strong></p>
<pre><code>| id1 |
| --- |
| 1 |
</code></pre>
<p>But when i run the following query it also gives id1 = 2 in result along with id1 = 1</p>
<pre><code>Select id1 from table where id2 in (2,3) group by id1;
</code></pre>
<p>What is the correct query to get this output?</p>
|
[
{
"answer_id": 74499346,
"author": "lrn",
"author_id": 2156621,
"author_profile": "https://Stackoverflow.com/users/2156621",
"pm_score": 3,
"selected": true,
"text": "final class OrderInfo {\n late final Something something = _computeSomething();\n ...\n Something _computeSomething() {\n // Very long code that I don't want to recalculate\n return something;\n }\n}\n _computeSomething Something null class OrderInfo {\n Something? _something;\n ...\n Something get something => _something ??= _computeSomething();\n ...\n}\n late final .. = ... _something late late late late late final something = ...; late final late final late final"
},
{
"answer_id": 74499787,
"author": "Sayyid J",
"author_id": 15366030,
"author_profile": "https://Stackoverflow.com/users/15366030",
"pm_score": 0,
"selected": false,
"text": "class OrderInfo {\n final String orderId;\n final String status;\n final DateTime orderDateTime;\n final DateTime? deliverDateTime;\n final String? restaurantTitle;\n\n late final Something _somethingFinal;\n\n OrderInfo({\n required this.orderId,\n required this.status,\n required this.orderDateTime,\n required this.deliverDateTime,\n required this.restaurantTitle,\n }){\n _somethingFinal = _calculateSomthing();\n }\n\n // and a getter\n Something get something {\n // Very long code that I don't want to recalculate\n return _somethingFinal;\n }\n\n Something _calculateSomthing(){\n return Something();\n }\n\n}\n\nclass Something{\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13662630/"
] |
74,498,543
|
<p>This is my systemd service file:</p>
<pre><code>[Unit]
Description=Foo
[Service]
WorkingDirectory=/tmp/test
ExecStartPre=/usr/bin/yq -o json config.yaml > config.json
ExecStart=/usr/bin/foo run -c config.json
[Install]
WantedBy=multi-user.target
</code></pre>
<p>Everything working if I run <code>ExecStartPre</code> and <code>ExecStart</code> in the shell.
But got error when I run <code>systemctl start foo.service</code>:</p>
<pre><code>Error: open >: no such file or directory
</code></pre>
<p>Seems the ">" operator doesn't work as shell in the systemd file.</p>
|
[
{
"answer_id": 74499346,
"author": "lrn",
"author_id": 2156621,
"author_profile": "https://Stackoverflow.com/users/2156621",
"pm_score": 3,
"selected": true,
"text": "final class OrderInfo {\n late final Something something = _computeSomething();\n ...\n Something _computeSomething() {\n // Very long code that I don't want to recalculate\n return something;\n }\n}\n _computeSomething Something null class OrderInfo {\n Something? _something;\n ...\n Something get something => _something ??= _computeSomething();\n ...\n}\n late final .. = ... _something late late late late late final something = ...; late final late final late final"
},
{
"answer_id": 74499787,
"author": "Sayyid J",
"author_id": 15366030,
"author_profile": "https://Stackoverflow.com/users/15366030",
"pm_score": 0,
"selected": false,
"text": "class OrderInfo {\n final String orderId;\n final String status;\n final DateTime orderDateTime;\n final DateTime? deliverDateTime;\n final String? restaurantTitle;\n\n late final Something _somethingFinal;\n\n OrderInfo({\n required this.orderId,\n required this.status,\n required this.orderDateTime,\n required this.deliverDateTime,\n required this.restaurantTitle,\n }){\n _somethingFinal = _calculateSomthing();\n }\n\n // and a getter\n Something get something {\n // Very long code that I don't want to recalculate\n return _somethingFinal;\n }\n\n Something _calculateSomthing(){\n return Something();\n }\n\n}\n\nclass Something{\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6702575/"
] |
74,498,546
|
<p>I have a list of 10 values:</p>
<pre><code>variable=[2.1, 5.3, 4.1, 6.7, 2, 6.6, 1.9, 4.51, 4, 7.15]
</code></pre>
<p>Its length:</p>
<pre><code>>>> len(variable)
10
</code></pre>
<p>Its average:</p>
<pre><code>>>> mean(variable)
4.436
</code></pre>
<p>Its standard deviation:</p>
<pre><code>>>> np.std(variable)
1.8987269419271429
</code></pre>
<p>From it I want to generate a <code>new_variable</code> having <code>len(new_variable)==100</code> and normally distributed where <code>mean==4.436</code> and <code>np.std==1.898</code>.</p>
|
[
{
"answer_id": 74498561,
"author": "mousetail",
"author_id": 6333444,
"author_profile": "https://Stackoverflow.com/users/6333444",
"pm_score": 2,
"selected": false,
"text": "import random\nx = random.gauss(4.436, 1.898)\n import random\nx = [random.gauss(4.436, 1.898) for _ in range(100)]\n"
},
{
"answer_id": 74498792,
"author": "khalo-sa",
"author_id": 17684014,
"author_profile": "https://Stackoverflow.com/users/17684014",
"pm_score": 2,
"selected": true,
"text": "from statistics import NormalDist, mean, stdev\n\ndef get_target_dist(target_mean, target_std, size):\n dist = NormalDist(target_mean, target_std).samples(size)\n dist_mean, dist_std = mean(dist), stdev(dist)\n dist_standard = [(val - dist_mean) / dist_std for val in dist]\n dist_scaled = [val * target_std + target_mean for val in dist_standard]\n return dist_scaled\n\ndist = get_target_dist(4.436, 1.898, 100)\n\nprint(\"len:\", len(dist))\nprint(\"mean:\", mean(dist))\nprint(\"std:\", stdev(dist))\n\n# len: 100\n# mean: 4.436\n# std: 1.898\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15852600/"
] |
74,498,573
|
<p>The objective is to <code>concat</code> all values in a <code>dict</code> into a single <code>str.</code></p>
<p>Additionally, the <code>\r\n</code> also will be appended.</p>
<p>The code below demonstrates the end result.</p>
<p>However, I am looking for a more elegant alternative than the proposed code below.</p>
<pre><code>d=dict(idx='1',sat='so',sox=[['x1: y3'],['x2: y1'],['x3: y3']],mul_sol='my love so')
s=''
for x in d:
if x=='sox':
for kk in d[x]:
s=s +kk[0] +'\r\n'
else:
s=s +d[x]+'\r\n'
print(s)
</code></pre>
|
[
{
"answer_id": 74498601,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 2,
"selected": true,
"text": "d['sox'] join() s = ''.join(kk[0] for kk in d['sox']) + '\\r\\n'\ns += '\\r\\n'.join(val for key, val in d.items() if key != 'sox')\n"
},
{
"answer_id": 74498700,
"author": "shan",
"author_id": 18579739,
"author_profile": "https://Stackoverflow.com/users/18579739",
"pm_score": 2,
"selected": false,
"text": "def conca(li):\n ret=''\n for ele in li:\n if isinstance(ele,str):\n ret += ele + '\\r\\n'\n else:\n ret += conca(ele) \n return ret\n\nprint(conca([d[e] for e in list(d)]))\n def conca(li):\n ret = ''\n for ele in li:\n if isinstance(ele, str):\n ret += ele + '\\r\\n'\n elif isinstance(ele, list):\n ret += conca(ele)\n elif isinstance(ele, dict):\n ret += conca(ele.values())\n # you can add any other customized conversions here...\n else:\n raise Exception(\n \"value of dictionary can only be str, list or dict~\")\n return ret\nprint(conca([d[e] for e in list(d)]))\n"
},
{
"answer_id": 74498801,
"author": "Toby Speight",
"author_id": 4850040,
"author_profile": "https://Stackoverflow.com/users/4850040",
"pm_score": 2,
"selected": false,
"text": "map d = {\n 'idx': '1',\n 'sat': 'so',\n 'sox': [['x1: y3'],['x2: y1'],['x3: y3']],\n 'mul_sol': 'my love so'\n}\n\ncrlf = '\\r\\n'\n\nimport operator\n\ndef transform_sox(item):\n (key, val) = item\n if key == 'sox':\n return crlf.join(map(operator.itemgetter(0), val))\n else:\n return val\n\nprint(crlf.join(map(transform_sox, d.items())), crlf)\n def transform_sox(value):\n return value if isinstance(value, str) \\\n else crlf.join(map(operator.itemgetter(0), value))\n\nprint(crlf.join(map(transform_sox, d.values())), crlf)\n formatters = collections.defaultdict(lambda: lambda x: x)\nformatters['sox'] = lambda x: crlf.join(map(operator.itemgetter(0), x))\n\ndef transform_sox(item):\n return formatters[item[0]](item[1])\n\nprint(crlf.join(map(transform_sox, d.items())), crlf)\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6446053/"
] |
74,498,593
|
<p>I am trying to get the name of the employee from the database and fill it in the textbox for the respective employee id.</p>
<p>I tried this code but nothing is happening on the page. It just reloads and the textbox (name) is left blank only.</p>
<pre><code>SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-0FUUV7B\SQLEXPRESS;Initial Catalog=EmployeeDetails;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from ProfessionalDetails where EmpId='"+EmployeeId.Text+"'", con);
SqlDataReader da = cmd.ExecuteReader();
while (da.Read())
{
Name.Text = da.GetValue(1).ToString();
}
con.Close();
</code></pre>
|
[
{
"answer_id": 74498601,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 2,
"selected": true,
"text": "d['sox'] join() s = ''.join(kk[0] for kk in d['sox']) + '\\r\\n'\ns += '\\r\\n'.join(val for key, val in d.items() if key != 'sox')\n"
},
{
"answer_id": 74498700,
"author": "shan",
"author_id": 18579739,
"author_profile": "https://Stackoverflow.com/users/18579739",
"pm_score": 2,
"selected": false,
"text": "def conca(li):\n ret=''\n for ele in li:\n if isinstance(ele,str):\n ret += ele + '\\r\\n'\n else:\n ret += conca(ele) \n return ret\n\nprint(conca([d[e] for e in list(d)]))\n def conca(li):\n ret = ''\n for ele in li:\n if isinstance(ele, str):\n ret += ele + '\\r\\n'\n elif isinstance(ele, list):\n ret += conca(ele)\n elif isinstance(ele, dict):\n ret += conca(ele.values())\n # you can add any other customized conversions here...\n else:\n raise Exception(\n \"value of dictionary can only be str, list or dict~\")\n return ret\nprint(conca([d[e] for e in list(d)]))\n"
},
{
"answer_id": 74498801,
"author": "Toby Speight",
"author_id": 4850040,
"author_profile": "https://Stackoverflow.com/users/4850040",
"pm_score": 2,
"selected": false,
"text": "map d = {\n 'idx': '1',\n 'sat': 'so',\n 'sox': [['x1: y3'],['x2: y1'],['x3: y3']],\n 'mul_sol': 'my love so'\n}\n\ncrlf = '\\r\\n'\n\nimport operator\n\ndef transform_sox(item):\n (key, val) = item\n if key == 'sox':\n return crlf.join(map(operator.itemgetter(0), val))\n else:\n return val\n\nprint(crlf.join(map(transform_sox, d.items())), crlf)\n def transform_sox(value):\n return value if isinstance(value, str) \\\n else crlf.join(map(operator.itemgetter(0), value))\n\nprint(crlf.join(map(transform_sox, d.values())), crlf)\n formatters = collections.defaultdict(lambda: lambda x: x)\nformatters['sox'] = lambda x: crlf.join(map(operator.itemgetter(0), x))\n\ndef transform_sox(item):\n return formatters[item[0]](item[1])\n\nprint(crlf.join(map(transform_sox, d.items())), crlf)\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20002248/"
] |
74,498,656
|
<p>I'm still quite new to programming in Rust, but I do have experience with C/C++ programming.</p>
<p>The crux of my question has to do with this code:</p>
<p><code>src/main.rs</code>:</p>
<pre class="lang-rust prettyprint-override"><code>use storefront::store_model;
fn main() {
let mut store_model: store_model::StoreModel = store_model::new_store_model();
store_model.add_product(
String::from("Test Product"),
123.45,
String::from("This is a Test Product."),
String::from("This is a Test Product for a test."),
42,
);
store_model.add_product(
String::from("Wonderfon"),
77.34,
String::from("This is the 1998 Wonderfon, brought back in 2022!"),
String::from("Call like it's the 1990's! The Wonderfon is back in all its glory!"),
77,
);
store_model.add_product(
String::from("Test Product 2.0"),
123.45,
String::from("This is the Test Product 2.0!"),
String::from("This is a Test Product 2.0 for another test."),
42,
);
match store_model.product(0) {
None => println!("That isn't an item!"),
Some(p) => {
let (product, quantity) = p;
println!("{}", product.name());
}
}
match store_model.product(1) {
None => println!("That isn't an item!"),
Some(p) => println!("{:?}", p),
}
match store_model.product(2) {
None => println!("That isn't an item!"),
Some(p) => println!("{:?}", p),
}
match store_model.product(3) {
None => println!("That isn't an item!"),
Some(p) => println!("{:?}", p),
}
}
</code></pre>
<p>I didn't expect to be able to use the <code>name()</code> method for product (which is a struct I defined in a separate module, <code>src/product.rs</code>). What I did expect was some sort of error.</p>
<p>Is this expected behavior in Rust? If it is, is it explained somewhere, or is there any resources pointing to this behavior? I own a copy of <em>The Rust Programming Language</em> (for Rust 2018) and am currently on chapter 9. If it's further than what I've read to, where is it?</p>
|
[
{
"answer_id": 74499331,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 0,
"selected": false,
"text": "// src/product.rs\nstruct Product;\nimpl Product {\n fn name(&self) {}\n}\n let p = crate::product::Product;\np.name();\n// ^ this is syntactic sugar to the following:\ncrate::product::Product::name(&p);\n"
},
{
"answer_id": 74502112,
"author": "Kevin Reid",
"author_id": 99692,
"author_profile": "https://Stackoverflow.com/users/99692",
"pm_score": 2,
"selected": true,
"text": "T T T T impl Product { .rmeta src/main.rs src/product.rs"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20414356/"
] |
74,498,660
|
<p>This is the Table:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>NAME:</th>
<th>DATE:</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>2022-10-04</td>
</tr>
<tr>
<td>Apple</td>
<td>2022-10-04</td>
</tr>
<tr>
<td>Apple</td>
<td>2022-10-04</td>
</tr>
<tr>
<td>Orange</td>
<td>2022-10-04</td>
</tr>
<tr>
<td>Apple</td>
<td>2022-10-06</td>
</tr>
<tr>
<td>Apple</td>
<td>2022-10-06</td>
</tr>
<tr>
<td>Apple</td>
<td>2022-10-06</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to group by name & date, and also add a column called 'Counts'.</p>
<p>OUTCOME that I wanna look like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>NAME:</th>
<th>DATE:</th>
<th>COUNTS:</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>2022-10-04</td>
<td>3</td>
</tr>
<tr>
<td>Orange</td>
<td>2022-10-04</td>
<td>1</td>
</tr>
<tr>
<td>Apple</td>
<td>2022-10-06</td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74499331,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 0,
"selected": false,
"text": "// src/product.rs\nstruct Product;\nimpl Product {\n fn name(&self) {}\n}\n let p = crate::product::Product;\np.name();\n// ^ this is syntactic sugar to the following:\ncrate::product::Product::name(&p);\n"
},
{
"answer_id": 74502112,
"author": "Kevin Reid",
"author_id": 99692,
"author_profile": "https://Stackoverflow.com/users/99692",
"pm_score": 2,
"selected": true,
"text": "T T T T impl Product { .rmeta src/main.rs src/product.rs"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19972459/"
] |
74,498,688
|
<p>I am trying to alternate the presence of a TinyMCE editor in R Shiny.</p>
<p>I can load the editor, then remove it with the respective <code>actionButton</code>s. However, upon attempting to load it more than once, only a <code>textAreaInput</code>-type interface is rendered:</p>
<pre><code>library(shiny)
library(ShinyEditor)
ui <- fluidPage(
use_editor("API-KEY"),
uiOutput("tiny"),
actionButton("load", "Load TinyMCE"),
actionButton( "remove", "Remove TinyMCE" ))
server <- function(input, output, session) {
observeEvent(input$load, {
output$tiny = renderUI( editor('textcontent'))})
observeEvent(input$remove, {
output$tiny = renderUI( NULL)})
}
shinyApp(ui = ui, server = server)
</code></pre>
<p>How would it be possible to reload it? Thank you.</p>
|
[
{
"answer_id": 74500961,
"author": "Stéphane Laurent",
"author_id": 1100107,
"author_profile": "https://Stackoverflow.com/users/1100107",
"pm_score": 2,
"selected": true,
"text": "library(shiny)\nlibrary(ShinyEditor)\n\nui <- fluidPage(\n use_editor(\"API-KEY\"),\n uiOutput(\"tiny\"),\n actionButton(\"btn\", \"Load/Remove TinyMCE\"), \n)\n\nserver <- function(input, output, session) {\n output$tiny <- renderUI({\n if(input$btn %% 2 == 0) {\n editor('textcontent')\n } else {\n NULL\n }\n })\n}\n\nshinyApp(ui = ui, server = server)\n library(shiny)\nlibrary(ShinyEditor)\n\nui <- fluidPage(\n use_editor(\"API-KEY\"),\n conditionalPanel(\n condition = \"input.btn %% 2 == 0\",\n uiOutput(\"tiny\")\n ),\n actionButton(\"btn\", \"Load/Remove TinyMCE\"), \n)\n\nserver <- function(input, output, session) {\n output$tiny <- renderUI({\n editor('textcontent')\n })\n}\n\nshinyApp(ui = ui, server = server)\n"
},
{
"answer_id": 74502172,
"author": "Graham",
"author_id": 14790235,
"author_profile": "https://Stackoverflow.com/users/14790235",
"pm_score": 0,
"selected": false,
"text": "library(shiny)\nlibrary(ShinyEditor)\nlibrary(shinyjs)\n\nui <- fluidPage(\n use_editor(\"API-KEY\"),\n useShinyjs(),\n uiOutput(\"tiny\"),\n actionButton( \"toggle\", \"Toggle TinyMCE\" ))\nserver <- function(input, output, session) {\n\n output$tiny = renderUI( editor('textcontent'))\n observe({if(input$toggle %% 2 == 0) {\n hide('tiny')\n } else {\n show('tiny')\n }\n })\n}\nshinyApp(ui = ui, server = server)\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14790235/"
] |
74,498,690
|
<p>I am receiving a response that I need to save as CSV file. So I would like to convert the response string as an array of json objects then access all the objects and convert each to json and push to another array to write to a csv with <code>csv.writerow()</code>. Probably this is too much steps and can be reduced. But I am currently searching for a way to convert the response to an array. Here is the response sample along with code of trial:</p>
<pre><code>import json
null = -1
response_object = """[{
"a" : "1",
"b" : "2",
"c" : "null"
}, {
"d" : "3",
"e" : "4",
"f" : "null"
}]
"""
jess_dict = json.dumps(response_object)
jeson_converted = json.loads(jess_dict)
print(jeson_converted)
</code></pre>
<p>since the response object is not a valid json, I am not sure what I should do to convert it. Please suggest.</p>
|
[
{
"answer_id": 74498745,
"author": "Oghli",
"author_id": 5169186,
"author_profile": "https://Stackoverflow.com/users/5169186",
"pm_score": 1,
"selected": false,
"text": "literal_eval ast import ast\nparsed_response_object = ast.literal_eval(response_object)\nfor json_obj in parsed_response_object:\n print(json_obj)\n {'a': '1', 'b': '2', 'c': 'null'}\n{'d': '3', 'e': '4', 'f': 'null'}\n"
},
{
"answer_id": 74498754,
"author": "Amin",
"author_id": 10281248,
"author_profile": "https://Stackoverflow.com/users/10281248",
"pm_score": 2,
"selected": false,
"text": "json.dumps loads ...\njeson_converted = json.loads(response_object)\nprint(jeson_converted)\n [{'a': '1', 'b': '2', 'c': 'null'}, {'d': '3', 'e': '4', 'f': 'null'}]\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7291498/"
] |
74,498,699
|
<p>I have two dataframes. One has tens of thousands of rows. The other has hundreds of rows.</p>
<p>df_1(tens of thousands of rows) (Inventory)</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Color</th>
<th>Size</th>
<th>Shape</th>
<th>rating</th>
</tr>
</thead>
<tbody>
<tr>
<td>Red</td>
<td>2</td>
<td>pear</td>
<td>82</td>
</tr>
<tr>
<td>Purple</td>
<td>4</td>
<td>heart</td>
<td>85</td>
</tr>
<tr>
<td>Blue</td>
<td>5</td>
<td>oval</td>
<td>99</td>
</tr>
<tr>
<td>Black</td>
<td>2</td>
<td>round</td>
<td>91</td>
</tr>
<tr>
<td>Red</td>
<td>1</td>
<td>heart</td>
<td>67</td>
</tr>
</tbody>
</table>
</div>
<p>df_2(hundreds of rows) (Table of standard ratings of gems with different colors, size and shape)</p>
<pre><code>| Color | Size | Shape(pear) |Shape(heart) |Shape(oval)
| standard rating |standard rating |standard rating
| -------- | -------- | -------- | -------- |----------
| Red | 1 | 85 | 85 | 85
| Red | 2 | 87 | 86 | 85
| Red | 3 | 85 | 88 | 86
| Red | 4 | 86 | 83 | 86
| Red | 5 | 85 | 84 | 86
| Blue | 1 | 90 | 90 | 90
</code></pre>
<p>I need to add a new column to df_1 called standard rating. It gives the standard rating from df_2 to each row in df_1.</p>
<p>For row 1 in df_1 which is a red gem, size 2 with pear shape. I'd like to fetch the standard rating of the same color gem, with the same size and shape from df_2 which is 87 and put it in a new column in df_1.</p>
<p>df_1</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Color</th>
<th>Size</th>
<th>Shape</th>
<th>ratings</th>
<th>standard ratings</th>
</tr>
</thead>
<tbody>
<tr>
<td>Red</td>
<td>2</td>
<td>pear</td>
<td>82</td>
<td>87</td>
</tr>
<tr>
<td>Purple</td>
<td>4</td>
<td>heart</td>
<td>85</td>
<td>85</td>
</tr>
<tr>
<td>Blue</td>
<td>5</td>
<td>oval</td>
<td>99</td>
<td>90</td>
</tr>
<tr>
<td>Black</td>
<td>2</td>
<td>round</td>
<td>91</td>
<td>92</td>
</tr>
<tr>
<td>Red</td>
<td>1</td>
<td>heart</td>
<td>67</td>
<td>85</td>
</tr>
</tbody>
</table>
</div>
<p>Any suggestions how I can accomplish it?</p>
|
[
{
"answer_id": 74498745,
"author": "Oghli",
"author_id": 5169186,
"author_profile": "https://Stackoverflow.com/users/5169186",
"pm_score": 1,
"selected": false,
"text": "literal_eval ast import ast\nparsed_response_object = ast.literal_eval(response_object)\nfor json_obj in parsed_response_object:\n print(json_obj)\n {'a': '1', 'b': '2', 'c': 'null'}\n{'d': '3', 'e': '4', 'f': 'null'}\n"
},
{
"answer_id": 74498754,
"author": "Amin",
"author_id": 10281248,
"author_profile": "https://Stackoverflow.com/users/10281248",
"pm_score": 2,
"selected": false,
"text": "json.dumps loads ...\njeson_converted = json.loads(response_object)\nprint(jeson_converted)\n [{'a': '1', 'b': '2', 'c': 'null'}, {'d': '3', 'e': '4', 'f': 'null'}]\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20546011/"
] |
74,498,701
|
<p><a href="https://i.stack.imgur.com/0zKEt.png" rel="nofollow noreferrer">Table</a></p>
<pre><code>CREATE DEFINER=`root`@`localhost` FUNCTION `GetGPA`(sName VARCHAR(45)) RETURNS float
DETERMINISTIC
BEGIN
DECLARE grade FLOAT;
DECLARE sName VARCHAR(45);
SELECT GPA INTO grade
FROM student
WHERE studentName = sName;
RETURN grade;
END
</code></pre>
<p>I did the function and it returned null:
<a href="https://i.stack.imgur.com/VKuW8.png" rel="nofollow noreferrer">Stored Function</a></p>
<p>I tried returning a student's GPA using a function inputting a student's name.</p>
|
[
{
"answer_id": 74498739,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": 0,
"selected": false,
"text": "Into set CREATE DEFINER=`root`@`localhost` FUNCTION `GetGPA`(sName VARCHAR(45)) RETURNS float\n DETERMINISTIC\nBEGIN\nDECLARE @grade FLOAT;\nDECLARE sName VARCHAR(45);\n\nSELECT @grade=GPA \nFROM student\nWHERE studentName = sName;\n\nRETURN @grade;\nEND\n"
},
{
"answer_id": 74498752,
"author": "Ergest Basha",
"author_id": 16461952,
"author_profile": "https://Stackoverflow.com/users/16461952",
"pm_score": 1,
"selected": false,
"text": "CREATE FUNCTION GetGPA (sname varchar(45)) \n RETURNS float DETERMINISTIC\nBEGIN\n DECLARE grade FLOAT;\n SELECT GPA INTO grade\n FROM student\n WHERE StudentName = sName;\n RETURN grade;\nEND \n DECLARE sName VARCHAR(45);"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20546282/"
] |
74,498,718
|
<p>//Modify the program from the previous exercise, so that it displays just the sum of all of the numbers from one to the input number. Be sure to test your program with several inputs.</p>
<pre><code>// Example5.java
import java.util.Scanner;
public class Example5 {
public static void main(String[] args) {
int count = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = in.nextInt();
while (count <= number) {
System.out.println(count);
++count;
}
}
</code></pre>
<p>Given that code I have to modify the program that it displays the sum from 1 to the input number.</p>
|
[
{
"answer_id": 74498840,
"author": "Lunatic",
"author_id": 15758781,
"author_profile": "https://Stackoverflow.com/users/15758781",
"pm_score": 1,
"selected": false,
"text": "public class Example5 {\n public static void main(String[] args) {\n int sum = 0;\n System.out.println(\"Add your numbers to sum: \");\n Scanner in = new Scanner(new Scanner(System.in).nextLine());\n while (in.hasNext()) {\n sum += in.nextInt();\n }\n System.out.println(sum);\n }\n}\n"
},
{
"answer_id": 74498885,
"author": "m3ow",
"author_id": 20474278,
"author_profile": "https://Stackoverflow.com/users/20474278",
"pm_score": 0,
"selected": false,
"text": "import java.util.Scanner;\n\npublic class Example5 {\n\n public static void main(String[] args) {\n int sum = 0, number;\n Scanner in = new Scanner(System.in);\n\n System.out.println(\"Enter a number: \");\n number = in.nextInt();\n\n for (int i = 1; i <= number; i++) sum += i;\n\n System.out.println(sum);\n }\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20546326/"
] |
74,498,773
|
<p>I have a table such as (dput format at the end):</p>
<pre><code>Groups SP1 SP2 SP3 SP4_1 SP4_2 SP5_1 SP5_2
G1 3 4 NA 2 4 2 1
G2 NA 1 NA 3 NA NA NA
G3 1 2 NA NA NA 8 NA
G4 4 6 NA NA NA NA NA
G5 8 9 NA NA NA NA 2
</code></pre>
<p>And I would like to sweep that table into:</p>
<pre><code> G1 G2 G3 G4 G5
SP1 SP1-3 NA SP1-1 SP1-4 SP1-8
SP2 SP2-4 SP2-1 SP2-2 SP2-6 SP2-9
SP3 NA NA NA NA NA
SP4 SP4_1-2;SP4_2-4 SP4_1-3 NA NA NA
SP5 SP5_1-2;SP5_2-1 NA SP5_1-8 NA SP5_2-2
</code></pre>
<p>Let me explain:</p>
<p>Let's take the <strong>G1</strong> to explain,
The Idea is first to create a new column <code>G1</code> and add all <code>SPn</code> present as rows:</p>
<pre><code> G1
SP1
SP2
SP3
SP4
SP5
</code></pre>
<p>Then, in <code>G1</code>, I have one value for <strong>SP1</strong> which is <strong>3</strong>, then I add a row <code>SP1-3</code></p>
<pre><code> G1
SP1 SP1-3
SP2
SP3
SP4
SP5
</code></pre>
<p>I have one value for <strong>SP2</strong> which is <strong>4</strong>, then I add a row <code>SP1-4</code></p>
<pre><code> G1
SP1 SP1-3
SP2 SP1-4
SP3
SP4
SP5
</code></pre>
<p>I have no value for <strong>SP3</strong></p>
<pre><code> G1
SP1 SP1-3
SP2 SP1-4
SP3 NA
SP4
SP5
</code></pre>
<p>I have two values for <strong>SP4</strong> which are <strong>2 in SP4_1</strong> and <strong>4 in SP4_2</strong>, then I merge them by a semicolon ";" within the cell and add a row <code>SP4_1-2;SP4_2-4</code></p>
<pre><code> G1
SP1 SP1-3
SP2 SP1-4
SP3 NA
SP4 SP4_1-2;SP4_2-4
SP5
</code></pre>
<p>And finally I have two values for <strong>SP5</strong> which are <strong>2 in SP5_1</strong> and <strong>1 in SP5_2</strong>, then I merge them by a semicolon ";" within the cell and add a row <code>SP5_1-2;SP5_2-1</code></p>
<pre><code> G1
SP1 SP1-3
SP2 SP1-4
SP3 NA
SP4 SP4_1-2;SP4_2-4
SP5 SP5_1-2;SP5_2-1
</code></pre>
<p>And so on for the other groups.</p>
<p>Does someone have an idea using Python please?</p>
<p>here is the dput format of the example table:</p>
<pre><code>structure(list(Groups = c("G1", "G2", "G3", "G4", "G5"), SP1 = c(3L,
NA, 1L, 4L, 8L), SP2 = c(4L, 1L, 2L, 6L, 9L), SP3 = c(NA, NA,
NA, NA, NA), SP4_1 = c(2L, 3L, NA, NA, NA), SP4_2 = c(4L, NA,
NA, NA, NA), SP5_1 = c(2L, NA, 8L, NA, NA), SP5_2 = c(1L, NA,
NA, NA, 2L)), class = "data.frame", row.names = c(NA, -5L))
</code></pre>
|
[
{
"answer_id": 74498840,
"author": "Lunatic",
"author_id": 15758781,
"author_profile": "https://Stackoverflow.com/users/15758781",
"pm_score": 1,
"selected": false,
"text": "public class Example5 {\n public static void main(String[] args) {\n int sum = 0;\n System.out.println(\"Add your numbers to sum: \");\n Scanner in = new Scanner(new Scanner(System.in).nextLine());\n while (in.hasNext()) {\n sum += in.nextInt();\n }\n System.out.println(sum);\n }\n}\n"
},
{
"answer_id": 74498885,
"author": "m3ow",
"author_id": 20474278,
"author_profile": "https://Stackoverflow.com/users/20474278",
"pm_score": 0,
"selected": false,
"text": "import java.util.Scanner;\n\npublic class Example5 {\n\n public static void main(String[] args) {\n int sum = 0, number;\n Scanner in = new Scanner(System.in);\n\n System.out.println(\"Enter a number: \");\n number = in.nextInt();\n\n for (int i = 1; i <= number; i++) sum += i;\n\n System.out.println(sum);\n }\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12559770/"
] |
74,498,823
|
<p>I want to print a square using two half pyramids but it's displaying it vertically instead of printing out a square. I also encounter this problem in other patterns that I create using loops and I don't know how to resolve it. Here's my code:</p>
<pre><code>for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.println("A");
}
for (int k = 5; k >= i; k--) {
System.out.println("B");
}
System.out.println();
}
</code></pre>
<p>Expected result:</p>
<p>A
B
B
B
B
B</p>
<p>A
A
B
B
B
B</p>
<p>A
A
A
B
B
B</p>
<p>A
A
A
A
B
B</p>
<p>A
A
A
A
A
B</p>
|
[
{
"answer_id": 74498844,
"author": "Rahul",
"author_id": 6367109,
"author_profile": "https://Stackoverflow.com/users/6367109",
"pm_score": 2,
"selected": false,
"text": "print println for (int i = 1; i <= 5; i++) {\n for (int j = 1; j <= i; j++) {\n System.out.print(\"A\");\n }\n for (int k = 5; k >= i; k--) {\n System.out.print(\"B\");\n }\n System.out.println();\n}\n"
},
{
"answer_id": 74498872,
"author": "Umair Ali Khan",
"author_id": 15814754,
"author_profile": "https://Stackoverflow.com/users/15814754",
"pm_score": 1,
"selected": false,
"text": "system.out.println(\"A\"); \n system.out.print(\"B\");\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19955084/"
] |
74,498,824
|
<p>i typed <code>rails s</code> in the terminal and everything was working fine,</p>
<p>as my rails server was running i by mistakely pressed ctrl+z on the keyboard and next time when i tried to run <code>rails s</code> , my terminal was showing an error</p>
<p><code>A server is already running. Check /home/..name/rprojects/railsapp/tmp/pids/server.pid.</code></p>
<p>so i checked other solutions on stackoverflow itself and i found out we need to delete the <code>server.pid.</code> file present inside it.</p>
<p>after when i deleted the <code>server.pid.</code> file and typed <code>rails s</code> to start the server in the terminal, my browser keeps on loading the http://localhost:3000/ and does not render anything, it just keeps on loading and nothing happens</p>
<p>so then i typed <code>rails s -p 3001</code> in the terminal and it started working fine and everything is working normally on 3001 port</p>
<p>So how do i fix the loading problem on 3000 port when i run <code>rails s</code> in terminal and infinite loop of loading occurs and nothing happens??</p>
<p>even if i did not start the rails server in terminal and went on browser and typed http://localhost:3000/ , it keeps on loading and nothing shows</p>
|
[
{
"answer_id": 74498844,
"author": "Rahul",
"author_id": 6367109,
"author_profile": "https://Stackoverflow.com/users/6367109",
"pm_score": 2,
"selected": false,
"text": "print println for (int i = 1; i <= 5; i++) {\n for (int j = 1; j <= i; j++) {\n System.out.print(\"A\");\n }\n for (int k = 5; k >= i; k--) {\n System.out.print(\"B\");\n }\n System.out.println();\n}\n"
},
{
"answer_id": 74498872,
"author": "Umair Ali Khan",
"author_id": 15814754,
"author_profile": "https://Stackoverflow.com/users/15814754",
"pm_score": 1,
"selected": false,
"text": "system.out.println(\"A\"); \n system.out.print(\"B\");\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20214145/"
] |
74,498,888
|
<p>I am trying to create a calculator app using Tkinter in python.
However, when I am trying to input my text in entry box i am getting the following error.</p>
<pre><code>Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Optimus\anaconda3\envs\virtual_enviournment\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Users\Optimus\AppData\Local\Temp/ipykernel_2608/2120973008.py", line 18, in <lambda>
button_7=Button(root, text="7", padx=40,pady=20, command=lambda: button_click(7))
TypeError: 'Button' object is not callable
</code></pre>
<p>my Code for the app is:</p>
<pre><code>from tkinter import *
root=Tk()
root.title("Simple Calculator")
e=Entry(root, width=35, borderwidth=5)
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10 )
def button_click(number):
e.delete(0, END)
e.insert(0, number)
#Define buttons
button_1=Button(root, text="1", padx=40,pady=20, command=lambda: button_click(1))
button_2=Button(root, text="2", padx=40,pady=20, command=lambda: button_click(2))
button_3=Button(root, text="3", padx=40,pady=20, command=lambda: button_click(3))
button_4=Button(root, text="4", padx=40,pady=20, command=lambda: button_click(4))
button_5=Button(root, text="5", padx=40,pady=20, command=lambda: button_click(5))
button_6=Button(root, text="6", padx=40,pady=20, command=lambda: button_click(6))
button_7=Button(root, text="7", padx=40,pady=20, command=lambda: button_click(7))
button_8=Button(root, text="8", padx=40,pady=20, command=lambda: button_click(8))
button_9=Button(root, text="9", padx=40,pady=20, command=lambda: button_click(9))
button_0=Button(root, text="0", padx=40,pady=20, command=lambda: button_click(0))
button_click=Button(root, text="+", padx=40,pady=20, command=lambda: button_click())
button_equals=Button(root, text="=", padx=120,pady=20, command=lambda: button_click())
button_clear=Button(root, text="Clear", padx=30,pady=20, command=lambda: button_click())
# Put the bottons
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)
button_0.grid(row=4, column=0)
button_click.grid(row=4, column=1)
button_equals.grid(row=6, column=0, columnspan=3)
button_clear.grid(row=4, column=2)
root.mainloop()
</code></pre>
<p>Text is not getting entered in entry box.</p>
|
[
{
"answer_id": 74499059,
"author": "Artygo",
"author_id": 11547305,
"author_profile": "https://Stackoverflow.com/users/11547305",
"pm_score": 1,
"selected": true,
"text": "button_click=Button(root, text=\"+\", padx=40,pady=20, command=lambda: button_click())\n button_click Button"
},
{
"answer_id": 74499066,
"author": "Ayesha Nadeem",
"author_id": 20546157,
"author_profile": "https://Stackoverflow.com/users/20546157",
"pm_score": 1,
"selected": false,
"text": "button_click button_click Button Click_Button"
},
{
"answer_id": 74499089,
"author": "Sam Wittwicky",
"author_id": 20546479,
"author_profile": "https://Stackoverflow.com/users/20546479",
"pm_score": 0,
"selected": false,
"text": "from tkinter import *\nfrom functools import partial\nroot=Tk()\nroot.title(\"Simple Calculator\")\ne=Entry(root, width=35, borderwidth=5)\ne.grid(row=0, column=0, columnspan=3, padx=10, pady=10 )\n\ndef button_click(number):\n e.delete(0, END)\n e.insert(0, number)\n\naction_with_arg1 = partial(button_click, 1)\naction_with_arg2 = partial(button_click, 2)\naction_with_arg3 = partial(button_click, 3)\naction_with_arg4 = partial(button_click, 4)\naction_with_arg5 = partial(button_click, 5)\naction_with_arg6 = partial(button_click, 6)\naction_with_arg7 = partial(button_click, 7)\naction_with_arg8 = partial(button_click, 8)\naction_with_arg9 = partial(button_click, 9)\naction_with_arg0 = partial(button_click, 0)\n#Define buttons\nbutton_1=Button(root, text=\"1\", padx=40,pady=20, command=action_with_arg1)\n\nbutton_2=Button(root, text=\"2\", padx=40,pady=20, command=action_with_arg2)\nbutton_3=Button(root, text=\"3\", padx=40,pady=20, command=action_with_arg3)\nbutton_4=Button(root, text=\"4\", padx=40,pady=20, command=action_with_arg4)\nbutton_5=Button(root, text=\"5\", padx=40,pady=20, command=action_with_arg5)\nbutton_6=Button(root, text=\"6\", padx=40,pady=20, command=action_with_arg6)\nbutton_7=Button(root, text=\"7\", padx=40,pady=20, command=action_with_arg7)\nbutton_8=Button(root, text=\"8\", padx=40,pady=20, command=action_with_arg8)\nbutton_9=Button(root, text=\"9\", padx=40,pady=20, command=action_with_arg9)\nbutton_0=Button(root, text=\"0\", padx=40,pady=20, command=action_with_arg0)\nbutton_click=Button(root, text=\"+\", padx=40,pady=20, command=button_click())\nbutton_equals=Button(root, text=\"=\", padx=120,pady=20, command=button_click())\nbutton_clear=Button(root, text=\"Clear\", padx=30,pady=20, command=button_click())\n\n# Put the bottons \nbutton_1.grid(row=3, column=0)\nbutton_2.grid(row=3, column=1)\nbutton_3.grid(row=3, column=2)\nbutton_4.grid(row=2, column=0)\nbutton_5.grid(row=2, column=1)\nbutton_6.grid(row=2, column=2)\nbutton_7.grid(row=1, column=0)\nbutton_8.grid(row=1, column=1)\nbutton_9.grid(row=1, column=2)\nbutton_0.grid(row=4, column=0)\nbutton_click.grid(row=4, column=1)\nbutton_equals.grid(row=6, column=0, columnspan=3)\nbutton_clear.grid(row=4, column=2)\n\nroot.mainloop()\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20546479/"
] |
74,498,899
|
<p>Let's say I have these three models:</p>
<pre><code>class Author(models.Model):
name = models.CharField(max_length=64)
class Book(models.Model):
author = models.ForeignKey(
Author,
blank=True,
null=True,
on_delete=models.SET_NULL
)
name = models.CharField(max_length=64)
class Store(models.Model):
books = models.ManyToManyField(Book)
name = models.CharField(max_length=64)
</code></pre>
<p>I don't know the author of some books. In these cases, the author is null.</p>
<p>When I query Store, I would like to know how many books each store has and sort them. So my queryset is something like this:</p>
<pre><code>Store.objects.all().annotate(books_count=Count('books')).order_by('-books_count')
</code></pre>
<p>Now, what if I want to count only the books that have an author?</p>
<p>I tried this queryset, but it is clearly not correct:</p>
<pre><code>filter = Q(books__author__isnull=False)
Store.objects.annotate(books_count=Count(filter)).all().order_by('-books_count')
</code></pre>
<p>Does anyone know the correct way to do this query?</p>
|
[
{
"answer_id": 74498981,
"author": "lucutzu33",
"author_id": 8770336,
"author_profile": "https://Stackoverflow.com/users/8770336",
"pm_score": 1,
"selected": false,
"text": "Book.objects.filter(author__isnull=False).values('store_set').annotate(count=Count('store_set')).order_by('-count')\n"
},
{
"answer_id": 74500547,
"author": "Swift",
"author_id": 8874154,
"author_profile": "https://Stackoverflow.com/users/8874154",
"pm_score": 0,
"selected": false,
"text": "Q Count Count Store.objects.filter(filter).annotate(\n books_count=Count(\"books\")\n).order_by('-books_count')\n"
},
{
"answer_id": 74500957,
"author": "Yery cs",
"author_id": 11934228,
"author_profile": "https://Stackoverflow.com/users/11934228",
"pm_score": 2,
"selected": true,
"text": "books_count = (\n Book.objects.filter(\n store=OuterRef(\"pk\"),\n author__isnull=False,\n )\n .annotate(count=Func(F(\"id\"), function=\"COUNT\"))\n .values(\"count\")\n)\nStore.objects.annotate(count=Subquery(books_count)).order_by(\"-count\")\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15535644/"
] |
74,498,926
|
<p>I have this array ( I displayed it with function dd() ), with multiple data, and I want to display only "name" data in input field.</p>
<p><a href="https://i.stack.imgur.com/FwNgy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FwNgy.png" alt="enter image description here" /></a></p>
<p>That's how is looking now</p>
<p><a href="https://i.stack.imgur.com/ubEyh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ubEyh.png" alt="enter image description here" /></a></p>
<p>And how I want to be displayed names.</p>
<p><a href="https://i.stack.imgur.com/4Az91.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4Az91.png" alt="enter image description here" /></a></p>
<p>That's my function from Controller that I push data to page.</p>
<pre class="lang-php prettyprint-override"><code> private function needs()
{
$grades = Grade::all()->pluck('name', 'id')->toArray();
$subjects = Subject::all()->pluck('name', 'id')->toArray();
$students = User::students()->get()->pluck('name', 'id')->toArray();
$teachers = User::teachers()->get()->pluck('name', 'id')->toArray();
$goals = Goal::all()->pluck('name', 'id')->toArray();
$statuses = Status::all()->pluck('name', 'id')->toArray();
$formats = Format::all()->map->only(['id', 'name', 'students'])->values()->toArray();
return compact('grades', 'subjects', 'students', 'teachers', 'goals', 'statuses', 'formats');
}
</code></pre>
<p>And there is form from the page :</p>
<pre class="lang-php prettyprint-override"><code><div class="form-group">
{{ Form::label('format_id', 'Формат', ['class' => 'col-sm-3 control-label no-padding-right']) }}
<div class="col-sm-8">
{{ Form::select('format_id', [null => '--не выбран--'] + $formats, $data->format_id ?? 0, ['class' => 'form-control', 'id' => 'format_id']) }}
</div>
</div>
</code></pre>
|
[
{
"answer_id": 74498981,
"author": "lucutzu33",
"author_id": 8770336,
"author_profile": "https://Stackoverflow.com/users/8770336",
"pm_score": 1,
"selected": false,
"text": "Book.objects.filter(author__isnull=False).values('store_set').annotate(count=Count('store_set')).order_by('-count')\n"
},
{
"answer_id": 74500547,
"author": "Swift",
"author_id": 8874154,
"author_profile": "https://Stackoverflow.com/users/8874154",
"pm_score": 0,
"selected": false,
"text": "Q Count Count Store.objects.filter(filter).annotate(\n books_count=Count(\"books\")\n).order_by('-books_count')\n"
},
{
"answer_id": 74500957,
"author": "Yery cs",
"author_id": 11934228,
"author_profile": "https://Stackoverflow.com/users/11934228",
"pm_score": 2,
"selected": true,
"text": "books_count = (\n Book.objects.filter(\n store=OuterRef(\"pk\"),\n author__isnull=False,\n )\n .annotate(count=Func(F(\"id\"), function=\"COUNT\"))\n .values(\"count\")\n)\nStore.objects.annotate(count=Subquery(books_count)).order_by(\"-count\")\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16320462/"
] |
74,498,934
|
<p>(For example, I have a <code>Detailpage</code> with Similar products have the same <code>Detailpage</code> info(Nested navigation to same ).. how do we navigate to that page in Getx navigation or material route......and when the back button click we navigate to previous pages how do to do like that?)
<code>flutter</code></p>
<pre><code>class DetailPage extends StatefulWidget { final String redirectScreen; const DetailPage({super.key, required this.redirectScreen});
@override State<DetailPage> createState() => _DetailPageState(); }
class _DetailPageState extends State<DetailPage> { DetailPageController detailPageController = Get.put(DetailPageController()); late ThemeData themeData; @override void initState() {
super.initState();
detailPageController.fetchDetailPageScreen(
redirectScreen: widget.redirectScreen); } @override Widget build(BuildContext context) {
themeData = Theme.of(context);
return Scaffold(
appBar: AppBar(
backgroundColor: themeData.colorScheme.onSecondary,
title: Text(
'Detail Page',
style: AppTheme.getTextStyle(
themeData.textTheme.headline1!,
fontSize: MySize.s25,
fontWeight: 400,
color: themeData.colorScheme.primary,
),
),
),
body: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: [
HorizontalList(
padding: EdgeInsets.only(left: MySize.s10!, right: MySize.s10!),
itemCount: detailPageController.similarProducts.length,
itemBuilder: ((context, index) {
HomeProducts model = detailPageController.similarProducts[index];
return MainProductCard(
onTap: () {
Get.to(
DetailPage (
redirectScreen: model.redirectApi!,
),
popGesture: true,
preventDuplicates: false,
);
},
productOptions: model.productOptions!,
textfieldKG: model.productOptions!.isEmpty?false :true,
imagePath: model.image!,
productName: model.productName!,
strikePrice: model.strikePrice!,
sellingPrice: model.sellingPrice!,
savePercent: model.savePercentage!,
akshyamPrice: model.akshyamPrice!,
);
}),
),
],
),
); }; };
``
</code></pre>
|
[
{
"answer_id": 74501309,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "Getx Get.to(YourWidgetScreen()),\n Get.off(YourWidgetScreen()),\n Get.offAll(YourWidgetScreen()),\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17986144/"
] |
74,498,947
|
<p>I am making a "Wordle" type of game in Python and wanted to remove the last letters you wrote when you press backspace and it worked in most cases but I have a problem if your word has the letter that are the same for example "start".</p>
<p>I tried using the <code>.replace()</code> function like this:</p>
<pre><code>word = 'start'
new_word = word.replace(word[4], '', 1)
print(new_word)
</code></pre>
<p>But the result isn't <code>'star'</code>, but rather <code>'sart'</code>.
As you see it replaces the first 't' and not the last.
Does anyone know how to replace the last <code>'t'</code> but the solution needs to work on any case, like in <code>'aaaaa'</code> it just needs to replace the last <code>'a'</code>?</p>
|
[
{
"answer_id": 74501309,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "Getx Get.to(YourWidgetScreen()),\n Get.off(YourWidgetScreen()),\n Get.offAll(YourWidgetScreen()),\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20511732/"
] |
74,498,955
|
<p>I have a question and answer related to the Object oriented concept and I need help to understand the answer.
Below is an example where I have 2 classes 'Student' and 'Course'. I dont need code just the concept of how object model works.</p>
<p><img src="https://i.stack.imgur.com/BS5O7.jpg" alt="classes relation diagram" /></p>
<p>Question: How would I get all the titles of the courses a student is taking?</p>
<p>Answer: From Student, I would traverse the relationship to Course and when I get to the Course I return the title of the Courses.</p>
<p>What does it mean to traverse the relationship? Doesn it mean to create List of objects of Student class inside Course class?</p>
|
[
{
"answer_id": 74501309,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "Getx Get.to(YourWidgetScreen()),\n Get.off(YourWidgetScreen()),\n Get.offAll(YourWidgetScreen()),\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18484038/"
] |
74,498,958
|
<p>I'm trying to delete an item from a fetched data from API, but whenever I try to press on delete button I got this error:</p>
<pre><code>App.js:50 DELETE https://-api.herokuapp.com/api/products/%7Bid%7D 404 (Not Found)
</code></pre>
<p>Here is my code:</p>
<pre class="lang-js prettyprint-override"><code>const deleteProduct = async (id) => {
await fetch(
`https://upayments-studycase-api.herokuapp.com/api/products/{id}`,
{ method: "DELETE" }
);
setProdcts(products.filter((product) => product.id !== id));
};
return(
<div key={product.id}>
<div>
<div>
<FaTimes
onClick={() => onDelete(product.id)}
/>
<p>{product. Price}</p>{" "}
</div>
)
</code></pre>
<p>a photo of the error:</p>
<p><a href="https://i.stack.imgur.com/keuI8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/keuI8.png" alt="enter image description here" /></a></p>
<p>the code is in <a href="https://codesandbox.io/s/little-wave-quiliu?file=/src/App.js" rel="nofollow noreferrer">sandbox code</a>
So what happens after clicking on the delete sign it deleted all the items from the page, and then it re-loaded them.</p>
<p>I want to delete a specific item from the data.</p>
|
[
{
"answer_id": 74498976,
"author": "rocambille",
"author_id": 6612932,
"author_profile": "https://Stackoverflow.com/users/6612932",
"pm_score": 1,
"selected": false,
"text": "$ id `https://upayments-studycase-api.herokuapp.com/api/products/${id}`\n"
},
{
"answer_id": 74500149,
"author": "Mohamed CHIBANI",
"author_id": 8808725,
"author_profile": "https://Stackoverflow.com/users/8808725",
"pm_score": 0,
"selected": false,
"text": "backticks"
},
{
"answer_id": 74500387,
"author": "Mohamed CHIBANI",
"author_id": 8808725,
"author_profile": "https://Stackoverflow.com/users/8808725",
"pm_score": 0,
"selected": false,
"text": "const deleteProduct = async (id) => { \n await fetch(\n `upayments-studycase-api.herokuapp.com/api/products/${id}`, \n { method: \"DELETE\" }\n )\n .then(() => { \n return setProducts(products.filter(product => product.id !== id)) \n }) \n}; \n"
},
{
"answer_id": 74501486,
"author": "Maniraj Murugan",
"author_id": 7785337,
"author_profile": "https://Stackoverflow.com/users/7785337",
"pm_score": 2,
"selected": true,
"text": "${id} https://upayments-studycase-api.herokuapp.com/api/products/${id} id _id id"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15208666/"
] |
74,498,961
|
<p>I would like to fit several subplot inside an A4 figure.</p>
<p>With this code I have unwanted white gap. How can I remove them (see figure). Thanks</p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
gs1 = gridspec.GridSpec(8, 2)
gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes.
plt.figure(figsize=(11.69,8.27)) # for landscape
colors=['c','m','y','k','b','g','r','w']
for i in range(16):
ax = plt.subplot(gs1[i])
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.tick_params(left = False, bottom = False)
ax.set_facecolor(colors[i%8])
plt.savefig("toto.png")
</code></pre>
<p><a href="https://i.stack.imgur.com/Vbvlr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vbvlr.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74500788,
"author": "Joao_PS",
"author_id": 20262902,
"author_profile": "https://Stackoverflow.com/users/20262902",
"pm_score": 2,
"selected": true,
"text": "import matplotlib.pyplot as plt\n\ngridspec_kw = {'wspace':0.025, 'hspace':0.05}\n\nfig, ax = plt.subplots(8, 2, \n figsize=(11.69,8.27), \n gridspec_kw=gridspec_kw,\n layout=\"constrained\")\n\ncolors = ['c', 'm', 'y', 'k', 'b', 'g', 'r', 'w']\n\nfor i in range(8):\n\n # left subplot\n ax[i, 0].set_xticklabels([])\n ax[i, 0].set_yticklabels([])\n ax[i, 0].tick_params(left=False, bottom=False)\n ax[i, 0].set_facecolor(colors[(2*i)%8])\n\n # right subplot \n ax[i, 1].set_xticklabels([])\n ax[i, 1].set_yticklabels([])\n ax[i, 1].tick_params(left=False, bottom=False)\n ax[i, 1].set_facecolor(colors[(2*i)%8+1])\n\nplt.savefig(\"toto_stack_overflow.png\")\n"
},
{
"answer_id": 74500878,
"author": "Tranbi",
"author_id": 13525512,
"author_profile": "https://Stackoverflow.com/users/13525512",
"pm_score": 0,
"selected": false,
"text": "fig = plt.figure(figsize=(11.69,8.27)) # for landscape\nfig.subplots_adjust(bottom=0, top=1, left=0, right=1)\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4730164/"
] |
74,498,977
|
<p>I have a few strings, like:</p>
<pre><code>address1 = 'Красноярский край, г Красноярск, ул Академика Вавилова, 2Д, кв. 311'
address2 = 'Москва г, ул Ольховская, 45 стр. 1, квартира 3'
address3 = 'Красноярский край, г Красноярск, ул Академика Вавилова, 2Д, квартира 311'
</code></pre>
<p>So I need to cut that piece of string, which start from <strong>кв</strong>.
I use regular expression and this my code:</p>
<pre><code>import re
flat_template = r"кв(.*)$"
flat1 = re.search(flat_template, address1)
flat2 = re.search(flat_template, address2)
flat3 = re.search(flat_template, address3)
cut_flat1 = addresses[flat.start():flat.end()]
cut_flat2 = addresses[flat.start():flat.end()]
cut_flat3 = addresses[flat.start():flat.end()]
Output:
cut_flat1 = 'кв. 311'
cut_flat2 = 'ква г, ул Ольховская, 45 стр. 1, квартира 3'
cut_flat3 = 'квартира 311'
</code></pre>
<p>But I want to get:</p>
<pre><code>cut_flat1 = 'кв. 311'
cut_flat2 = 'квартира 3'
cut_flat3 = 'квартира 311'
</code></pre>
<p>All what I want to is search from end of string</p>
|
[
{
"answer_id": 74499010,
"author": "9769953",
"author_id": 9769953,
"author_profile": "https://Stackoverflow.com/users/9769953",
"pm_score": 1,
"selected": false,
"text": "flat_template = r\"кв(.*?)$\"\n .*? .* '\\b' flat_template = r\"\\bкв(.*?)$\"\n"
},
{
"answer_id": 74499393,
"author": "AidarDzhumagulov",
"author_id": 17436464,
"author_profile": "https://Stackoverflow.com/users/17436464",
"pm_score": 0,
"selected": false,
"text": "flat_template = r\" кв(.*?)$\"\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17436464/"
] |
74,498,986
|
<p>I made my first Pull request from the master branch which is reviewed but not merged yet.
Now I tried making a second Pull Request by making a new branch. But the problem I am facing is that this second Pull Request is showing the commits of the first Pull Request as well. I do not want to have previous commits in this Pull Request</p>
<p>Can anyone please suggest a way so that I can make this second PR having only the commits I made for this PR.</p>
|
[
{
"answer_id": 74499010,
"author": "9769953",
"author_id": 9769953,
"author_profile": "https://Stackoverflow.com/users/9769953",
"pm_score": 1,
"selected": false,
"text": "flat_template = r\"кв(.*?)$\"\n .*? .* '\\b' flat_template = r\"\\bкв(.*?)$\"\n"
},
{
"answer_id": 74499393,
"author": "AidarDzhumagulov",
"author_id": 17436464,
"author_profile": "https://Stackoverflow.com/users/17436464",
"pm_score": 0,
"selected": false,
"text": "flat_template = r\" кв(.*?)$\"\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12878000/"
] |
74,498,991
|
<p>I am trying to convert this dataset: <a href="http://promise.site.uottawa.ca/SERepository/datasets/cocomo81.arff" rel="nofollow noreferrer">COCOMO81</a> to arff.</p>
<p>Before converting to .arff, I am trying to convert it to .csv</p>
<p>I am following <a href="https://datatofish.com/convert-text-file-to-csv-using-python-tool-included/" rel="nofollow noreferrer">this LINK</a> to do this.</p>
<p>I got that dataset from promise site. I copied the entire page to notepad as cocomo81.txt and now I am trying to convert that cocomo81.txt file to .csv using python.
(I intend to convert the .csv file to .arff later using weka)</p>
<p>However, when I run</p>
<pre><code>import pandas as pd
read_file = pd.read_csv(r"cocomo81.txt")
</code></pre>
<p>I get <a href="https://pastebin.com/LAft3j9p" rel="nofollow noreferrer">THIS </a> ParserError.</p>
<p>To fix this, I followed <a href="https://stackoverflow.com/a/69554955/14613817">this solution</a> and modified my command to</p>
<p><code>read_file = pd.read_csv(r"cocomo81.txt",on_bad_lines='warn')</code></p>
<p>I got a bunch of warnings - you can see what it looks like <a href="https://pastebin.com/rj1CRviE" rel="nofollow noreferrer">here</a></p>
<p>and then I ran
<code>read_file.to_csv(r'.\cocomo81csv.csv',index=None)</code></p>
<p>But it seems that the fix for ParserError didn't work in my case because my cocomo81csv.csv file looks like <a href="https://pastebin.com/sbE9dESY" rel="nofollow noreferrer">THIS</a> in Excel.</p>
<p>Can someone please help me understand where I am going wrong and how can I use datasets from the promise repository in .arff format?</p>
|
[
{
"answer_id": 74499010,
"author": "9769953",
"author_id": 9769953,
"author_profile": "https://Stackoverflow.com/users/9769953",
"pm_score": 1,
"selected": false,
"text": "flat_template = r\"кв(.*?)$\"\n .*? .* '\\b' flat_template = r\"\\bкв(.*?)$\"\n"
},
{
"answer_id": 74499393,
"author": "AidarDzhumagulov",
"author_id": 17436464,
"author_profile": "https://Stackoverflow.com/users/17436464",
"pm_score": 0,
"selected": false,
"text": "flat_template = r\" кв(.*?)$\"\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14613817/"
] |
74,498,996
|
<p>I am writing an app that has a lot of images (about 200) which are different items that you can select and order. So far I have been using Glide to load the images from file. To support different resolutions, I made a image of the item with my smartphone and converted them into the 5 different Android resolutions in the folders drawable-mdpi, drawable-hdpi, drawable-xhdpi, drawable-xxhdpi and drawable-xxxhdpi.</p>
<p>The problem is that the original image has as size of 4,2 MB and all 5 images together just for one item for the different resolutions have a size of 18 MB (0,7 MB, 1,5 MB, 2,5 MB, 5,6 MB and 7,8 MB). If I now do this for 200 images, I will have to store 3,6 GB of images within the app. Thus, the size of the app would be extremely big.</p>
<p>So I would like to know what is a good way of dealing with so many images in an app? Is there a way to include multiple images for different resolutions while still having an app whose size is not enormous?</p>
|
[
{
"answer_id": 74508014,
"author": "CommonsWare",
"author_id": 115145,
"author_profile": "https://Stackoverflow.com/users/115145",
"pm_score": 0,
"selected": false,
"text": "res/drawable-anydpi/"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74498996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9437740/"
] |
74,499,004
|
<p>I'm making a website with a search function using select dropdown and am having a hard time. I want the web to be able to search for both model and group name at the same time or maybe just search for model/groupname.</p>
<p>I tried some ways but it didn't work.Because I'm new to programming, my knowledge is still poor, so I hope everyone can help me with my mistake or can keep me a code with similar content for reference. Thank you very much.</p>
<p>Code is:</p>
<pre><code><?php
include '../includes/dbconnection.php';
$sql = "SELECT *
FROM SFISM4.R_STATION_ATE_T
WHERE WORK_DATE= TO_CHAR(SYSDATE, 'YYYYMMDD') ";
try{
$params = [];
if(isset($_GET['model'], $_GET['group']) && $_GET['model'] && $_GET['group']){
$sql = $sql. 'AND MODEL_NAME=:MODEL_NAME '.'AND GROUP_NAME=:GROUP_NAME';
$params= [
'MODEL_NAME' => $_GET['model'],
'GROUP_NAME' => $_GET['group']
];
}
$stm = $db->prepare($sql);
$stm->execute($params);
$result = $stm->fetchAll(PDO::FETCH_ASSOC);
}catch(PDOException $e){
echo $e->getMessage();
}
try{
$stm = $db->prepare('SELECT DISTINCT MODEL_NAME FROM SFISM4.R_STATION_ATE_T ');
$stm->execute();
$result_model = $stm->fetchAll(PDO::FETCH_OBJ);
}catch(PDOException $e){
echo $e->getMessage();
}
try{
$stm = $db->prepare('SELECT DISTINCT GROUP_NAME FROM SFISM4.R_STATION_ATE_T');
$stm->execute();
$result_group = $stm->fetchAll(PDO::FETCH_OBJ);
}catch(PDOException $e){
echo $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Station Detail</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body >
<div class="container" >
<div class="row">
<div class="col-sm-12">
<div class="well" style="background-color:LightGray;">
<h2 class="text-center">Station Details</h2>
</div>
<form method="get">
<select name="model" id="model" style="">
<option value="">- MODEL_NAME -</option>
<?php foreach($result_model as $key => $value):?>
<option value="<?=$value->MODEL_NAME?>" <?= (isset($_GET['model']) && $_GET['model'] == $value->MODEL_NAME) ? 'selected' : '' ?>><?=$value->MODEL_NAME?></option>
<?php endforeach; ?>
</select>
<select name="group" id="group">
<option value="">- GROUP_NAME -</option>
<?php foreach($result_group as $key => $value):?>
<option value="<?=$value->GROUP_NAME?>" <?= (isset($_GET['group']) && $_GET['group'] == $value->GROUP_NAME) ? 'selected' : '' ?>><?=$value->GROUP_NAME?></option>
<?php endforeach; ?>
</select>
<button class="btn btn-success btn-primary" type="submit" name="filter" id="filter" style="">
<i class="fa fa-filter"></i> Filter
</button>
</form>
<br/><br/>
<table class="table table-hover table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>MODEL_NAME</th>
<th>GROUP_NAME</th>
<th>STATION_NAME</th>
<th>WORK_DATE</th>
<th>PASS_QTY</th>
<th>FAIL_QTY</th>
</tr>
<?php
foreach($result as $key => $value):
?>
<tr>
<td> <?php echo $value['MODEL_NAME']?></td>
<td> <?php echo $value['GROUP_NAME']; ?>
<td> <?=$value['STATION_NAME']; ?>
<td> <?=$value['WORK_DATE']; ?>
<td> <?=$value['PASS_QTY']; ?>
<td> <?=$value['FAIL_QTY'] ?>
</tr>
<?php endforeach; ?>
</thead>
</table>
</div>
</div>
</div>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 74499104,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 0,
"selected": false,
"text": "select * \nfrom sfism4.r_station_ate_t\nwhere work_date= to_char(sysdate, 'YYYYMMDD')\n and (model_name = :model_name or :model_name is null)\n and (group_name = :group_name or :group_name is null)\n"
},
{
"answer_id": 74500272,
"author": "Ken Lee",
"author_id": 11854986,
"author_profile": "https://Stackoverflow.com/users/11854986",
"pm_score": 2,
"selected": true,
"text": "$sql $params $params = [];\n if(isset($_GET['model'], $_GET['group']) && $_GET['model'] && $_GET['group']){\n $sql = $sql. 'AND MODEL_NAME=:MODEL_NAME '.'AND GROUP_NAME=:GROUP_NAME';\n $params= [\n 'MODEL_NAME' => $_GET['model'],\n 'GROUP_NAME' => $_GET['group']\n ];\n }\n \n$model=\"\";\n$group=\"\";\n\nif(isset($_GET['model'])){\n $model=$_GET[\"model\"];\n}\n\nif(isset($_GET['group'])){\n $group=$_GET[\"group\"];\n}\n\n $params = [];\n\n if(isset($model) && $model!=\"\"){ \n $sql = $sql. ' AND MODEL_NAME=:MODEL_NAME ' ;\n $params['MODEL_NAME']=$model;\n }\n\n if(isset($group) && $group!=\"\"){ \n $sql = $sql. ' AND GROUP_NAME=:GROUP_NAME ' ;\n $params['GROUP_NAME']=$group;\n }\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20423901/"
] |
74,499,017
|
<p>I have a list with a drop down menu and each selection effects multiple variables.
is there any way to refine it down? here is a snippet:</p>
<pre><code>if (selectedLeft == 'item 1')
row1Vis = false;
if (selectedLeft == 'item 1')
leftCounter = false;
if (selectedLeft == 'item 1')
leftNA = true;
</code></pre>
<p>is it possible to have it something like,
if (selectedLeft == 'item 1')
row1Vis = false, leftCounter = false, leftNA = true;</p>
<p>so i don't have to write out if (selectedLeft == 'item 1') 3 times.</p>
<p>cheers</p>
|
[
{
"answer_id": 74499054,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 1,
"selected": false,
"text": "(){...} if (selectedLeft == 'item 1') {\n row1Vis = false;\n leftCounter = false;\n leftNA = true;\n}\n"
},
{
"answer_id": 74499647,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 1,
"selected": true,
"text": "if && || && AND || OR if(selectedLeft == 'item 1' && selectRight == 'item 2') {\n row1Vis = false;\n leftCounter = false; \n leftNA = true; \n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373623/"
] |
74,499,023
|
<p>I have a dataframe that looks something like:</p>
<pre><code>IndexMonth Cus1 Cus2 Cus3 Cus4 ........ Cusn
2019-01 0 111 0 0 333
2019-02 0 111 0 666 0
2019-03 500 0 333 55 0
2019-04 600 0 333 111 0
2019-05 600 100 0 111 0
</code></pre>
<p>I am looking to fetch the first non zero month for each Cus column, and also the last non-zero month. If the Cus has a break and it starts again, i want to have the new start also added in the start column.
So my output should look something like :</p>
<pre><code> StartMonth EndMonth
Cus1 2019-03 2019-05
Cus2 2019-01,2019-05 2019-02,2019-05
Cus3 2019-03 2019-04
Cus4 2019-02 2019-05
..
Cusn 2019-01 2019-01
</code></pre>
<p>Could you please confirm how efficiently i can achieve this.</p>
|
[
{
"answer_id": 74500359,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 1,
"selected": false,
"text": "df2=df.T\ndf2['first']=df2.ne(0).idxmax(axis=1)\ndf2['last']=df2[df2.columns[0:5]].mask(df2==0).apply(pd.Series.last_valid_index, axis=1)\n#You should set the numbers 0 and 5 according to the number of columns. Here I am only getting the month columns.\n\nprint(df2)\n'''\nIndexMonth 2019-01 2019-02 2019-03 2019-04 2019-05 first last\nCus1 0 0 500 600 600 2019-03 2019-05\nCus2 111 111 0 0 100 2019-01 2019-05\nCus3 0 0 333 333 0 2019-03 2019-04\nCus4 0 666 55 111 111 2019-02 2019-05\nCusn 333 0 0 0 0 2019-01 2019-01\n'''\n df2['check']=False\nfor i in range (0,len(df2.index)):\n col_name=df2['first'][i] #which columns is the first ?\n if len(df2.iloc[i].loc[lambda x : x == df2[col_name][i]]) >= 2: #if there is more than one of the same value\n\n df2['check'][i]=True #return true and fill the first first value with 0. To be able to get the latter when using idxmax.\n\n df2[col_name][i]=0\ndf2['first_2']=df2.ne(0).idxmax(axis=1)\ndf2['is_combine']=(df2['check']==True) & (df2['last'] != df2['first_2'])\ndf2['StartMonth']=np.where(df2['is_combine']==True,(df2['first'] +', '+df2['last']),df2['first'])\ndf2['EndMonth']=np.where(df2['is_combine']==True,(df2['first_2'] +', '+df2['last']),df2['last'])\ndf2=df2[['StartMonth','EndMonth']]\nprint(df2)\n'''\nIndexMonth StartMonth EndMonth\nCus1 2019-03 2019-05\nCus2 2019-01, 2019-05 2019-02, 2019-05\nCus3 2019-03 2019-04\nCus4 2019-02 2019-05\nCusn 2019-01 2019-01\n'''\n"
},
{
"answer_id": 74500452,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "df2 = df.set_index('IndexMonth')\nm = df2.ne(0)\n\nstart = (df2\n .where(m&~m.shift(fill_value=False))\n .stack()\n .reset_index('IndexMonth')\n .groupby(level=0)['IndexMonth']\n .agg(','.join)\n .rename('StartMonth')\n )\n\nend = (df2\n .where(m&~m.shift(-1, fill_value=False))\n .stack()\n .reset_index('IndexMonth')\n .groupby(level=0)['IndexMonth']\n .agg(','.join)\n .rename('EndMonth')\n )\n\nout = pd.concat([start, end], axis=1)\n\nprint(out)\n StartMonth EndMonth\nCus1 2019-03 2019-05\nCus2 2019-01,2019-05 2019-02,2019-05\nCus3 2019-03 2019-04\nCus4 2019-02 2019-05\nCusn 2019-01 2019-01\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9218680/"
] |
74,499,036
|
<p>This is a very simple problem where it reads file from a CSV with first column header as "title" and then counts how many times the title appears in side the dictionary. But I am not understanding in which step it is assigning the "title" to "titles" dictionary.</p>
<p>The code is:</p>
<pre><code>import csv
titles = {}
with open("movies.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
#title is defined here
title = row["title"].strip().upper()
if title in titles:
titles[title] = titles[title] + 1
else:
titles[title] = 1
</code></pre>
<p>If it is assigning inside the else block then why is my second code where I just want to assign values to the dictionary named "titles" and not count the number of times it appears, is not Working?:</p>
<pre><code>import csv
titles = {}
with open("movies.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
#title is defined here
title = row["title"].strip().upper()
if not title in titles:
titles[title]
print(titles[title])
Error: Key Value error
</code></pre>
|
[
{
"answer_id": 74499146,
"author": "DaPanda",
"author_id": 4342167,
"author_profile": "https://Stackoverflow.com/users/4342167",
"pm_score": 1,
"selected": false,
"text": "titles[title] titles[title]"
},
{
"answer_id": 74499169,
"author": "doctorlove",
"author_id": 1055118,
"author_profile": "https://Stackoverflow.com/users/1055118",
"pm_score": 1,
"selected": true,
"text": "titles titles[title] title titles[title] set import csv\n\ntitles = set()\n\nwith open(\"movies.csv\", \"r\") as file:\n reader = csv.DictReader(file)\n\n for row in reader:\n #title is defined here\n title = row[\"title\"].strip().upper()\n titles.add(title)\n \nprint(titles)\n add"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15072033/"
] |
74,499,046
|
<p>If i write for example a node express app, i have the opportunity to pass some env vars from the server configuration.</p>
<p>Is there an opportunity in SharePoint Online also?
As SharePoint Online is a managed service, there's imho no way to do so.</p>
<p>Is there possibly a workaround?</p>
<p>I stuck at creating any idea regarding this problem.</p>
<p>cheers Thomas</p>
|
[
{
"answer_id": 74499146,
"author": "DaPanda",
"author_id": 4342167,
"author_profile": "https://Stackoverflow.com/users/4342167",
"pm_score": 1,
"selected": false,
"text": "titles[title] titles[title]"
},
{
"answer_id": 74499169,
"author": "doctorlove",
"author_id": 1055118,
"author_profile": "https://Stackoverflow.com/users/1055118",
"pm_score": 1,
"selected": true,
"text": "titles titles[title] title titles[title] set import csv\n\ntitles = set()\n\nwith open(\"movies.csv\", \"r\") as file:\n reader = csv.DictReader(file)\n\n for row in reader:\n #title is defined here\n title = row[\"title\"].strip().upper()\n titles.add(title)\n \nprint(titles)\n add"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12386782/"
] |
74,499,073
|
<p>I have the following list of values: Numbers = [1,2,3,4].
Is it possible to create a dictionary with the same name as the values contained in the list?</p>
<p>Example: dictionary_1 = {}
dictionary_2 = {}
....
dictionary_Number.. {}</p>
<p>I would like to create these dictionaries automatically, without creating them manually, reading the numbers contained in the list</p>
|
[
{
"answer_id": 74499172,
"author": "Andreas Hauser",
"author_id": 13597432,
"author_profile": "https://Stackoverflow.com/users/13597432",
"pm_score": 0,
"selected": false,
"text": "Numbers = [1,2,3,4]\nNumbers_dict = dict.fromkeys(Numbers,\"dict_value\")\nprint(Numbers_dict)\n {'1': 'dict_value', '2': 'dict_value', '3': 'dict_value', '4': 'dict_value'}\n"
},
{
"answer_id": 74499204,
"author": "MUsmanTahir",
"author_id": 17729087,
"author_profile": "https://Stackoverflow.com/users/17729087",
"pm_score": 1,
"selected": false,
"text": "exec List = [1, 2,3]\nfor ele in List:\n dic = f\"Dictionary_{ele}\"\n exec(dic+\" = {}\")\nprint(Dictionary_1, Dictionary_2, Dictionary_3, sep='\\n') \n exec exec"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9590971/"
] |
74,499,103
|
<p>I am brand new at all of this and I am completely lost even after Googling, watching hours of youtube videos, and reading posts on this site for the past week.</p>
<p>I am using Jupyter notebook</p>
<p>I have a config file with my api keys it is called config.ipynb</p>
<p>I have a different file where I am trying to call?? (I am not sure if this is the correct terminology) my config file so that I can connect to the twitter API but I getting an attribute error</p>
<p>Here is my code</p>
<pre><code> import numpy as np
import pandas as pd
import tweepy as tw
import configparser
#Read info from the config file named config.ipynb
config = configparser.ConfigParser()
config.read(config.ipynb)
api_key = config[twitter][API_key]
print(api_key) #to test if I did this correctly`
</code></pre>
<pre><code>---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In [17], line 4
1 #Read info from the config file named config.ipynb
3 config = configparser.ConfigParser()
</code></pre>
<p>----> 4 config.read(config.ipynb)
5 api_key = config[twitter][API_key]</p>
<pre><code>AttributeError: 'ConfigParser' object has no attribute 'ipynb'
</code></pre>
<p>Thank you for your help</p>
<p>I corrected my mistake thank you.</p>
<p>After fixing my read() mistake I received a MissingSectionHeaderError.</p>
<pre><code>MissingSectionHeaderError: File contains no section headers.
file: 'config.ipynb', line: 1 '{\n'.
</code></pre>
<p>My header in my config file is [twitter] but that gives me a NameError and say [twitter] is not defined... I have updated this many times per readings but I always get the same error.</p>
<p>My config.ipynb file code is below:</p>
<pre><code>['twitter']
API_key = "" #key between the ""
API_secret = "" #key between the ""
Bearer_token = "" #key between the ""
Client_ID = "" #key between the ""
Client_Secret = "" #key between the ""
</code></pre>
<p>I have tried [twitter], ['twitter'], and ["twitter"] but all render a MissingSectionHeaderError:</p>
<p>Update - I have been able to call my config file and pull in my
keys. After doing so, I am being told I cannot authenticate.</p>
<p>Code below:</p>
<pre><code> import tweepy
import configparser
import os
# Define file path and make sure path is correct
file_name = "config.txt"
# Config file stored in the same directory as the script.
# Get currect working directory with os.getcwd()
file_path = os.path.join(os.getcwd(), file_name)
#print(file_path) # Confirm file path is correct.
File path is correct
# Read info from the config file named config.txt
config = configparser.ConfigParser()
config.read(file_path)
# Will raise KeyError if the file path is not correct
api_key = config["twitter"]["API_key"]
api_secret = config["twitter"]["API_secret"]
client_id = config["twitter"]["Client_ID"]
client_secret = config["twitter"]["Client_Secret"]
#print(api_key, api_secret, client_id, client_secret)
</code></pre>
<p>Prints all keys and they are correct</p>
<pre><code> #authentication
from tweepy.auth import OAuthHandler
auth = OAuthHandler("API_key", "API_secret")
auth.set_client_token = (client_id, client_secret)
api = tweepy.API(auth)
public_tweets = api.home_timeline() #all code above works,
this is the line that renders an error
print(public_tweets)
</code></pre>
<p>This is the error message I receive:</p>
<pre><code> Unauthorized Traceback (most
recent call last)
Cell In [61], line 9
5 auth.set_client_token = (client_id, client_secret)
7 api = tweepy.API(auth)
----> 9 public_tweets = api.home_timeline()
11 print(public_tweets)
File ~/opt/miniconda3/lib/python3.9/site-
packages/tweepy/api.py:33, in pagination.<locals>.decorator.
<locals>.wrapper(*args, **kwargs)
31 @functools.wraps(method)
32 def wrapper(*args, **kwargs):
---> 33 return method(*args, **kwargs)
File ~/opt/miniconda3/lib/python3.9/site-
packages/tweepy/api.py:46, in payload.<locals>.decorator.
<locals>.wrapper(*args, **kwargs)
44 kwargs['payload_list'] = payload_list
45 kwargs['payload_type'] = payload_type
---> 46 return method(*args, **kwargs)
File ~/opt/miniconda3/lib/python3.9/site-
packages/tweepy/api.py:494, in API.home_timeline(self,
**kwargs)
461 @pagination(mode='id')
462 @payload('status', list=True)
463 def home_timeline(self, **kwargs):
464 """home_timeline(*, count, since_id, max_id,
trim_user,
\
465 exclude_replies, include_entities)
466
(...)
492 https://developer.twitter.com/en/docs/twitter-
api/v1/tweets/timelines/api-reference/get-statuses-
home_timeline
493 """
--> 494 return self.request(
495 'GET', 'statuses/home_timeline',
endpoint_parameters=(
496 'count', 'since_id', 'max_id', 'trim_user',
'exclude_replies',
497 'include_entities'
498 ), **kwargs
499 )
File ~/opt/miniconda3/lib/python3.9/site-
packages/tweepy/api.py:263, in API.request(self, method,
endpoint, endpoint_parameters, params, headers,
json_payload,
parser, payload_list, payload_type, post_data, files,
require_auth, return_cursors, upload_api, use_cache,
**kwargs)
261 raise BadRequest(resp)
262 if resp.status_code == 401:
--> 263 raise Unauthorized(resp)
264 if resp.status_code == 403:
265 raise Forbidden(resp)
Unauthorized: 401 Unauthorized
32 - Could not authenticate you.
</code></pre>
<p>I am not sure why it is saying that it cannot authenticate me.
I only have one set of keys and one twitter dev account</p>
<p>Twitter states the following for a 401 error:</p>
<p>401</p>
<p>Unauthorized</p>
<p>V1.1 V2
There was a problem authenticating your request. This could be
due to missing or incorrect authentication credentials. This
may also be returned in other undefined circumstances.</p>
<p>Check that you are using the correct authentication method and
that your credentials are correct. The link provided no longer works and I don't know what I am doing to check my authentication methods and credentials are correct (I only have the one set of credentials so I am thinking that it is my authentication method...maybe??)</p>
|
[
{
"answer_id": 74499172,
"author": "Andreas Hauser",
"author_id": 13597432,
"author_profile": "https://Stackoverflow.com/users/13597432",
"pm_score": 0,
"selected": false,
"text": "Numbers = [1,2,3,4]\nNumbers_dict = dict.fromkeys(Numbers,\"dict_value\")\nprint(Numbers_dict)\n {'1': 'dict_value', '2': 'dict_value', '3': 'dict_value', '4': 'dict_value'}\n"
},
{
"answer_id": 74499204,
"author": "MUsmanTahir",
"author_id": 17729087,
"author_profile": "https://Stackoverflow.com/users/17729087",
"pm_score": 1,
"selected": false,
"text": "exec List = [1, 2,3]\nfor ele in List:\n dic = f\"Dictionary_{ele}\"\n exec(dic+\" = {}\")\nprint(Dictionary_1, Dictionary_2, Dictionary_3, sep='\\n') \n exec exec"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20546628/"
] |
74,499,117
|
<p>I am looking for the shortest way in terms of writing to declare an array of points.
My problem is that I have humongous point data that I want to hardcode as an initialization.</p>
<p>These initializations repeat the 'new Point' multiple times:</p>
<p><code>Point[] points1 = new[] { new Point { X = 0, Y = 0 }, new Point { X = 20, Y = 120 }, new Point { X = 40, Y = 60 }, }; // kinda long typing</code></p>
<p><code>Point[] points2 = { new Point(0, 0), new Point(20, 120), new Point(40, 60) }; // better</code></p>
<p>Alternatively I could declare the array like so:</p>
<p><code>int[,] arr = new int[,] { { 0, 0 }, { 20, 120 }, { 40, 60 } }; // so far shortest typing</code></p>
<p>But how can I cast int[,] to Point[] ?
Are there other alternatives (like using lists) ?</p>
|
[
{
"answer_id": 74499203,
"author": "Sweeper",
"author_id": 5133585,
"author_profile": "https://Stackoverflow.com/users/5133585",
"pm_score": 3,
"selected": true,
"text": "new[] new Point[] new Point[] points1 = new Point[] { \n new() { X = 0, Y = 0 }, \n new() { X = 20, Y = 120 },\n new() { X = 40, Y = 60 }, \n};\n Point Point[] points1 = new Point[] { \n new(0, 0),\n new(20, 120),\n new(40, 160)\n};\n points1 var points1 = new Point[] { \n new(0, 0),\n new(20, 120),\n new(40, 160)\n};\n (int, int)[] Point[] Point[] points1 = new[] { \n (0, 0),\n (20, 120),\n (40, 160)\n}.Select(x => new Point(x.Item1, x.Item2)).ToArray();\n"
},
{
"answer_id": 74499823,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 1,
"selected": false,
"text": "public class Point\n{\n public int X { get; set; }\n public int Y { get; set; }\n}\n\npublic class Root\n{\n public Point[] Points { get; set; }\n}\n\nstring json = File.ReadAllText(\"inut.json\");\nRoot obj = JsonConvert.DeserializeObject<Root>(json); //Use NewtonSoft.json library to deserialize the JSON to object.\n {\n \"Points\": [{\n \"X\": 0,\n \"Y\": 0\n },\n {\n \"X\": 10,\n \"Y\": 20\n }\n ]\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10360416/"
] |
74,499,119
|
<p>For example, I want to match all strings that contain the word 'cat' or 'dog' such as concatenation, doghouse, underdog, catastrophe, or endogamy. But I want to exclude the words dogs or cats from being matched. I tried this task using the following regex.</p>
<pre><code>\\w*(cat|dog)(s(?=\w+))*\
</code></pre>
<p>But this regex doesn't help me select whatever is after the s. Is there some other way to achieve this? Any help is appreciated.</p>
|
[
{
"answer_id": 74499203,
"author": "Sweeper",
"author_id": 5133585,
"author_profile": "https://Stackoverflow.com/users/5133585",
"pm_score": 3,
"selected": true,
"text": "new[] new Point[] new Point[] points1 = new Point[] { \n new() { X = 0, Y = 0 }, \n new() { X = 20, Y = 120 },\n new() { X = 40, Y = 60 }, \n};\n Point Point[] points1 = new Point[] { \n new(0, 0),\n new(20, 120),\n new(40, 160)\n};\n points1 var points1 = new Point[] { \n new(0, 0),\n new(20, 120),\n new(40, 160)\n};\n (int, int)[] Point[] Point[] points1 = new[] { \n (0, 0),\n (20, 120),\n (40, 160)\n}.Select(x => new Point(x.Item1, x.Item2)).ToArray();\n"
},
{
"answer_id": 74499823,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 1,
"selected": false,
"text": "public class Point\n{\n public int X { get; set; }\n public int Y { get; set; }\n}\n\npublic class Root\n{\n public Point[] Points { get; set; }\n}\n\nstring json = File.ReadAllText(\"inut.json\");\nRoot obj = JsonConvert.DeserializeObject<Root>(json); //Use NewtonSoft.json library to deserialize the JSON to object.\n {\n \"Points\": [{\n \"X\": 0,\n \"Y\": 0\n },\n {\n \"X\": 10,\n \"Y\": 20\n }\n ]\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9522270/"
] |
74,499,162
|
<p>As the title suggests I'm getting an error in the below code (related to the loop when trying to build.</p>
<pre><code>struct ContentView: View {
var testImages = ["Image1", "Image2", "Image3"].shuffled()
var body: some View {
VStack{
ForEach(0...2) { number in
Image(self.testImages[number])
}
}
}
}
</code></pre>
<p>Any help would be much appreciated.</p>
|
[
{
"answer_id": 74499198,
"author": "ScottM",
"author_id": 1326518,
"author_profile": "https://Stackoverflow.com/users/1326518",
"pm_score": 0,
"selected": false,
"text": "0...2 ClosedRange ForEach Range ..< ForEach(0..<3) { number in\n Image(self.testImages[number])\n}\n"
},
{
"answer_id": 74500634,
"author": "dibs",
"author_id": 6332286,
"author_profile": "https://Stackoverflow.com/users/6332286",
"pm_score": -1,
"selected": false,
"text": "ForEach(0..<Int(testImages.count), id:\\.self) { number in\n Image(self.testImages[number])\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15415385/"
] |
74,499,199
|
<p>I am working on a part of an indoor localization project. I need my Flutter application scan and get Mac addresses and RSSI values of Wifi and Bluetooth devices. I am using <a href="https://pub.dev/packages/flutter_blue" rel="nofollow noreferrer">flutter_blue</a> for bluetooth scans and <a href="https://pub.dev/packages/wifi_scan" rel="nofollow noreferrer">wifi_scan</a> for Wifi scans. The application works well while in the foreground but scans are failing when the application is in background.</p>
<p>What I have tried so far:</p>
<ul>
<li>Tried to change Bluetooth scan mode from <code>ScanMode.lowLatency</code> to <code>ScanMode.lowPower</code> and <code>ScanMode.opportunistic</code> for the <code>startScan()</code> method for <a href="https://pub.dev/packages/flutter_blue" rel="nofollow noreferrer">flutter_blue</a>.</li>
<li><a href="https://pub.dev/packages/flutter_background" rel="nofollow noreferrer">flutter_background</a>. I managed to do some tasks in background but wifi and bluetooth did not work.</li>
<li><a href="https://pub.dev/packages/flutter_background_service" rel="nofollow noreferrer">flutter_background_service</a> the same situation</li>
<li><a href="https://pub.dev/packages/flutter_foreground_plugin" rel="nofollow noreferrer">flutter_foreground_plugin</a> the same situation</li>
<li><a href="https://pub.dev/packages/flutter_foreground_task" rel="nofollow noreferrer">flutter_foreground_task</a> the same situation</li>
<li><a href="https://pub.dev/packages/workmanager" rel="nofollow noreferrer">workmanager</a> did not try it because it says it can trigger the bg operation per every 15 minutes but I am scanning per every 6 seconds.</li>
</ul>
<p>Is there any way to achieve this? Aren't there any package with the option <code>backgroundMode: true</code>? I don't know the natives. Don't know Kotlin too.</p>
|
[
{
"answer_id": 74521775,
"author": "TarHalda",
"author_id": 15170120,
"author_profile": "https://Stackoverflow.com/users/15170120",
"pm_score": 1,
"selected": false,
"text": "ScanMode.lowPower"
},
{
"answer_id": 74574598,
"author": "Baran",
"author_id": 20468293,
"author_profile": "https://Stackoverflow.com/users/20468293",
"pm_score": 1,
"selected": true,
"text": "location.enableBackgroundMode(enable: true)"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20468293/"
] |
74,499,211
|
<p>I have an ASP.NET Core 6 app using Automapper 12.0.0 and I defined a mapper profile where I map one class to two different ones:</p>
<pre><code>public class ModelMapper : AutoMapper.Profile
{
public ModelMapper()
{
CreateMap<A, B1>().ReverseMap();
CreateMap<A, B2>().ReverseMap();
}
}
</code></pre>
<p>And then:</p>
<pre><code>services.AddAutoMapper(typeof(ModelMapper));
</code></pre>
<p>When I try to map from B2 to A I get this error:</p>
<blockquote>
<p>AutoMapperMappingException: Missing type map configuration or unsupported mapping.</p>
<p>Mapping types: B2 -> A</p>
</blockquote>
<p>Is there a way to set up AutoMapper to be able to map from A to B1 and to B2 and also from B1 to A and from B2 to A ?</p>
|
[
{
"answer_id": 74521775,
"author": "TarHalda",
"author_id": 15170120,
"author_profile": "https://Stackoverflow.com/users/15170120",
"pm_score": 1,
"selected": false,
"text": "ScanMode.lowPower"
},
{
"answer_id": 74574598,
"author": "Baran",
"author_id": 20468293,
"author_profile": "https://Stackoverflow.com/users/20468293",
"pm_score": 1,
"selected": true,
"text": "location.enableBackgroundMode(enable: true)"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1116445/"
] |
74,499,215
|
<p>After Taking Numbers From Users e:g (1,2,3,4) how can I convert them into text e:g(One, Two, Three) Pardon if If not specific in my question</p>
<p>I Wanted tio use Switch but I Think I do need some Automation like if Someone type 1005 he'll get a return of one thousand and five</p>
|
[
{
"answer_id": 74521775,
"author": "TarHalda",
"author_id": 15170120,
"author_profile": "https://Stackoverflow.com/users/15170120",
"pm_score": 1,
"selected": false,
"text": "ScanMode.lowPower"
},
{
"answer_id": 74574598,
"author": "Baran",
"author_id": 20468293,
"author_profile": "https://Stackoverflow.com/users/20468293",
"pm_score": 1,
"selected": true,
"text": "location.enableBackgroundMode(enable: true)"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13904643/"
] |
74,499,225
|
<p>I'm trying to make a layout with a "page".
I would have 3 columns, 1st and 3th would use only 10% of the space, and the middle 80%. Until there no problem. But I would like that as soon as the middle part reach 64rem, it's only the first and last column that grow.</p>
<p>Currently I've tried this:
<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>.container {
display: grid;
grid-template-columns: 10% minmax(80%, 64rem) 10%;
grid-template-rows: min-content auto;
min-height: 100vh;
background-color: red;
}
.header {
grid-column-start: 2;
grid-column-end: 3;
grid-row-start: 1;
grid-row-end: 2;
background-color: blue;
}
.content {
grid-column-start: 2;
grid-column-end: 3;
grid-row-start: 2;
grid-row-end: 3;
background-color: yellow;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="header">
header
</div>
<div class="content">
content
</div>
</div></code></pre>
</div>
</div>
</p>
<p>But it doesn't stops at 64rem. Any idea how to adress this issue?</p>
|
[
{
"answer_id": 74521775,
"author": "TarHalda",
"author_id": 15170120,
"author_profile": "https://Stackoverflow.com/users/15170120",
"pm_score": 1,
"selected": false,
"text": "ScanMode.lowPower"
},
{
"answer_id": 74574598,
"author": "Baran",
"author_id": 20468293,
"author_profile": "https://Stackoverflow.com/users/20468293",
"pm_score": 1,
"selected": true,
"text": "location.enableBackgroundMode(enable: true)"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/397830/"
] |
74,499,273
|
<p>I wanted to read a phrase and a series of numbers/alphabetic separated by ",". I read the first string then I print it (works fine). I read the first string, read 62 of those series and try to print the first string again and is not working. I tried a lot of methods but none working.</p>
<pre><code> char text[1001];
scanf("%[^\n]", text);
for (int i = 1; i <= 62; i++) {
char alpha[3] = {0}, lit_orig, lit_replace;
scanf("%s", alpha);
lit_orig = alpha[0];
lit_replace = alpha[2];
}
printf("\n%s", text);
</code></pre>
<p>Input example:</p>
<pre><code>Example text here!
a,H b,j c,6 d,I e,2 f,R g,5 h,t i,h j,k k,m l,f m,D n,F o,1 p,0 q,c r,G s,n t,N u,e v,B w,r x,U y,p z,A A,8 B,X C,S D,P E,T F,a G,M H,d I,K J,L K,3 L,C M,i N,9 O,E P,w Q,o R,z S,4 T,O U,q V,V W,J X,x Y,Z Z,u 0,l 1,y 2,W 3,s 4,Q 5,g 6,v 7,7 8,b 9,Y
</code></pre>
<p>Output example: There is no output.</p>
<p>I did expect it to print just fine the first string called "text" but it is not working. I tried even clearing out the buffer using getchar() but no results (this is what other websites said it would work). Can you explain what is wrong with my code?</p>
|
[
{
"answer_id": 74499309,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": true,
"text": " lit_orig = alpha[0];\n lit_replace = alpha[2];\n 2 scanf scanf(\"%s\", alpha);\n '\\0' alpha text text alpha char alpha[4] = {0}, \n scanf scanf(\"%3s\", alpha);\n"
},
{
"answer_id": 74499367,
"author": "Yunnosch",
"author_id": 7733418,
"author_profile": "https://Stackoverflow.com/users/7733418",
"pm_score": 0,
"selected": false,
"text": "char alpha[5] printf (\"(%4s)\", alpha); alpha"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14336401/"
] |
74,499,347
|
<p>I have a list with strings and super script characters(as power).
I need to concatenate scripted values with strings.
But according to my coding part It repeating same value twice.
I have no idea to remove unnecessary values from the list.</p>
<p>my original list --></p>
<pre><code>separate_units = ['N', 'm', '⁻²⁴', 'kJ', 's', '⁻¹', 'km', '⁻²¹', 'kJ', '⁻²', 'm', '⁻²']
</code></pre>
<p>result according to my coding part --></p>
<pre><code>result = ['N', 'm', 'm⁻²⁴', 'kJ', 's', 's⁻¹', 'km', 'km⁻²¹', 'kJ', 'kJ⁻²', 'm', 'kJ⁻²']
</code></pre>
<p>I expected result --></p>
<pre><code> result = ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm', 'kJ⁻²']
</code></pre>
<p>I tried to delete last index when concatenate two items.But It gave me an error.</p>
<p>--> del (separating_units[(separate_units.index(su) - 1)]) # grab the last (index of unit) value to delete from the list.</p>
<p>Error coding part --></p>
<pre><code>def power_set_to_unit():
result = [su if su.isalpha() else del (separating_units[(separate_units.index(su) - 1)]) (separate_units[(separate_units.index(su) - 1)] + su) for su in separate_units]
print(result)
</code></pre>
<p><em>I prefer to do this in single line coding part.</em>
Please help me to do this...</p>
|
[
{
"answer_id": 74499446,
"author": "C-3PO",
"author_id": 4667669,
"author_profile": "https://Stackoverflow.com/users/4667669",
"pm_score": 3,
"selected": true,
"text": "power_set_to_unit result separate_units = ['N', 'm', '⁻²⁴', 'kJ', 's', '⁻¹', 'km', '⁻²¹', 'kJ', '⁻²', 'm', '⁻²']\n\ndef power_set_to_unit():\n result = []\n for x in separate_units:\n if x.isalpha():\n result.append(x)\n else:\n result[-1] += x\n return result\n\nprint(power_set_to_unit())\n# ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm⁻²']\n power_set_to_unit = lambda sep='\\n': ''.join((sep+x if x.isalpha() else x) for x in separate_units).split(sep)[1:]\nprint(power_set_to_unit())\n# ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm⁻²']\n"
},
{
"answer_id": 74499551,
"author": "Dmitri Chubarov",
"author_id": 1328439,
"author_profile": "https://Stackoverflow.com/users/1328439",
"pm_score": 1,
"selected": false,
"text": "zip separate_units = ['N', 'm', '⁻²⁴', 'kJ', 's', '⁻¹', 'km', '⁻²¹', 'kJ', '⁻²', 'm', '⁻²']\n\n[a if b.isalpha() else a + b for (a,b) in zip(separate_units[:-1], separate_units[1:]) if a.isalpha()]\n# should result in ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm⁻²']\n if for in string_list [x for x in string_list if x.isalpha()]\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18161524/"
] |
74,499,350
|
<p>I have a question listing page where I want to sort the data with the following for each question</p>
<p><strong>Requirement 1</strong></p>
<ul>
<li><p>Total Question attempted</p>
</li>
<li><p>Total Passed students</p>
</li>
<li><p>Passed students percentage</p>
</li>
</ul>
<p><strong>Requirement 2</strong></p>
<ul>
<li><p>Total Question attempted (for particular institute, Institute id is 20 in our case which we get by logged in user's Institute)</p>
</li>
<li><p>Total Passed students (for particular institute, Institute id is 20 in our case which we get by logged in user's Institute)</p>
</li>
<li><p>Passed students percentage (for particular institute, Institute id is 20 in our case which we get by logged in user's Institute)</p>
</li>
</ul>
<p>I have achieved "<strong>Requirement 1</strong>" but for the "<strong>Requirement 2</strong>" which is very similar to "<strong>Requirement 1</strong>" I forced to run 4 subqueries to find out below:</p>
<ul>
<li><p>total_students_facility</p>
</li>
<li><p>passed_students_facility</p>
</li>
<li><p>percentage_facility</p>
</li>
</ul>
<p>Which is making the query very slow for <strong>9M records</strong>. I wonder if I can achieve "<strong>Requirement 2</strong>" also with join and correct indexing.</p>
<p>Also I run two subquery again to calculate percentage as we cannot use ALIAS in calculation it shows unknown column. As we can just use ALIAS in "group by", "having", and "order by" any solution will be helpful.</p>
<p><a href="https://i.stack.imgur.com/dWNLn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dWNLn.png" alt="enter image description here" /></a></p>
<pre><code>
CREATE TABLE IF NOT EXISTS `mdl_question` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`category` bigint(20) NOT NULL DEFAULT 0,
`parent` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`name` text COLLATE utf8mb4_unicode_ci NOT NULL,
`questiontext` text COLLATE utf8mb4_unicode_ci NOT NULL,
`questiontextformat` tinyint(4) NOT NULL DEFAULT 0,
`generalfeedback` text COLLATE utf8mb4_unicode_ci NOT NULL,
`generalfeedbackformat` tinyint(4) NOT NULL DEFAULT 0,
`defaultmark` decimal(12,7) NOT NULL DEFAULT 1.0000000,
`penalty` decimal(12,7) NOT NULL DEFAULT 0.3333333,
`qtype` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '''1''',
`length` bigint(20) UNSIGNED NOT NULL DEFAULT 1,
`stamp` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`version` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`hidden` tinyint(3) UNSIGNED NOT NULL DEFAULT 0,
`timecreated` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`timemodified` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`createdby` bigint(20) UNSIGNED DEFAULT NULL,
`modifiedby` bigint(20) UNSIGNED DEFAULT NULL,
`type_data_id` bigint(20) NOT NULL,
`img_id` bigint(20) DEFAULT NULL,
`qimg_gallary_text` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`qrimg_gallary_text` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`qimg_gallary_ids` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`qrimg_gallary_ids` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`case_id` bigint(20) NOT NULL DEFAULT 0,
`ques_type_id` bigint(20) DEFAULT NULL,
`year` bigint(20) DEFAULT NULL,
`spec` bigint(20) DEFAULT NULL,
`sub_speciality_id` int(11) DEFAULT NULL,
`sub_sub_speciality_id` int(11) DEFAULT NULL,
`spec_level` bigint(20) DEFAULT 1,
`is_deleted` int(11) NOT NULL DEFAULT 0,
`sequence` int(11) NOT NULL DEFAULT 0,
`sort_order` bigint(20) NOT NULL DEFAULT 0 COMMENT 'Question order in list',
`idnumber` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`addendum` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`text_for_search` longtext COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'this is for the text based searching, this will store the text of the question without html tags',
`text_for_search_ans` longtext COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `type_data_id` (`type_data_id`),
UNIQUE KEY `mdl_ques_catidn_uix` (`category`,`idnumber`),
KEY `mdl_ques_cat_ix` (`category`),
KEY `mdl_ques_par_ix` (`parent`),
KEY `mdl_ques_cre_ix` (`createdby`),
KEY `mdl_ques_mod_ix` (`modifiedby`),
KEY `id` (`id`),
KEY `mq_spec_ix` (`spec`),
KEY `sort_order` (`sort_order`),
KEY `idx2` (`is_deleted`,`sort_order`,`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='The questions themselves';
CREATE TABLE IF NOT EXISTS `mdl_question_attempts` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`questionusageid` bigint(20) UNSIGNED NOT NULL,
`slot` bigint(20) UNSIGNED NOT NULL,
`behaviour` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`questionid` bigint(20) UNSIGNED NOT NULL,
`variant` bigint(20) UNSIGNED NOT NULL DEFAULT 1,
`maxmark` decimal(12,7) NOT NULL,
`minfraction` decimal(12,7) NOT NULL,
`flagged` tinyint(3) UNSIGNED NOT NULL DEFAULT 2,
`questionsummary` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`rightanswer` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`responsesummary` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`timemodified` bigint(20) UNSIGNED NOT NULL,
`maxfraction` decimal(12,7) DEFAULT 1.0000000,
`in_remind_state` int(11) NOT NULL DEFAULT 0,
`is_correct` tinyint(1) DEFAULT 1,
`institution_id` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `mdl_quesatte_queslo_uix` (`questionusageid`,`slot`),
KEY `mdl_quesatte_que2_ix` (`questionusageid`),
KEY `is_correct` (`is_correct`),
KEY `idx1` (`questionid`,`is_correct`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Each row here corresponds to an attempt at one question, as ';
COMMIT;
CREATE TABLE IF NOT EXISTS `mdl_quiz_attempts` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`uniqueid` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`quiz` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`userid` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`attempt` mediumint(9) NOT NULL DEFAULT 0,
`sumgrades` decimal(10,5) DEFAULT NULL,
`timestart` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`timefinish` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`timemodified` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`layout` text COLLATE utf8mb4_unicode_ci NOT NULL,
`preview` smallint(5) UNSIGNED NOT NULL DEFAULT 0,
`needsupgradetonewqe` smallint(5) UNSIGNED NOT NULL DEFAULT 0,
`comments` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`is_deleted` int(11) NOT NULL DEFAULT 0,
`groupname` text CHARACTER SET utf8mb3 DEFAULT NULL,
`pageid` int(11) DEFAULT 0,
`currentpage` bigint(20) DEFAULT 0,
`state` varchar(16) COLLATE utf8mb4_unicode_ci DEFAULT 'inprogress',
`timemodifiedoffline` bigint(20) NOT NULL DEFAULT 0,
`timecheckstate` bigint(20) DEFAULT 0,
`retake` int(11) NOT NULL DEFAULT 0,
`is_on_going` int(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `mdl_quizatte_uni_uix` (`uniqueid`),
KEY `mdl_quizatte_use_ix` (`userid`),
KEY `mdl_quizatte_qui_ix` (`quiz`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `mdl_user` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`auth` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'manual',
`confirmed` tinyint(1) NOT NULL DEFAULT 0,
`policyagreed` tinyint(1) NOT NULL DEFAULT 0,
`deleted` tinyint(1) NOT NULL DEFAULT 0,
`suspended` tinyint(1) NOT NULL DEFAULT 0,
`mnethostid` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`username` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`password` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`idnumber` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`firstname` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`lastname` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`recommend_email` tinyint(1) NOT NULL DEFAULT 0,
`emailstop` tinyint(3) UNSIGNED NOT NULL DEFAULT 0,
`icq` varchar(15) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`skype` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`yahoo` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`aim` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`msn` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`phone1` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`phone2` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`institution` varchar(40) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`department` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`address` varchar(70) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`city` varchar(120) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`country` varchar(2) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`lang` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'en',
`theme` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`timezone` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '99',
`firstaccess` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`lastaccess` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`lastlogin` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`currentlogin` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`lastip` varchar(45) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`secret` varchar(15) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`picture` tinyint(1) NOT NULL DEFAULT 0,
`url` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`description` longtext COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`descriptionformat` tinyint(3) UNSIGNED NOT NULL DEFAULT 0,
`mailformat` tinyint(3) UNSIGNED NOT NULL DEFAULT 1,
`maildigest` tinyint(3) UNSIGNED NOT NULL DEFAULT 0,
`maildisplay` tinyint(3) UNSIGNED NOT NULL DEFAULT 2,
`htmleditor` tinyint(3) UNSIGNED NOT NULL DEFAULT 1,
`ajax` tinyint(3) UNSIGNED NOT NULL DEFAULT 1,
`autosubscribe` tinyint(3) UNSIGNED NOT NULL DEFAULT 1,
`trackforums` tinyint(3) UNSIGNED NOT NULL DEFAULT 0,
`timecreated` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`timemodified` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`trustbitmask` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`imagealt` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`screenreader` tinyint(1) NOT NULL DEFAULT 0,
`furlastname` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`furfirstname` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`grade` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`group_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`jobtitle` varchar(250) COLLATE utf8mb4_unicode_ci NOT NULL,
`comment` text COLLATE utf8mb4_unicode_ci NOT NULL,
`actstatus` enum('1','0') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
`slearncount` int(11) NOT NULL DEFAULT 0,
`agrrement_status` tinyint(1) NOT NULL DEFAULT 0,
`excludesure` int(11) DEFAULT 0,
`calendartype` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'gregorian',
`lastnamephonetic` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`firstnamephonetic` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`middlename` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`alternatename` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`version` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`reviewertype` smallint(6) DEFAULT 0,
PRIMARY KEY (`id`),
KEY `mdl_user_del_ix` (`deleted`),
KEY `mdl_user_con_ix` (`confirmed`),
KEY `mdl_user_fir_ix` (`firstname`),
KEY `mdl_user_las_ix` (`lastname`),
KEY `mdl_user_cit_ix` (`city`),
KEY `mdl_user_cou_ix` (`country`),
KEY `mdl_user_las2_ix` (`lastaccess`),
KEY `mdl_user_ema_ix` (`email`),
KEY `mdl_user_aut_ix` (`auth`),
KEY `mdl_user_idn_ix` (`idnumber`),
KEY `mdl_user_fir2_ix` (`firstnamephonetic`),
KEY `mdl_user_las3_ix` (`lastnamephonetic`),
KEY `mdl_user_mid_ix` (`middlename`),
KEY `mdl_user_alt_ix` (`alternatename`),
KEY `mdl_user_institution_ix` (`institution`),
KEY `actstatus` (`actstatus`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='One record for each person';
CREATE TABLE IF NOT EXISTS `mdl_my_ques_type_data` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`question_id` bigint(20) DEFAULT NULL,
`ques_pref` int(11) DEFAULT NULL,
`ques_case` bigint(20) DEFAULT NULL,
`ques_type_id` bigint(20) DEFAULT NULL,
`year` bigint(20) DEFAULT NULL,
`spec` bigint(20) DEFAULT NULL,
`subspec` bigint(20) DEFAULT NULL,
`subsubspec` bigint(20) DEFAULT NULL,
`spec_level` bigint(20) NOT NULL,
`is_deleted` tinyint(4) NOT NULL DEFAULT 0,
`institute_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `question_id` (`question_id`),
KEY `id` (`id`),
KEY `ques_type_id` (`ques_type_id`),
KEY `ques_case` (`ques_case`),
KEY `spec` (`spec`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
CREATE TABLE IF NOT EXISTS `mdl_my_ques_attributes` (
`attrib_id` int(11) NOT NULL AUTO_INCREMENT,
`question` bigint(20) NOT NULL,
`related_question` varchar(250) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`keywords` varchar(250) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`explanation` mediumtext COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`ext_link` mediumtext COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`ext_link_txt` mediumtext COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`link_type` mediumtext COLLATE utf8mb4_unicode_ci NOT NULL,
`diff_id` int(11) DEFAULT NULL,
`shuffle` int(11) DEFAULT NULL,
`ownerid` int(11) DEFAULT NULL,
`creator_id` int(11) DEFAULT NULL,
`date_created` bigint(20) DEFAULT NULL,
`last_modified_id` int(11) DEFAULT NULL,
`last_modified_date` bigint(20) DEFAULT NULL,
`status` int(11) DEFAULT NULL,
`insti_id` bigint(20) NOT NULL DEFAULT 0,
`ques_type` int(11) NOT NULL,
`no_ques` bigint(20) NOT NULL DEFAULT 0,
`is_deleted` tinyint(4) NOT NULL DEFAULT 0,
`review_id` int(11) NOT NULL DEFAULT 1,
`land_id` int(11) NOT NULL DEFAULT 1,
`ques_label` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`exclude_self_learning` mediumtext COLLATE utf8mb4_unicode_ci NOT NULL,
`text_for_search` longtext COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'this is for the text based searching, this will store the text of the question without html tags',
PRIMARY KEY (`attrib_id`),
KEY `attrib_id` (`attrib_id`),
KEY `question` (`question`),
KEY `diff_id` (`diff_id`),
KEY `mqa_ques_type_ix` (`ques_type`),
KEY `mqa_insti_id_ix` (`insti_id`),
KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `specilities` (
`sp_id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`parent_id` int(11) DEFAULT NULL,
`percentage` float NOT NULL DEFAULT 0,
`color` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`order` bigint(20) NOT NULL DEFAULT 0,
`is_deleted` int(11) NOT NULL DEFAULT 0,
`institute_id` int(11) NOT NULL DEFAULT 0,
`sp_level` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`sp_id`),
KEY `sp_id` (`sp_id`),
KEY `mq_spec_parent_ix` (`parent_id`),
KEY `specilities_institute_id` (`institute_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
</code></pre>
<pre><code>select
mq.id, mq.ques_type_id, mq.qtype, mq.name, mq.qimg_gallary_ids,
qtd.question_id, qtd.year, qtd.spec, qtd.subspec, qtd.subsubspec,
qa.status, qa.review_id, qa.diff_id, qa.land_id, qa.insti_id, qa.exclude_self_learning,
COUNT(mqa.questionid) AS total_students,
SUM(CASE WHEN is_correct = 1 then 1 else 0 end) passed_students,
round((SUM(CASE WHEN is_correct = 1 then 1 else 0 end) / COUNT(mqa.questionid) * 100 ),2) AS percentage,
(SELECT COUNT(mqas1.questionid)
FROM mdl_question_attempts mqas1
LEFT JOIN mdl_quiz_attempts mquizas1 ON mqas1.questionusageid=mquizas1.uniqueid
LEFT JOIN mdl_user us1 ON mquizas1.userid=us1.id
WHERE us1.institution=20 AND mqas1.questionid=mq.id) AS total_students_facility,
(SELECT COUNT(mqas1.questionid)
FROM mdl_question_attempts mqas1
LEFT JOIN mdl_quiz_attempts mquizas1 ON mqas1.questionusageid=mquizas1.uniqueid
LEFT JOIN mdl_user us1 ON mquizas1.userid=us1.id
WHERE us1.institution=20 AND mqas1.questionid=mq.id AND mqas1.is_correct=1) AS passed_students_facility,
round(((SELECT COUNT(mqas1.questionid)
FROM mdl_question_attempts mqas1
LEFT JOIN mdl_quiz_attempts mquizas1 ON mqas1.questionusageid=mquizas1.uniqueid
LEFT JOIN mdl_user us1 ON mquizas1.userid=us1.id
WHERE us1.institution=20 AND mqas1.questionid=mq.id AND mqas1.is_correct=1) / (SELECT COUNT(mqas1.questionid)
FROM mdl_question_attempts mqas1
LEFT JOIN mdl_quiz_attempts mquizas1 ON mqas1.questionusageid=mquizas1.uniqueid
LEFT JOIN mdl_user us1 ON mquizas1.userid=us1.id
WHERE us1.institution=20 AND mqas1.questionid=mq.id) * 100 ),2) AS percentage_facility
from mdl_question mq
LEFT JOIN mdl_question_attempts mqa ON mq.id = mqa.questionid
left join mdl_my_ques_type_data qtd on (qtd.question_id=mq.id)
left join mdl_my_ques_attributes qa on (qa.question=mq.id)
left join specilities as s on(s.sp_id=qtd.spec)
where NOT mq.is_deleted
and ((qa.status = 1) OR (qa.insti_id = 20 and qa.status = 0))
GROUP BY mq.id
ORDER by mq.sort_order desc, mq.id DESC
LIMIT 0,50;
</code></pre>
|
[
{
"answer_id": 74499446,
"author": "C-3PO",
"author_id": 4667669,
"author_profile": "https://Stackoverflow.com/users/4667669",
"pm_score": 3,
"selected": true,
"text": "power_set_to_unit result separate_units = ['N', 'm', '⁻²⁴', 'kJ', 's', '⁻¹', 'km', '⁻²¹', 'kJ', '⁻²', 'm', '⁻²']\n\ndef power_set_to_unit():\n result = []\n for x in separate_units:\n if x.isalpha():\n result.append(x)\n else:\n result[-1] += x\n return result\n\nprint(power_set_to_unit())\n# ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm⁻²']\n power_set_to_unit = lambda sep='\\n': ''.join((sep+x if x.isalpha() else x) for x in separate_units).split(sep)[1:]\nprint(power_set_to_unit())\n# ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm⁻²']\n"
},
{
"answer_id": 74499551,
"author": "Dmitri Chubarov",
"author_id": 1328439,
"author_profile": "https://Stackoverflow.com/users/1328439",
"pm_score": 1,
"selected": false,
"text": "zip separate_units = ['N', 'm', '⁻²⁴', 'kJ', 's', '⁻¹', 'km', '⁻²¹', 'kJ', '⁻²', 'm', '⁻²']\n\n[a if b.isalpha() else a + b for (a,b) in zip(separate_units[:-1], separate_units[1:]) if a.isalpha()]\n# should result in ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm⁻²']\n if for in string_list [x for x in string_list if x.isalpha()]\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5891402/"
] |
74,499,390
|
<p>I keep getting the following error and I can't seem to find a solution for it.</p>
<pre><code> if password not in old_passwords:
TypeError: argument of type 'PasswordManager' is not iterable
</code></pre>
<p>For clarity, I needed to create a class called 'PasswordManager'. The class should have a list called 'old_passwords'. The list contains all past passwords, the last index of the list should be the current password. The required methods are 'set_password', 'get_password' and 'is_correct'.</p>
<p>'get_password' should return the current password.</p>
<p>'set_password' sets a new password. It should only change the password if the attempted password is different from all the user’s past passwords.</p>
<p>'is_correct' receives a string and returns a boolean True or False depending on whether the string is equal to the current password or not.</p>
<pre><code>class PasswordManager():
old_passwords = []
def get_password(old_passwords):
return old_passwords[len(old_passwords-1)]
def set_password(old_passwords, password):
if password not in old_passwords:
old_passwords.append(password)
def is_correct(old_passwords, password):
if password == old_passwords[len(old_passwords-1)]:
return True
else:
return False
</code></pre>
<p>Does anyone have an idea that could help me? Thanks in advance!</p>
|
[
{
"answer_id": 74499484,
"author": "Abhi747",
"author_id": 17103026,
"author_profile": "https://Stackoverflow.com/users/17103026",
"pm_score": 0,
"selected": false,
"text": "self.somemethod() self.somevariable class PasswordManager():\n old_passwords = []\n def get_password(self):\n return self.old_passwords[-1]\n\n def set_password(self, password):\n if password not in self.old_passwords:\n self.old_passwords.append(password)\n\n def is_correct(self, password):\n if password == self.old_passwords[-1]:\n return True\n else:\n return False\n old_passwords[len(old_passwords-1)] old_passwords[len(old_passwords)-1] old_passwords[-1]"
},
{
"answer_id": 74499496,
"author": "Gianluca Viganò",
"author_id": 10415670,
"author_profile": "https://Stackoverflow.com/users/10415670",
"pm_score": 3,
"selected": true,
"text": "old_passwords self class PasswordManager():\n \n def __init__(self):\n self.old_passwords = []\n\n def get_password(self):\n return self.old_passwords[-1]\n\n def set_password(self, password):\n if password not in self.old_passwords:\n self.old_passwords.append(password)\n\n def is_correct(self, password):\n return password == self.old_passwords[-1]\n [-1] __init__"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18082733/"
] |
74,499,439
|
<p>Suppose that I have a dataframe which can be created using code below</p>
<pre><code>df = pd.DataFrame(data = {'date':['2021-01-01', '2021-01-02', '2021-01-05','2021-01-02', '2021-01-03', '2021-01-05'],
'product':['A', 'A', 'A', 'B', 'B', 'B'],
'price':[10, 20, 30, 40, 50, 60]
}
)
df['date'] = pd.to_datetime(df['date'])
</code></pre>
<p>I want to create an empty dataframe let's say <code>main_df</code> which will contain all dates between <code>df.date.min()</code> and <code>df.date.max()</code> for each <code>product</code> and on days where values in <code>nan</code> I want to <code>ffill</code> and <code>bfill</code> for remaning. The resulting dataframe would be as below:</p>
<pre><code>+------------+---------+-------+
| date | product | price |
+------------+---------+-------+
| 2021-01-01 | A | 10 |
| 2021-01-02 | A | 20 |
| 2021-01-03 | A | 20 |
| 2021-01-04 | A | 20 |
| 2021-01-05 | A | 30 |
| 2021-01-01 | B | 40 |
| 2021-01-02 | B | 40 |
| 2021-01-03 | B | 50 |
| 2021-01-04 | B | 50 |
| 2021-01-05 | B | 60 |
+------------+---------+-------+
</code></pre>
|
[
{
"answer_id": 74499609,
"author": "user2314737",
"author_id": 2314737,
"author_profile": "https://Stackoverflow.com/users/2314737",
"pm_score": 0,
"selected": false,
"text": "resample df = pd.DataFrame(data = {'date':['2021-01-01', '2021-01-02', '2021-01-05','2021-01-02', '2021-01-03', '2021-01-06'],\n 'product':['A', 'A', 'A', 'B', 'B', 'B'],\n 'price':[10, 20, 30, 40, 50, 60]\n }\n )\ndf['date'] = pd.to_datetime(df['date'])\n\ndf\n# Out: \n# date product price\n# 0 2021-01-01 A 10\n# 1 2021-01-02 A 20\n# 2 2021-01-05 A 30\n# 3 2021-01-02 B 40\n# 4 2021-01-03 B 50\n# 5 2021-01-06 B 60\n\n\n\n\ndf.set_index(\"date\").groupby(\"product\")[\"price\"].resample(\"d\").ffill().reset_index()\n# Out: \n# product date price\n# 0 A 2021-01-01 10\n# 1 A 2021-01-02 20\n# 2 A 2021-01-03 20\n# 3 A 2021-01-04 20\n# 4 A 2021-01-05 30\n# 5 B 2021-01-02 40\n# 6 B 2021-01-03 50\n# 7 B 2021-01-04 50\n# 8 B 2021-01-05 50\n# 9 B 2021-01-06 60\n ffill df.set_index(\"date\").groupby(\"product\")[\"price\"].resample(\"d\").mean()\n# Out: \n# product date \n# A 2021-01-01 10.0\n# 2021-01-02 20.0\n# 2021-01-03 NaN\n# 2021-01-04 NaN\n# 2021-01-05 30.0\n# B 2021-01-02 40.0\n# 2021-01-03 50.0\n# 2021-01-04 NaN\n# 2021-01-05 NaN\n# 2021-01-06 60.0\n# Name: price, dtype: float64\n"
},
{
"answer_id": 74499668,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 3,
"selected": true,
"text": "asfreq df.pivot_table('price', 'date', 'product').asfreq('D').ffill().bfill()\n product A B\ndate \n2021-01-01 10.0 40.0\n2021-01-02 20.0 40.0\n2021-01-03 20.0 50.0\n2021-01-04 20.0 50.0\n2021-01-05 30.0 60.0\n stack (df.pivot_table('price', 'date', 'product').asfreq('D').ffill().bfill()\n .stack().reset_index().rename(columns={0:'price'})\n .sort_values('product').reset_index(drop=True))\n date product price\n0 2021-01-01 A 10.0\n1 2021-01-02 A 20.0\n2 2021-01-03 A 20.0\n3 2021-01-04 A 20.0\n4 2021-01-05 A 30.0\n5 2021-01-01 B 40.0\n6 2021-01-02 B 40.0\n7 2021-01-03 B 50.0\n8 2021-01-04 B 50.0\n9 2021-01-05 B 60.0\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10083382/"
] |
74,499,447
|
<p>I have the following code:</p>
<pre><code>import numpy as np
A=np.array([[2, 2-9j, -5j], [4-1j, 0, 9+6j], [4j, 6+7j, 6]])
print(A)
print(A.getH())
</code></pre>
<p>It doesn't work. I have checked different webs and followed <a href="https://www.geeksforgeeks.org/python-numpy-matrix-geth/" rel="nofollow noreferrer">this webpage</a> (geeksforgeeks), and <a href="https://numpy.org/doc/stable/reference/generated/numpy.matrix.H.html" rel="nofollow noreferrer">this other</a>(official numpy documentation) but I still get an error and I don't know where. Can someone please help me?</p>
<p>The error is <code>'numpy.ndarray' object has no attribute 'getH'</code></p>
|
[
{
"answer_id": 74499462,
"author": "Marcus Müller",
"author_id": 4433386,
"author_profile": "https://Stackoverflow.com/users/4433386",
"pm_score": 2,
"selected": true,
"text": "getH getH"
},
{
"answer_id": 74499479,
"author": "Abinashbunty",
"author_id": 13858770,
"author_profile": "https://Stackoverflow.com/users/13858770",
"pm_score": 1,
"selected": false,
"text": "numpy.conj() import numpy as np\nA=np.array([[2, 2-9j, -5j], [4-1j, 0, 9+6j], [4j, 6+7j, 6]])\nprint(A)\nprint(A.conj())\n [[ 2.+0.j 2.-9.j -0.-5.j]\n [ 4.-1.j 0.+0.j 9.+6.j]\n [ 0.+4.j 6.+7.j 6.+0.j]]\n[[ 2.-0.j 2.+9.j -0.+5.j]\n [ 4.+1.j 0.-0.j 9.-6.j]\n [ 0.-4.j 6.-7.j 6.-0.j]]\n"
},
{
"answer_id": 74499556,
"author": "user2357112",
"author_id": 2357112,
"author_profile": "https://Stackoverflow.com/users/2357112",
"pm_score": 0,
"selected": false,
"text": "numpy.matrix numpy.array numpy.ndarray numpy.matrix numpy.matrix numpy.matrix numpy.conj print(numpy.conj(A))\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9974205/"
] |
74,499,461
|
<p>I would like to display my output in the GUI like the picture below</p>
<p><a href="https://i.stack.imgur.com/l8RrL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l8RrL.png" alt="wanted display" /></a></p>
<p>But I end up having it like this when I use <code>setText</code> on <code>JLabel</code>s</p>
<p><a href="https://i.stack.imgur.com/uXRLl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uXRLl.png" alt="my program:( display" /></a></p>
<p>Here are the codes that display my texts:</p>
<pre class="lang-java prettyprint-override"><code>class StudentPanel extends JPanel {
JLabel jlName;
JLabel jlTitle;
JLabel jlImageFile;
JLabel jlGroup;
JLabel jlDemoWhat;
private JLabel student1image_2;
public StudentPanel() {
//jlName = new JTextArea("<html><body><\n>");
jlName = new JLabel();
add(jlName);
jlTitle = new JLabel();
add(jlTitle);
jlImageFile = new JLabel();
add(jlImageFile);
jlGroup = new JLabel();
add(jlGroup);
jlDemoWhat = new JLabel();
add(jlDemoWhat);
}
public void setStudent(Student s) {
jlName.setText("Hi Prof, I am " + s.getName());
jlTitle.setText("I am a " + s.getTitle());
ImageIcon student1image = new ImageIcon(s.getImageFile());
Image student1image_1 = student1image.getImage();
Image student1Resized = student1image_1.getScaledInstance(260, 180, UNDEFINED_CONDITION);
student1image = new ImageIcon(student1Resized);
student1image_2 = new JLabel(student1image);
add(student1image_2);
jlGroup.setText(s.getGroup());
jlDemoWhat.setText(s.getDemoWhat());
}
}
</code></pre>
<p>Does anyone know how to separate them?<br />
Thank you so much.</p>
<p>I Googled but so far no hope is found.</p>
|
[
{
"answer_id": 74499462,
"author": "Marcus Müller",
"author_id": 4433386,
"author_profile": "https://Stackoverflow.com/users/4433386",
"pm_score": 2,
"selected": true,
"text": "getH getH"
},
{
"answer_id": 74499479,
"author": "Abinashbunty",
"author_id": 13858770,
"author_profile": "https://Stackoverflow.com/users/13858770",
"pm_score": 1,
"selected": false,
"text": "numpy.conj() import numpy as np\nA=np.array([[2, 2-9j, -5j], [4-1j, 0, 9+6j], [4j, 6+7j, 6]])\nprint(A)\nprint(A.conj())\n [[ 2.+0.j 2.-9.j -0.-5.j]\n [ 4.-1.j 0.+0.j 9.+6.j]\n [ 0.+4.j 6.+7.j 6.+0.j]]\n[[ 2.-0.j 2.+9.j -0.+5.j]\n [ 4.+1.j 0.-0.j 9.-6.j]\n [ 0.-4.j 6.-7.j 6.-0.j]]\n"
},
{
"answer_id": 74499556,
"author": "user2357112",
"author_id": 2357112,
"author_profile": "https://Stackoverflow.com/users/2357112",
"pm_score": 0,
"selected": false,
"text": "numpy.matrix numpy.array numpy.ndarray numpy.matrix numpy.matrix numpy.matrix numpy.conj print(numpy.conj(A))\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16507341/"
] |
74,499,510
|
<p>I'm trying to produce a JSON format for a given entity and I'm having an issue getting the dictionary to NOT overwrite itself or become empty. This is pulling rows from a table in a MySQL database and attempting to produce JSON result from the query.</p>
<p>Here is my function:</p>
<pre class="lang-py prettyprint-override"><code>def detail():
student = 'John Doe'
conn = get_db_connection()
cur = conn.cursor()
sql = ("""
select
a.student_name,
a.student_id,
a.student_homeroom_name,
a.test_id,
a.datetaken,
a.datecertified,
b.request_number
FROM student_information a
INNER JOIN homeroom b ON a.homeroom_id = b.homeroom_id
WHERE a.student_name = '""" + student + """'
ORDER BY datecertified DESC
""")
cur.execute(sql)
details=cur.fetchall()
dataset = defaultdict(dict)
case_dataset = defaultdict(dict)
case_dataset = dict(case_dataset)
for student_name, student_id, student_homeroom_name, test_id, datetaken, datecertified, request_number in details:
dataset[student_name]['student_id'] = student_id
dataset[student_name]['student_homeroom_name'] = student_homeroom_name
case_dataset['test_id'] = test_id
case_dataset['datetaken'] = datetaken
case_dataset['datecertified'] = datecertified
case_dataset['request_number'] = request_number
dataset[student_name]['additional_information'] = case_dataset
case_dataset.clear()
dataset= dict(dataset)
print(dataset)
cur.close()
conn.close()
</code></pre>
<p>I tried a few different ways but nothing seems to work. What I'm getting is nothing in the <code>additonal_information</code> key. What I'm getting is this:</p>
<pre class="lang-json prettyprint-override"><code>{
"John Doe": {
"student_id": "1234",
"student_homeroom_name": "HR1",
"additional_information": []
}
}
</code></pre>
<p>What I'm expecting is something similar to the below JSON. However, I'm torn if this is even correct. Each student will have one to many <code>test_id</code> and I will need to iterate through them in my application.</p>
<pre class="lang-json prettyprint-override"><code>{
"John Doe": {
"student_id": "1234",
"student_homeroom_name": "HR1",
"additional_information": [
{
"test_id": "0987",
"datetaken": "1-1-1970",
"datecertified": "1-2-1970",
"request_number": "5643"
},
{
"test_id": "12343",
"datetaken": "1-1-1980",
"datecertified": "1-2-1980",
"request_number": "39807"
}
]
}
}
</code></pre>
<p>Removing the <code>clear()</code> from the function produces this JSON:</p>
<pre><code>{
"John Doe": {
"student_id": "1234",
"student_homeroom_name": "HR1",
"additional_information": [
{
"test_id": "0987",
"datetaken": "1-1-1970",
"datecertified": "1-2-1970",
"request_number": "5643"
},
{
"test_id": "0987",
"datetaken": "1-1-1970",
"datecertified": "1-2-1970",
"request_number": "5643"
}
]
}
}
</code></pre>
|
[
{
"answer_id": 74499630,
"author": "testfile",
"author_id": 6014330,
"author_profile": "https://Stackoverflow.com/users/6014330",
"pm_score": 1,
"selected": false,
"text": "dataset[student]['additional_information'] = case_dataset\n\ncase_dataset.clear()\n additional_information dataset[student]['additional_information'] = case_dataset[:]\n\ncase_dataset.clear()\n"
},
{
"answer_id": 74500043,
"author": "Robert Thompson",
"author_id": 9917783,
"author_profile": "https://Stackoverflow.com/users/9917783",
"pm_score": 1,
"selected": true,
"text": "additional_dataset case_dataset = defaultdict(dict) case_dataset = dict(case_dataset) case_dataset = {} dataset[student_name]['additional_information'] = case_dataset dataset[student_name]['additional_information'] = additional_dataset case_dataset.clear() case_dataset = {} def detail():\n student = 'John Doe'\n conn = get_db_connection()\n cur = conn.cursor()\n sql = (\"\"\"\n select\n a.student_name,\n a.student_id,\n a.student_homeroom_name,\n a.test_id,\n a.datetaken, \n a.datecertified,\n b.request_number\n FROM student_information a \n INNER JOIN homeroom b ON a.homeroom_id = b.homeroom_id\n WHERE a.student_name = '\"\"\" + student + \"\"\"'\n ORDER BY datecertified DESC \n \"\"\")\n cur.execute(sql)\n details=cur.fetchall()\n \n dataset = defaultdict(dict)\n case_dataset = {} #2 - Updated to just dict\n additional_dataset = [] #1 - added back additional_dataset as a list\n \n for student_name, student_id, student_homeroom_name, test_id, datetaken, datecertified, request_number in details:\n dataset[student_name]['student_id'] = student_id\n dataset[student_name]['student_homeroom_name'] = student_homeroom_name\n \n case_dataset['test_id'] = test_id\n case_dataset['datetaken'] = datetaken\n case_dataset['datecertified'] = datecertified\n case_dataset['request_number'] = request_number\n\n dataset[student_name]['additional_information'] = additional_dataset #3 - updated to additional_dataset\n\n case_dataset = {} #4 - updated to clear with new dict\n \n dataset= dict(dataset)\n print(dataset)\n\n cur.close()\n conn.close()\n {\n \"John Doe\": {\n \"student_id\": \"1234\",\n \"student_homeroom_name\": \"HR1\",\n \"additional_information\": [\n {\n \"test_id\": \"0987\",\n \"datetaken\": \"1-1-1970\",\n \"datecertified\": \"1-2-1970\",\n \"request_number\": \"5643\"\n },\n {\n \"test_id\": \"12343\",\n \"datetaken\": \"1-1-1980\",\n \"datecertified\": \"1-2-1980\",\n \"request_number\": \"39807\"\n }\n ]\n }\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9917783/"
] |
74,499,517
|
<p>I have created tables like before, with the given primary and foreign keys. However I get this error when I try to create a new table with the code below.</p>
<pre><code>create table Order (
oid int(255),
sid int(255),
sku int(255),
quantity int(255),
foreign key (sid) references Suppliers(sid),
foreign key (sku) references Parts(sku),
primary key(sid,sku)
)
</code></pre>
<p>and I have created Suppliers and Parts tables with the code below</p>
<pre><code>create table Parts(
sku int(255) auto_increment primary key,
pname varchar(255),
stock_level int(255),
color varchar(255)
)
</code></pre>
<pre><code>create table Suppliers (
sid int(255) auto_increment primary key,
sname varchar(255),
city varchar(255),
street varchar(255)
)
</code></pre>
<p>sid and sku already exist in their respective tables. I do not understand why I get such an error.
The complete output is:</p>
<blockquote>
<p>[42000][1064] You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
use near 'Order( oid int (255), sid int (255), sku int(255), quantity
i' at line 1</p>
</blockquote>
|
[
{
"answer_id": 74499709,
"author": "marcothesane",
"author_id": 6788255,
"author_profile": "https://Stackoverflow.com/users/6788255",
"pm_score": -1,
"selected": false,
"text": "INT(255) INT INT INT(255)"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15605143/"
] |
74,499,534
|
<p>I need to insert a string (character by character) into another string at every 3rd position
For example:- string_1:-wwwaabkccgkll
String_2:- toadhp
Now I need to insert string2 char by char into string1 at every third position
So the output must be wwtaaobkaccdgkhllp
Need in Python.. even Java is ok</p>
<p>So i tried this</p>
<pre><code>Test_str="hiimdumbiknow"
challenge="toadh"
new_st=challenge [k]
Last=list(test_str)
K=0
For i in range(Len(test_str)):
if(i%3==0):
last.insert(i,new_st)
K+=1
</code></pre>
<p>and the output i get
thitimtdutmbtiknow</p>
|
[
{
"answer_id": 74499602,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 0,
"selected": false,
"text": "Test_str challenge import itertools\nprint(''.join(f'{two}{letter}' for two, letter in itertools.zip_longest([Test_str[i:i+2] for i in range(0,len(Test_str),2)], challenge, fillvalue='')))\n hitimoduambdikhnow\n"
},
{
"answer_id": 74499728,
"author": "C-3PO",
"author_id": 4667669,
"author_profile": "https://Stackoverflow.com/users/4667669",
"pm_score": 1,
"selected": false,
"text": "test_str challenge def concat3(test_str, challenge):\n chunks = [test_str[i:i+2] for i in range(0,len(test_str),2)]\n result = []\n i = j = 0\n while i<len(chunks) or j<len(challenge):\n if i<len(chunks):\n result.append(chunks[i])\n i += 1\n if j<len(challenge):\n result.append(challenge[j])\n j += 1\n return ''.join(result)\n\ntest_str = \"hiimdumbiknow\"\nchallenge = \"toadh\"\n\nprint(concat3(test_str, challenge))\n# hitimoduambdikhnow\n test_str challenge"
},
{
"answer_id": 74499838,
"author": "Narcisse Doudieu Siewe",
"author_id": 1438644,
"author_profile": "https://Stackoverflow.com/users/1438644",
"pm_score": 0,
"selected": false,
"text": "def add3(s1, s2):\n def n():\n try:\n k = iter(s2)\n for i,j in enumerate(s1):\n yield (j if (i==0 or (i+1)%3) else next(k))\n except:\n try:\n yield s1[i+1:]\n except:\n pass \n return ''.join(n()) \n"
},
{
"answer_id": 74502923,
"author": "Joelinton",
"author_id": 19753231,
"author_profile": "https://Stackoverflow.com/users/19753231",
"pm_score": 0,
"selected": false,
"text": "def insertstring(test_str,challenge):\n result = ''\n x = [x for x in test_str]\n y = [y for y in challenge]\n j = 0\n for i in range(len(x)):\n if i % 2 != 0 or i == 0:\n result += x[i]\n else:\n if j < 5:\n result += y[j]\n result += x[i]\n j += 1\n get_last_element = x[-1]\n return result + get_last_element\n\n\nprint(insertstring(test_str,challenge))\n\n#output: hitimoduambdikhnow\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19502973/"
] |
74,499,585
|
<p>Below is the vault output generated by the vault command</p>
<p>vault kv get kv/Env | jq</p>
<pre><code>{
"request_id": "8498e5e4-050a-51e9-deaf-64a06a0",
"lease_id": "",
"lease_duration": 0,
"renewable": false,
"data": {
"data": {
"test": "test123",
"test1": "test1234"
},
"metadata": {
"created_time": "2022-11-17T12:2214.93229792Z",
"custom_metadata": null,
"deletion_time": "",
"destroyed": false,
"version": 1
}
},
"warnings": null
}
</code></pre>
<p>I am unable to find a way to get only test and test1 and set as environmental variable in powershell. The issue is I would like to extract only test and test1, but it is under data/data which is like sublist and unable to find a way to extract it. Kindly help</p>
<p>I had provided the paths to delete as below but not sure if its efficient way to loop through</p>
<pre><code>vault kv get kv/Env | jq 'del(.data.metadata, .request_id, .lease_id, .lease_duration, .renewable, .warnings)'
</code></pre>
<p>I would like to get the output something like below which I can loop through and set as variable.</p>
<pre><code>test=test123
test1=test1234
</code></pre>
|
[
{
"answer_id": 74499601,
"author": "knittl",
"author_id": 112968,
"author_profile": "https://Stackoverflow.com/users/112968",
"pm_score": 2,
"selected": true,
"text": ".data.data to_entries vault ... | jq -r '.data.data | to_entries[] | join(\"=\")'\n test=test123\ntest1=test1234\n"
},
{
"answer_id": 74500761,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 2,
"selected": false,
"text": "jq (vault kv get kv/Env | ConvertFrom-Json).data.data.psobject.Properties |\n % { Set-Item Env:$($_.Name) $_.Value }\n ConvertFrom-Json [pscustomobject] .data.data .Properties psobject .data.data % ForEach-Object Set-Item Env:"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17929486/"
] |
74,499,635
|
<p>I saw this parallax animation on <a href="https://www.ubisoft.com/en-gb/game/far-cry/far-cry-6" rel="nofollow noreferrer">Far Cry 6 website</a> and wanted to recreate it in Flutter. I read the docs and watched some tutorials but I am not able to achieve this design accurately. I want to make a mobile version like the website shows on Mobile Browser like this - <a href="https://imgur.com/a/RGdspxa" rel="nofollow noreferrer">https://imgur.com/a/RGdspxa</a></p>
<p>The image needs to be on top of one another and when I scroll, the bottom image should come from bottom to top in a reversed manner as the website. I am not able to figure out how to do this.</p>
<p>Please tell me how I can achieve this?</p>
<p>My Code -</p>
<pre class="lang-dart prettyprint-override"><code>import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
return Scaffold(
body: Material(
child: Stack(
children: [
Image.network(
"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg",
height: height,
// width: width,
fit: BoxFit.fitHeight,
),
SingleChildScrollView(
child: Column(
children: [
SizedBox(height: height),
Image.network(
"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg",
height: height,
width: width,
fit: BoxFit.cover,
),
],
),
)
],
),
),
);
}
}
</code></pre>
|
[
{
"answer_id": 74646549,
"author": "Sayyid J",
"author_id": 15366030,
"author_profile": "https://Stackoverflow.com/users/15366030",
"pm_score": 3,
"selected": true,
"text": "ScrollMetrics ScrollNotification class Parallax extends StatefulWidget {\n const Parallax({Key? key, required this.childreen}) : super(key: key);\n final List<Widget> childreen;\n\n @override\n State<Parallax> createState() => _ParallaxState();\n}\n\nclass _ParallaxState extends State<Parallax> {\n late double _pixel;\n\n @override\n void initState() {\n // TODO: implement initState\n super.initState();\n _pixel = 0;\n }\n\n @override\n Widget build(BuildContext context) {\n return NotificationListener<ScrollNotification>(\n onNotification: (notif) {\n setState(() {\n _pixel = notif.metrics.pixels;\n });\n return true;\n },\n child: SingleChildScrollView(\n child: Column(\n children: List.generate(\n widget.childreen.length,\n (index) => _ParalaxChild(\n index: index,\n pixel: _pixel,\n childreenLenght: widget.childreen.length,\n child: widget.childreen[index])),\n ),\n ),\n );\n }\n}\n\nclass _ParalaxChild extends StatelessWidget {\n final int index;\n final Widget child;\n final double pixel;\n final int childreenLenght;\n const _ParalaxChild(\n {Key? key,\n required this.child,\n required this.index,\n required this.pixel,\n required this.childreenLenght})\n : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n return ClipRect(\n child: SizedBox(\n height: MediaQuery.of(context).size.height,\n width: MediaQuery.of(context).size.width,\n child: Stack(\n fit: StackFit.expand,\n children: [\n FractionalTranslation(\n translation: Offset(0.0, -_calculateParallax(context)),\n child: child),\n const Positioned(\n bottom: 200,\n right: 20,\n child: Text(\n \"Parallax\",\n style: TextStyle(\n color: Colors.white,\n fontSize: 30,\n fontWeight: FontWeight.bold),\n )),\n const Positioned(\n bottom: 12,\n right: 20,\n left: 20,\n child: Padding(\n padding: EdgeInsets.all(20.0),\n child: Text(\n \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.\",\n style: TextStyle(\n color: Colors.white,\n fontSize: 16,\n ),\n ),\n ))\n ],\n )),\n );\n }\n\n double _calculateParallax(BuildContext context) {\n final double height = MediaQuery.of(context).size.height;\n final double pageHeight = height * index;\n final double childPosition = (pageHeight - pixel) / height;\n return childPosition.isNaN ? 0.0 : childPosition;\n }\n}\n class MyApp extends StatelessWidget {\n const MyApp({Key? key}) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n double height = MediaQuery.of(context).size.height;\n double width = MediaQuery.of(context).size.width;\n return Scaffold(\n body: Parallax(childreen: [\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg\",\n height: height,\n // width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg\",\n height: height,\n width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg\",\n height: height,\n // width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg\",\n height: height,\n width: width,\n fit: BoxFit.fitHeight,\n ),\n ]),\n );\n }\n}\n class TornEffect extends CustomClipper<Path>{\n ///how much the torn effect will be\n final int intensity;\n\n TornEffect({required this.intensity});\n\n @override\n ui.Path getClip(ui.Size size) {\n\n var path = Path();\n //make sure path on left top corner\n path.moveTo(0.0, 0.0);\n\n var random = math.Random();\n \n //to prevent blankSpace, move y to top (must always negative):\n double ybase = -20.0;\n\n //top:\n double topProgress = 0.0;\n while(topProgress < size.width){\n bool curve = random.nextBool();\n if(curve){\n \n double cpx = topProgress + random.nextInt(intensity) * 0.5 * negativePositive();\n double cpy = ybase + (random.nextInt(intensity) * 0.25 * negativePositive());\n\n double x = topProgress + random.nextInt(intensity)* 1.0 * negativePositive();\n double y = ybase + (random.nextInt(intensity) * 0.5 * negativePositive());\n\n path.quadraticBezierTo(\n cpx,\n cpy,\n x,\n y\n );\n topProgress += x.abs();\n }\n else {\n \n double x = topProgress + random.nextInt(intensity) * 1.0 * negativePositive();\n double y = ybase + (random.nextInt(intensity) * 0.5 * negativePositive());\n path.lineTo(x, y);\n topProgress += x.abs();\n }\n }\n //make sure top right corner got shape\n path.lineTo(size.width, 0.0);\n\n // line to bottom right corner\n path.lineTo(size.width, size.height);\n\n // you can build bottom rip effect later:\n //double bottomProgress = 0.0;\n //while(){}\n\n // bottom left\n path.lineTo(0.0, size.height);\n\n //close it with another line\n path.close();\n return path;\n\n }\n\n double negativePositive(){\n var random = math.Random();\n bool negativePositive = random.nextBool();\n double result = negativePositive ? 1.0: -1.0;\n return result;\n }\n\n @override\n bool shouldReclip(covariant CustomClipper<ui.Path> oldClipper) {\n // TODO: implement shouldReclip\n //return this != oldClipper;\n // return false for performance, or rebuilt every scroll\n return false;\n }\n\n}\n return ClipPath(\n clipper: TornEffect(intensity: 21),\n child: SizedBox(\n height: MediaQuery.of(context).size.height,\n width: MediaQuery.of(context).size.width,\n child: Stack(\n fit: StackFit.expand,\n children: [\n"
},
{
"answer_id": 74670593,
"author": "Cedar",
"author_id": 1870968,
"author_profile": "https://Stackoverflow.com/users/1870968",
"pm_score": 0,
"selected": false,
"text": "// Create the ScrollController\nfinal scrollController = ScrollController();\n\n// Retrieve the current scroll position\nfinal scrollPosition = scrollController.position.pixels;\n\n// Define the range of the animation (in this case, from 0.0 to 1.0)\nfinal animationRange = Tween(begin: 0.0, end: 1.0);\n\n// Calculate the animation value based on the current scroll position\nfinal animationValue = animationRange.transform(scrollPosition);\n\n// Use the animation value to animate the position of the background images\nreturn SingleChildScrollView(\n controller: scrollController,\n child: Stack(\n children: [\n // Background image 1\n Positioned(\n top: animationValue * 100.0, // This will move the image 100 pixels downwards as the user scrolls\n child: Image.asset(\"image1.png\"),\n ),\n // Background image 2\n Positioned(\n top: -animationValue * 100.0, // This will move the image 100 pixels upwards as the user scrolls\n child: Image.asset(\"image2.png\"),\n ),\n ],\n ),\n);\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10068879/"
] |
74,499,642
|
<p>I am trying to set up two different cronjobs. Some hosts need the standard cronjob while others need the failover cronjob</p>
<p>This is my hosts file, this is only one subset, there are others like [ukspare] and [usspare]</p>
<pre><code>[zaspare]
host01.example.com
host02.example.com
host03.example.com
host04.example.com
host05.example.com
host06.example.com
host07.example.com
host08.example.com
</code></pre>
<p>This is my yaml file, as you can see I want to stop the standard cron from running on hosts 1-5 but must run on hosts 6-8, and I need to copy the somescript.sh to all hosts</p>
<pre><code>---
- name: Updating somescript
hosts: zaspare
become: yes
tasks:
- name: Copy somescript.sh script to /usr/local/bin
copy:
src: somescript.sh
dest: /usr/local/bin/
owner: root
group: root
mode: 0755
- name: Setup standard crontab for somescript
cron:
name: Run somescript.sh
job: /usr/local/bin/somescript.sh {{ inventory_hostname }} false
cron_file: somescript
user: root
minute: "10"
hour: "22"
when: inventory_hostname != "host01.example.com" or
inventory_hostname != "host02.example.com" or
inventory_hostname != "host03.example.com" or
inventory_hostname != "host04.example.com" or
inventory_hostname != "host05.example.com"
- name: Setup failover crontab for somescript
cron:
name: Run somescript.sh
job: /usr/local/bin/somescript.sh {{ inventory_hostname }} true
cron_file: somescript
user: root
minute: "10"
hour: "22"
when: inventory_hostname == "host01.example.com" or
inventory_hostname == "host02.example.com" or
inventory_hostname == "host03.example.com" or
inventory_hostname == "host04.example.com" or
inventory_hostname == "host05.example.com"
</code></pre>
<p>As you can see from the output below the standard cron runs on all the hosts, and then skips some hosts and updates the cron for the failover correctly</p>
<pre><code>TASK [Setup standard crontab for somescript]******************************
changed: [host06.example.com]
changed: [host07.example.com]
changed: [host01.example.com]
changed: [host08.example.com]
changed: [host02.example.com]
changed: [host04.example.com]
changed: [host03.example.com]
changed: [host05.example.com]
TASK [Setup failover crontab for somescript]******************************
skipping: [host06.example.com]
skipping: [host07.example.com]
skipping: [host08.example.com]
changed: [host01.example.com]
changed: [host02.example.com]
changed: [host03.example.com]
changed: [host04.example.com]
changed: [host05.example.com]
</code></pre>
<p>I have tried with just one host and it appears to work correctly, the minute I start add ing multiple hosts to exclude on the standard cron it stop working</p>
<pre><code>---
- name: Updating somescript
hosts: zaspare
become: yes
tasks:
- name: Copy somescript.sh script to /usr/local/bin
copy:
src: somescript.sh
dest: /usr/local/bin/
owner: root
group: root
mode: 0755
- name: Setup standard crontab for somescript
cron:
name: Run somescript.sh
job: /usr/local/bin/somescript.sh {{ inventory_hostname }} false
cron_file: somescript
user: root
minute: "10"
hour: "22"
when: inventory_hostname != "host01.example.com"
- name: Setup failover crontab for somescript
cron:
name: Run somescript.sh
job: /usr/local/bin/somescript.sh {{ inventory_hostname }} true
cron_file: somescript
user: root
minute: "10"
hour: "22"
when: inventory_hostname == "host01.example.com"
</code></pre>
<pre><code>TASK [Setup standard crontab for somescript]******************************
skipping: [host01.example.com]
TASK [Setup failover crontab for somescript]******************************
changed: [host01.example.com]
</code></pre>
|
[
{
"answer_id": 74646549,
"author": "Sayyid J",
"author_id": 15366030,
"author_profile": "https://Stackoverflow.com/users/15366030",
"pm_score": 3,
"selected": true,
"text": "ScrollMetrics ScrollNotification class Parallax extends StatefulWidget {\n const Parallax({Key? key, required this.childreen}) : super(key: key);\n final List<Widget> childreen;\n\n @override\n State<Parallax> createState() => _ParallaxState();\n}\n\nclass _ParallaxState extends State<Parallax> {\n late double _pixel;\n\n @override\n void initState() {\n // TODO: implement initState\n super.initState();\n _pixel = 0;\n }\n\n @override\n Widget build(BuildContext context) {\n return NotificationListener<ScrollNotification>(\n onNotification: (notif) {\n setState(() {\n _pixel = notif.metrics.pixels;\n });\n return true;\n },\n child: SingleChildScrollView(\n child: Column(\n children: List.generate(\n widget.childreen.length,\n (index) => _ParalaxChild(\n index: index,\n pixel: _pixel,\n childreenLenght: widget.childreen.length,\n child: widget.childreen[index])),\n ),\n ),\n );\n }\n}\n\nclass _ParalaxChild extends StatelessWidget {\n final int index;\n final Widget child;\n final double pixel;\n final int childreenLenght;\n const _ParalaxChild(\n {Key? key,\n required this.child,\n required this.index,\n required this.pixel,\n required this.childreenLenght})\n : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n return ClipRect(\n child: SizedBox(\n height: MediaQuery.of(context).size.height,\n width: MediaQuery.of(context).size.width,\n child: Stack(\n fit: StackFit.expand,\n children: [\n FractionalTranslation(\n translation: Offset(0.0, -_calculateParallax(context)),\n child: child),\n const Positioned(\n bottom: 200,\n right: 20,\n child: Text(\n \"Parallax\",\n style: TextStyle(\n color: Colors.white,\n fontSize: 30,\n fontWeight: FontWeight.bold),\n )),\n const Positioned(\n bottom: 12,\n right: 20,\n left: 20,\n child: Padding(\n padding: EdgeInsets.all(20.0),\n child: Text(\n \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.\",\n style: TextStyle(\n color: Colors.white,\n fontSize: 16,\n ),\n ),\n ))\n ],\n )),\n );\n }\n\n double _calculateParallax(BuildContext context) {\n final double height = MediaQuery.of(context).size.height;\n final double pageHeight = height * index;\n final double childPosition = (pageHeight - pixel) / height;\n return childPosition.isNaN ? 0.0 : childPosition;\n }\n}\n class MyApp extends StatelessWidget {\n const MyApp({Key? key}) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n double height = MediaQuery.of(context).size.height;\n double width = MediaQuery.of(context).size.width;\n return Scaffold(\n body: Parallax(childreen: [\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg\",\n height: height,\n // width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg\",\n height: height,\n width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg\",\n height: height,\n // width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg\",\n height: height,\n width: width,\n fit: BoxFit.fitHeight,\n ),\n ]),\n );\n }\n}\n class TornEffect extends CustomClipper<Path>{\n ///how much the torn effect will be\n final int intensity;\n\n TornEffect({required this.intensity});\n\n @override\n ui.Path getClip(ui.Size size) {\n\n var path = Path();\n //make sure path on left top corner\n path.moveTo(0.0, 0.0);\n\n var random = math.Random();\n \n //to prevent blankSpace, move y to top (must always negative):\n double ybase = -20.0;\n\n //top:\n double topProgress = 0.0;\n while(topProgress < size.width){\n bool curve = random.nextBool();\n if(curve){\n \n double cpx = topProgress + random.nextInt(intensity) * 0.5 * negativePositive();\n double cpy = ybase + (random.nextInt(intensity) * 0.25 * negativePositive());\n\n double x = topProgress + random.nextInt(intensity)* 1.0 * negativePositive();\n double y = ybase + (random.nextInt(intensity) * 0.5 * negativePositive());\n\n path.quadraticBezierTo(\n cpx,\n cpy,\n x,\n y\n );\n topProgress += x.abs();\n }\n else {\n \n double x = topProgress + random.nextInt(intensity) * 1.0 * negativePositive();\n double y = ybase + (random.nextInt(intensity) * 0.5 * negativePositive());\n path.lineTo(x, y);\n topProgress += x.abs();\n }\n }\n //make sure top right corner got shape\n path.lineTo(size.width, 0.0);\n\n // line to bottom right corner\n path.lineTo(size.width, size.height);\n\n // you can build bottom rip effect later:\n //double bottomProgress = 0.0;\n //while(){}\n\n // bottom left\n path.lineTo(0.0, size.height);\n\n //close it with another line\n path.close();\n return path;\n\n }\n\n double negativePositive(){\n var random = math.Random();\n bool negativePositive = random.nextBool();\n double result = negativePositive ? 1.0: -1.0;\n return result;\n }\n\n @override\n bool shouldReclip(covariant CustomClipper<ui.Path> oldClipper) {\n // TODO: implement shouldReclip\n //return this != oldClipper;\n // return false for performance, or rebuilt every scroll\n return false;\n }\n\n}\n return ClipPath(\n clipper: TornEffect(intensity: 21),\n child: SizedBox(\n height: MediaQuery.of(context).size.height,\n width: MediaQuery.of(context).size.width,\n child: Stack(\n fit: StackFit.expand,\n children: [\n"
},
{
"answer_id": 74670593,
"author": "Cedar",
"author_id": 1870968,
"author_profile": "https://Stackoverflow.com/users/1870968",
"pm_score": 0,
"selected": false,
"text": "// Create the ScrollController\nfinal scrollController = ScrollController();\n\n// Retrieve the current scroll position\nfinal scrollPosition = scrollController.position.pixels;\n\n// Define the range of the animation (in this case, from 0.0 to 1.0)\nfinal animationRange = Tween(begin: 0.0, end: 1.0);\n\n// Calculate the animation value based on the current scroll position\nfinal animationValue = animationRange.transform(scrollPosition);\n\n// Use the animation value to animate the position of the background images\nreturn SingleChildScrollView(\n controller: scrollController,\n child: Stack(\n children: [\n // Background image 1\n Positioned(\n top: animationValue * 100.0, // This will move the image 100 pixels downwards as the user scrolls\n child: Image.asset(\"image1.png\"),\n ),\n // Background image 2\n Positioned(\n top: -animationValue * 100.0, // This will move the image 100 pixels upwards as the user scrolls\n child: Image.asset(\"image2.png\"),\n ),\n ],\n ),\n);\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12422400/"
] |
74,499,667
|
<p>I have seen many sites load whenever you scroll. How to do the same thing on my site?</p>
|
[
{
"answer_id": 74646549,
"author": "Sayyid J",
"author_id": 15366030,
"author_profile": "https://Stackoverflow.com/users/15366030",
"pm_score": 3,
"selected": true,
"text": "ScrollMetrics ScrollNotification class Parallax extends StatefulWidget {\n const Parallax({Key? key, required this.childreen}) : super(key: key);\n final List<Widget> childreen;\n\n @override\n State<Parallax> createState() => _ParallaxState();\n}\n\nclass _ParallaxState extends State<Parallax> {\n late double _pixel;\n\n @override\n void initState() {\n // TODO: implement initState\n super.initState();\n _pixel = 0;\n }\n\n @override\n Widget build(BuildContext context) {\n return NotificationListener<ScrollNotification>(\n onNotification: (notif) {\n setState(() {\n _pixel = notif.metrics.pixels;\n });\n return true;\n },\n child: SingleChildScrollView(\n child: Column(\n children: List.generate(\n widget.childreen.length,\n (index) => _ParalaxChild(\n index: index,\n pixel: _pixel,\n childreenLenght: widget.childreen.length,\n child: widget.childreen[index])),\n ),\n ),\n );\n }\n}\n\nclass _ParalaxChild extends StatelessWidget {\n final int index;\n final Widget child;\n final double pixel;\n final int childreenLenght;\n const _ParalaxChild(\n {Key? key,\n required this.child,\n required this.index,\n required this.pixel,\n required this.childreenLenght})\n : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n return ClipRect(\n child: SizedBox(\n height: MediaQuery.of(context).size.height,\n width: MediaQuery.of(context).size.width,\n child: Stack(\n fit: StackFit.expand,\n children: [\n FractionalTranslation(\n translation: Offset(0.0, -_calculateParallax(context)),\n child: child),\n const Positioned(\n bottom: 200,\n right: 20,\n child: Text(\n \"Parallax\",\n style: TextStyle(\n color: Colors.white,\n fontSize: 30,\n fontWeight: FontWeight.bold),\n )),\n const Positioned(\n bottom: 12,\n right: 20,\n left: 20,\n child: Padding(\n padding: EdgeInsets.all(20.0),\n child: Text(\n \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.\",\n style: TextStyle(\n color: Colors.white,\n fontSize: 16,\n ),\n ),\n ))\n ],\n )),\n );\n }\n\n double _calculateParallax(BuildContext context) {\n final double height = MediaQuery.of(context).size.height;\n final double pageHeight = height * index;\n final double childPosition = (pageHeight - pixel) / height;\n return childPosition.isNaN ? 0.0 : childPosition;\n }\n}\n class MyApp extends StatelessWidget {\n const MyApp({Key? key}) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n double height = MediaQuery.of(context).size.height;\n double width = MediaQuery.of(context).size.width;\n return Scaffold(\n body: Parallax(childreen: [\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg\",\n height: height,\n // width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg\",\n height: height,\n width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg\",\n height: height,\n // width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg\",\n height: height,\n width: width,\n fit: BoxFit.fitHeight,\n ),\n ]),\n );\n }\n}\n class TornEffect extends CustomClipper<Path>{\n ///how much the torn effect will be\n final int intensity;\n\n TornEffect({required this.intensity});\n\n @override\n ui.Path getClip(ui.Size size) {\n\n var path = Path();\n //make sure path on left top corner\n path.moveTo(0.0, 0.0);\n\n var random = math.Random();\n \n //to prevent blankSpace, move y to top (must always negative):\n double ybase = -20.0;\n\n //top:\n double topProgress = 0.0;\n while(topProgress < size.width){\n bool curve = random.nextBool();\n if(curve){\n \n double cpx = topProgress + random.nextInt(intensity) * 0.5 * negativePositive();\n double cpy = ybase + (random.nextInt(intensity) * 0.25 * negativePositive());\n\n double x = topProgress + random.nextInt(intensity)* 1.0 * negativePositive();\n double y = ybase + (random.nextInt(intensity) * 0.5 * negativePositive());\n\n path.quadraticBezierTo(\n cpx,\n cpy,\n x,\n y\n );\n topProgress += x.abs();\n }\n else {\n \n double x = topProgress + random.nextInt(intensity) * 1.0 * negativePositive();\n double y = ybase + (random.nextInt(intensity) * 0.5 * negativePositive());\n path.lineTo(x, y);\n topProgress += x.abs();\n }\n }\n //make sure top right corner got shape\n path.lineTo(size.width, 0.0);\n\n // line to bottom right corner\n path.lineTo(size.width, size.height);\n\n // you can build bottom rip effect later:\n //double bottomProgress = 0.0;\n //while(){}\n\n // bottom left\n path.lineTo(0.0, size.height);\n\n //close it with another line\n path.close();\n return path;\n\n }\n\n double negativePositive(){\n var random = math.Random();\n bool negativePositive = random.nextBool();\n double result = negativePositive ? 1.0: -1.0;\n return result;\n }\n\n @override\n bool shouldReclip(covariant CustomClipper<ui.Path> oldClipper) {\n // TODO: implement shouldReclip\n //return this != oldClipper;\n // return false for performance, or rebuilt every scroll\n return false;\n }\n\n}\n return ClipPath(\n clipper: TornEffect(intensity: 21),\n child: SizedBox(\n height: MediaQuery.of(context).size.height,\n width: MediaQuery.of(context).size.width,\n child: Stack(\n fit: StackFit.expand,\n children: [\n"
},
{
"answer_id": 74670593,
"author": "Cedar",
"author_id": 1870968,
"author_profile": "https://Stackoverflow.com/users/1870968",
"pm_score": 0,
"selected": false,
"text": "// Create the ScrollController\nfinal scrollController = ScrollController();\n\n// Retrieve the current scroll position\nfinal scrollPosition = scrollController.position.pixels;\n\n// Define the range of the animation (in this case, from 0.0 to 1.0)\nfinal animationRange = Tween(begin: 0.0, end: 1.0);\n\n// Calculate the animation value based on the current scroll position\nfinal animationValue = animationRange.transform(scrollPosition);\n\n// Use the animation value to animate the position of the background images\nreturn SingleChildScrollView(\n controller: scrollController,\n child: Stack(\n children: [\n // Background image 1\n Positioned(\n top: animationValue * 100.0, // This will move the image 100 pixels downwards as the user scrolls\n child: Image.asset(\"image1.png\"),\n ),\n // Background image 2\n Positioned(\n top: -animationValue * 100.0, // This will move the image 100 pixels upwards as the user scrolls\n child: Image.asset(\"image2.png\"),\n ),\n ],\n ),\n);\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16105784/"
] |
74,499,694
|
<p>I don't know what I'm doing wrong, all my pages have the same model, but this one doesn't want to center !</p>
<p>Do you have any idea where the problem come from ?</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:sizer/sizer.dart';
class OnBoardingDataPage1 extends StatefulWidget {
const OnBoardingDataPage1({Key? key}) : super(key: key);
@override
State<OnBoardingDataPage1> createState() => _OnBoardingDataPage1State();
}
class _OnBoardingDataPage1State extends State<OnBoardingDataPage1> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(height: 5.h),
Text(
"MugiwarApp",
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.titleLarge,
),
Image.asset(
"assets/images/animation.gif",
height: 125.0,
width: 125.0,
)
]),
)),
);
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/NzSND.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NzSND.png" alt="example" /></a></p>
|
[
{
"answer_id": 74646549,
"author": "Sayyid J",
"author_id": 15366030,
"author_profile": "https://Stackoverflow.com/users/15366030",
"pm_score": 3,
"selected": true,
"text": "ScrollMetrics ScrollNotification class Parallax extends StatefulWidget {\n const Parallax({Key? key, required this.childreen}) : super(key: key);\n final List<Widget> childreen;\n\n @override\n State<Parallax> createState() => _ParallaxState();\n}\n\nclass _ParallaxState extends State<Parallax> {\n late double _pixel;\n\n @override\n void initState() {\n // TODO: implement initState\n super.initState();\n _pixel = 0;\n }\n\n @override\n Widget build(BuildContext context) {\n return NotificationListener<ScrollNotification>(\n onNotification: (notif) {\n setState(() {\n _pixel = notif.metrics.pixels;\n });\n return true;\n },\n child: SingleChildScrollView(\n child: Column(\n children: List.generate(\n widget.childreen.length,\n (index) => _ParalaxChild(\n index: index,\n pixel: _pixel,\n childreenLenght: widget.childreen.length,\n child: widget.childreen[index])),\n ),\n ),\n );\n }\n}\n\nclass _ParalaxChild extends StatelessWidget {\n final int index;\n final Widget child;\n final double pixel;\n final int childreenLenght;\n const _ParalaxChild(\n {Key? key,\n required this.child,\n required this.index,\n required this.pixel,\n required this.childreenLenght})\n : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n return ClipRect(\n child: SizedBox(\n height: MediaQuery.of(context).size.height,\n width: MediaQuery.of(context).size.width,\n child: Stack(\n fit: StackFit.expand,\n children: [\n FractionalTranslation(\n translation: Offset(0.0, -_calculateParallax(context)),\n child: child),\n const Positioned(\n bottom: 200,\n right: 20,\n child: Text(\n \"Parallax\",\n style: TextStyle(\n color: Colors.white,\n fontSize: 30,\n fontWeight: FontWeight.bold),\n )),\n const Positioned(\n bottom: 12,\n right: 20,\n left: 20,\n child: Padding(\n padding: EdgeInsets.all(20.0),\n child: Text(\n \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.\",\n style: TextStyle(\n color: Colors.white,\n fontSize: 16,\n ),\n ),\n ))\n ],\n )),\n );\n }\n\n double _calculateParallax(BuildContext context) {\n final double height = MediaQuery.of(context).size.height;\n final double pageHeight = height * index;\n final double childPosition = (pageHeight - pixel) / height;\n return childPosition.isNaN ? 0.0 : childPosition;\n }\n}\n class MyApp extends StatelessWidget {\n const MyApp({Key? key}) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n double height = MediaQuery.of(context).size.height;\n double width = MediaQuery.of(context).size.width;\n return Scaffold(\n body: Parallax(childreen: [\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg\",\n height: height,\n // width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg\",\n height: height,\n width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg\",\n height: height,\n // width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg\",\n height: height,\n width: width,\n fit: BoxFit.fitHeight,\n ),\n ]),\n );\n }\n}\n class TornEffect extends CustomClipper<Path>{\n ///how much the torn effect will be\n final int intensity;\n\n TornEffect({required this.intensity});\n\n @override\n ui.Path getClip(ui.Size size) {\n\n var path = Path();\n //make sure path on left top corner\n path.moveTo(0.0, 0.0);\n\n var random = math.Random();\n \n //to prevent blankSpace, move y to top (must always negative):\n double ybase = -20.0;\n\n //top:\n double topProgress = 0.0;\n while(topProgress < size.width){\n bool curve = random.nextBool();\n if(curve){\n \n double cpx = topProgress + random.nextInt(intensity) * 0.5 * negativePositive();\n double cpy = ybase + (random.nextInt(intensity) * 0.25 * negativePositive());\n\n double x = topProgress + random.nextInt(intensity)* 1.0 * negativePositive();\n double y = ybase + (random.nextInt(intensity) * 0.5 * negativePositive());\n\n path.quadraticBezierTo(\n cpx,\n cpy,\n x,\n y\n );\n topProgress += x.abs();\n }\n else {\n \n double x = topProgress + random.nextInt(intensity) * 1.0 * negativePositive();\n double y = ybase + (random.nextInt(intensity) * 0.5 * negativePositive());\n path.lineTo(x, y);\n topProgress += x.abs();\n }\n }\n //make sure top right corner got shape\n path.lineTo(size.width, 0.0);\n\n // line to bottom right corner\n path.lineTo(size.width, size.height);\n\n // you can build bottom rip effect later:\n //double bottomProgress = 0.0;\n //while(){}\n\n // bottom left\n path.lineTo(0.0, size.height);\n\n //close it with another line\n path.close();\n return path;\n\n }\n\n double negativePositive(){\n var random = math.Random();\n bool negativePositive = random.nextBool();\n double result = negativePositive ? 1.0: -1.0;\n return result;\n }\n\n @override\n bool shouldReclip(covariant CustomClipper<ui.Path> oldClipper) {\n // TODO: implement shouldReclip\n //return this != oldClipper;\n // return false for performance, or rebuilt every scroll\n return false;\n }\n\n}\n return ClipPath(\n clipper: TornEffect(intensity: 21),\n child: SizedBox(\n height: MediaQuery.of(context).size.height,\n width: MediaQuery.of(context).size.width,\n child: Stack(\n fit: StackFit.expand,\n children: [\n"
},
{
"answer_id": 74670593,
"author": "Cedar",
"author_id": 1870968,
"author_profile": "https://Stackoverflow.com/users/1870968",
"pm_score": 0,
"selected": false,
"text": "// Create the ScrollController\nfinal scrollController = ScrollController();\n\n// Retrieve the current scroll position\nfinal scrollPosition = scrollController.position.pixels;\n\n// Define the range of the animation (in this case, from 0.0 to 1.0)\nfinal animationRange = Tween(begin: 0.0, end: 1.0);\n\n// Calculate the animation value based on the current scroll position\nfinal animationValue = animationRange.transform(scrollPosition);\n\n// Use the animation value to animate the position of the background images\nreturn SingleChildScrollView(\n controller: scrollController,\n child: Stack(\n children: [\n // Background image 1\n Positioned(\n top: animationValue * 100.0, // This will move the image 100 pixels downwards as the user scrolls\n child: Image.asset(\"image1.png\"),\n ),\n // Background image 2\n Positioned(\n top: -animationValue * 100.0, // This will move the image 100 pixels upwards as the user scrolls\n child: Image.asset(\"image2.png\"),\n ),\n ],\n ),\n);\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19904553/"
] |
74,499,703
|
<pre><code>// YOUR CODE
let letters = '';
function lettersAfter(haystack, needle, limit){
('any value','a', 2);
for(let i = 0; i < haystack.length; i++){
console.log(i);
if(haystack[i] === needle){
for(let j = 0; j < limit; j++) {
console.log(j);
let innerChar = haystack[i + j + 1];
console.log(innerChar);
letters += innerChar;
console.log(letters);
}
return letters;
}
}
}
// DO NOT EDIT BELOW
module.exports = lettersAfter;
</code></pre>
<p>I am doing tests (that are not written by me) and I should get the values listed below:</p>
<p>lettersAfter('any value','a', 2); // ==> ny
lettersAfter('indefatigable', 'a', 4); // => tiga</p>
<p>I receive ==>nytiga</p>
<p>I can't figure out why it is pushing the two of them together, functions as much information that can be given is super helpful, I am a beginner!</p>
|
[
{
"answer_id": 74646549,
"author": "Sayyid J",
"author_id": 15366030,
"author_profile": "https://Stackoverflow.com/users/15366030",
"pm_score": 3,
"selected": true,
"text": "ScrollMetrics ScrollNotification class Parallax extends StatefulWidget {\n const Parallax({Key? key, required this.childreen}) : super(key: key);\n final List<Widget> childreen;\n\n @override\n State<Parallax> createState() => _ParallaxState();\n}\n\nclass _ParallaxState extends State<Parallax> {\n late double _pixel;\n\n @override\n void initState() {\n // TODO: implement initState\n super.initState();\n _pixel = 0;\n }\n\n @override\n Widget build(BuildContext context) {\n return NotificationListener<ScrollNotification>(\n onNotification: (notif) {\n setState(() {\n _pixel = notif.metrics.pixels;\n });\n return true;\n },\n child: SingleChildScrollView(\n child: Column(\n children: List.generate(\n widget.childreen.length,\n (index) => _ParalaxChild(\n index: index,\n pixel: _pixel,\n childreenLenght: widget.childreen.length,\n child: widget.childreen[index])),\n ),\n ),\n );\n }\n}\n\nclass _ParalaxChild extends StatelessWidget {\n final int index;\n final Widget child;\n final double pixel;\n final int childreenLenght;\n const _ParalaxChild(\n {Key? key,\n required this.child,\n required this.index,\n required this.pixel,\n required this.childreenLenght})\n : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n return ClipRect(\n child: SizedBox(\n height: MediaQuery.of(context).size.height,\n width: MediaQuery.of(context).size.width,\n child: Stack(\n fit: StackFit.expand,\n children: [\n FractionalTranslation(\n translation: Offset(0.0, -_calculateParallax(context)),\n child: child),\n const Positioned(\n bottom: 200,\n right: 20,\n child: Text(\n \"Parallax\",\n style: TextStyle(\n color: Colors.white,\n fontSize: 30,\n fontWeight: FontWeight.bold),\n )),\n const Positioned(\n bottom: 12,\n right: 20,\n left: 20,\n child: Padding(\n padding: EdgeInsets.all(20.0),\n child: Text(\n \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.\",\n style: TextStyle(\n color: Colors.white,\n fontSize: 16,\n ),\n ),\n ))\n ],\n )),\n );\n }\n\n double _calculateParallax(BuildContext context) {\n final double height = MediaQuery.of(context).size.height;\n final double pageHeight = height * index;\n final double childPosition = (pageHeight - pixel) / height;\n return childPosition.isNaN ? 0.0 : childPosition;\n }\n}\n class MyApp extends StatelessWidget {\n const MyApp({Key? key}) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n double height = MediaQuery.of(context).size.height;\n double width = MediaQuery.of(context).size.width;\n return Scaffold(\n body: Parallax(childreen: [\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg\",\n height: height,\n // width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg\",\n height: height,\n width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg\",\n height: height,\n // width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg\",\n height: height,\n width: width,\n fit: BoxFit.fitHeight,\n ),\n ]),\n );\n }\n}\n class TornEffect extends CustomClipper<Path>{\n ///how much the torn effect will be\n final int intensity;\n\n TornEffect({required this.intensity});\n\n @override\n ui.Path getClip(ui.Size size) {\n\n var path = Path();\n //make sure path on left top corner\n path.moveTo(0.0, 0.0);\n\n var random = math.Random();\n \n //to prevent blankSpace, move y to top (must always negative):\n double ybase = -20.0;\n\n //top:\n double topProgress = 0.0;\n while(topProgress < size.width){\n bool curve = random.nextBool();\n if(curve){\n \n double cpx = topProgress + random.nextInt(intensity) * 0.5 * negativePositive();\n double cpy = ybase + (random.nextInt(intensity) * 0.25 * negativePositive());\n\n double x = topProgress + random.nextInt(intensity)* 1.0 * negativePositive();\n double y = ybase + (random.nextInt(intensity) * 0.5 * negativePositive());\n\n path.quadraticBezierTo(\n cpx,\n cpy,\n x,\n y\n );\n topProgress += x.abs();\n }\n else {\n \n double x = topProgress + random.nextInt(intensity) * 1.0 * negativePositive();\n double y = ybase + (random.nextInt(intensity) * 0.5 * negativePositive());\n path.lineTo(x, y);\n topProgress += x.abs();\n }\n }\n //make sure top right corner got shape\n path.lineTo(size.width, 0.0);\n\n // line to bottom right corner\n path.lineTo(size.width, size.height);\n\n // you can build bottom rip effect later:\n //double bottomProgress = 0.0;\n //while(){}\n\n // bottom left\n path.lineTo(0.0, size.height);\n\n //close it with another line\n path.close();\n return path;\n\n }\n\n double negativePositive(){\n var random = math.Random();\n bool negativePositive = random.nextBool();\n double result = negativePositive ? 1.0: -1.0;\n return result;\n }\n\n @override\n bool shouldReclip(covariant CustomClipper<ui.Path> oldClipper) {\n // TODO: implement shouldReclip\n //return this != oldClipper;\n // return false for performance, or rebuilt every scroll\n return false;\n }\n\n}\n return ClipPath(\n clipper: TornEffect(intensity: 21),\n child: SizedBox(\n height: MediaQuery.of(context).size.height,\n width: MediaQuery.of(context).size.width,\n child: Stack(\n fit: StackFit.expand,\n children: [\n"
},
{
"answer_id": 74670593,
"author": "Cedar",
"author_id": 1870968,
"author_profile": "https://Stackoverflow.com/users/1870968",
"pm_score": 0,
"selected": false,
"text": "// Create the ScrollController\nfinal scrollController = ScrollController();\n\n// Retrieve the current scroll position\nfinal scrollPosition = scrollController.position.pixels;\n\n// Define the range of the animation (in this case, from 0.0 to 1.0)\nfinal animationRange = Tween(begin: 0.0, end: 1.0);\n\n// Calculate the animation value based on the current scroll position\nfinal animationValue = animationRange.transform(scrollPosition);\n\n// Use the animation value to animate the position of the background images\nreturn SingleChildScrollView(\n controller: scrollController,\n child: Stack(\n children: [\n // Background image 1\n Positioned(\n top: animationValue * 100.0, // This will move the image 100 pixels downwards as the user scrolls\n child: Image.asset(\"image1.png\"),\n ),\n // Background image 2\n Positioned(\n top: -animationValue * 100.0, // This will move the image 100 pixels upwards as the user scrolls\n child: Image.asset(\"image2.png\"),\n ),\n ],\n ),\n);\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20547246/"
] |
74,499,718
|
<pre><code>class Test
{
public $prop1;
public function __get(string $n)
{
echo '__GET: '.$n.' - but why?<br>';
die;
}
}
$t = new Test();
$x1 = new \stdClass();
$t->prop2 = &$x1;
echo '.';
die;
</code></pre>
<p><a href="https://onlinephp.io/c/f7f16" rel="noreferrer">https://onlinephp.io/c/f7f16</a></p>
<p>here you can see, I create an <code>stdClass</code> object, try to pass it to a non-exists variable, and <code>__get()</code> gets executed - even though I was just tryting to write it, instead of reading. And if I didn't <code>die()</code> it, I get <code>Indirect modification of overloaded property has no effect</code> exception.</p>
<p>If I have this (no reference)</p>
<pre><code>class Test
{
public $prop1;
public function __get(string $n)
{
echo '__GET: '.$n.' - but why?<br>';
die;
}
}
$t = new Test();
$x1 = new \stdClass();
$t->prop2 = $x1;
echo '.';
die;
</code></pre>
<p><a href="https://onlinephp.io/c/3afef" rel="noreferrer">https://onlinephp.io/c/3afef</a></p>
<p>everything works fine, but why?</p>
|
[
{
"answer_id": 74525435,
"author": "hakre",
"author_id": 367456,
"author_profile": "https://Stackoverflow.com/users/367456",
"pm_score": 2,
"selected": false,
"text": "$t->prop2 $t->prop2 __get() $t __get() $t = new class() extends stdClass\n{\n public function __get(string $name) {\n $x = null;\n return $x;\n }\n};\n\n$t->prop2 = &$x1;\n"
},
{
"answer_id": 74528118,
"author": "Jabbar",
"author_id": 16930239,
"author_profile": "https://Stackoverflow.com/users/16930239",
"pm_score": -1,
"selected": false,
"text": "__get() __get public function &__get ( $index )\n"
},
{
"answer_id": 74576390,
"author": "user3840170",
"author_id": 3840170,
"author_profile": "https://Stackoverflow.com/users/3840170",
"pm_score": 4,
"selected": true,
"text": "__get class Globalses {\n public function& __get(string $name) {\n echo \"{$name} GET!\\n\";\n return $GLOBALS[$name];\n }\n}\n\n$obj = new Globalses;\n\n$foo = [0, 1, 2, 3];\n$obj->foo[] = 4; // foo GET!\necho 'foo='; debug_zval_dump($foo);\n\n$bar = 42;\n$var =& $obj->bar; // bar GET!\n$var = 69;\necho 'bar='; debug_zval_dump($bar);\n & function& __get =& $obj->prop =& (expr) $obj->prop (expr) __get $obj->prop =& expr zend_assign_to_property_reference zend_fetch_property_address get_property_ptr_ptr read_property zend_std_read_property __get zend_std_read_property __get function& __get E_NOTICE zend_std_read_property zend_fetch_property_address zend_assign_to_property_reference __get"
},
{
"answer_id": 74590685,
"author": "Barkermn01",
"author_id": 493804,
"author_profile": "https://Stackoverflow.com/users/493804",
"pm_score": 1,
"selected": false,
"text": "__get() $obj = new \\stdClass();\n$test = \"hello\";\n$obj->var = &%test;\n $obj->var $test __get __get __get"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043342/"
] |
74,499,731
|
<p>I am new to the MERN stack and I want to store user information into the MongoDB which has two string attributes "name" and "role".</p>
<p>I am getting an error in the browser console which states "<strong>Failed to load resource: Request timeout</strong>" and "<strong>Unhandled Promise Rejection: AxiosError: timeout exceeded</strong>"</p>
<p><strong>server index.js</strong></p>
<pre><code>const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
app = express();
const bookModel = require("./models/book");
const userModel = require("./models/user");
app.use(express.json());
app.use(cors);
// mongoose.connect('mongodb://mh_user:<credentials>').then(() => {console.log('test')});
mongoose.connect("mongodb://mh_user:<credentials>", {
useNewUrlParser: true,
})
// usermodel
app.postUser("/insert", async (req, res) => {
const userName = req.body.userName
const role = req.body.role
const user = new userModel({ username: userName, role: role })
try {
await userModel.save();
} catch (err) {
console.log(err);
}
});
app.getUser("/read", async (req, res) => {
userModel.find({}, (err, result) => {
if(err) {
res.send(err)
}
res.send(result)
})
});
// bookmodel
app.post("/insert", async (req, res) => {
const bookName = req.body.bookName
const ISBN = req.body.ISBN
const book = new bookModel({ bookname: bookName, ISBN: ISBN })
try {
await bookModel.save();
} catch (err) {
console.log(err);
}
});
app.get("/read", async (req, res) => {
bookModel.find({}, (err, result) => {
if(err) {
res.send(err)
}
res.send(result)
})
});
app.listen(3001, () => {
console.log("Server running on port 3001 ...");
})
</code></pre>
<p><strong>client adduser.js</strong></p>
<pre><code>import styles from './Home.module.css'
import React, { useState } from "react";
import Axios from "axios"
export default function AddUser() {
const [userName, setUserName] = useState("");
const [role, setRole] = useState("");
const addToDatabase = () => {
Axios.post("http://localhost:3001/insert", { userName: userName, role: role })
}
return (
<div className={styles.container}>
<main className={styles.main}>
<h1 className={styles.title}>
Fügen Sie einen <a>neuen Nutzer</a> hinzu
</h1>
<p className={styles.description}>
Create - Operation{' '}
</p>
<div className={styles.grid}>
<form className={styles.table}>
<label>
<input
onChange={(event) => {
setUserName(event.target.value);
}}
type="name" placeholder='name'
/>
</label>
<label>
<input
onChange={(event) => {
setRole(event.target.value);
}}
type="role" placeholder='role'
/>
</label>
</form>
</div>
<br></br>
<button
onClick={addToDatabase}
>speichern</button>
<br></br>
<a href="http://localhost:3000/">
<button>Hauptmenü</button>
</a>
</main>
<footer className={styles.footer}>
<a>
Powered by{' '}- Gruppe 1
</a>
</footer>
</div>
);
}
</code></pre>
<p><strong>server user.js</strong></p>
<pre><code>const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
role: {
type: String,
required: true,
}
});
const user = mongoose.model('userData', userSchema)
module.exports = user
</code></pre>
|
[
{
"answer_id": 74525435,
"author": "hakre",
"author_id": 367456,
"author_profile": "https://Stackoverflow.com/users/367456",
"pm_score": 2,
"selected": false,
"text": "$t->prop2 $t->prop2 __get() $t __get() $t = new class() extends stdClass\n{\n public function __get(string $name) {\n $x = null;\n return $x;\n }\n};\n\n$t->prop2 = &$x1;\n"
},
{
"answer_id": 74528118,
"author": "Jabbar",
"author_id": 16930239,
"author_profile": "https://Stackoverflow.com/users/16930239",
"pm_score": -1,
"selected": false,
"text": "__get() __get public function &__get ( $index )\n"
},
{
"answer_id": 74576390,
"author": "user3840170",
"author_id": 3840170,
"author_profile": "https://Stackoverflow.com/users/3840170",
"pm_score": 4,
"selected": true,
"text": "__get class Globalses {\n public function& __get(string $name) {\n echo \"{$name} GET!\\n\";\n return $GLOBALS[$name];\n }\n}\n\n$obj = new Globalses;\n\n$foo = [0, 1, 2, 3];\n$obj->foo[] = 4; // foo GET!\necho 'foo='; debug_zval_dump($foo);\n\n$bar = 42;\n$var =& $obj->bar; // bar GET!\n$var = 69;\necho 'bar='; debug_zval_dump($bar);\n & function& __get =& $obj->prop =& (expr) $obj->prop (expr) __get $obj->prop =& expr zend_assign_to_property_reference zend_fetch_property_address get_property_ptr_ptr read_property zend_std_read_property __get zend_std_read_property __get function& __get E_NOTICE zend_std_read_property zend_fetch_property_address zend_assign_to_property_reference __get"
},
{
"answer_id": 74590685,
"author": "Barkermn01",
"author_id": 493804,
"author_profile": "https://Stackoverflow.com/users/493804",
"pm_score": 1,
"selected": false,
"text": "__get() $obj = new \\stdClass();\n$test = \"hello\";\n$obj->var = &%test;\n $obj->var $test __get __get __get"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15815852/"
] |
74,499,783
|
<p>I have string with slash separated contains function names.</p>
<pre><code>e.g.
my_doc/desktop/customer=getCustomer()/getCsvFileName()/controller=getControllerName()
</code></pre>
<p>Within above string I want only function name <strong>i.e. getCustomer(), getControllerName() & getCsvFileName()</strong></p>
<p>I searched some regex like:</p>
<pre><code>let res = myString.match(/(?<=(function\s))(\w+)/g);
</code></pre>
<p>but its returning result as null.</p>
<p>Update:
Now I want to get function names without parentheses <code>()</code> <strong>i.e. getCustomer, getControllerName & getCsvFileName</strong></p>
<p>Please help me in this</p>
|
[
{
"answer_id": 74500418,
"author": "Soorya J",
"author_id": 18576371,
"author_profile": "https://Stackoverflow.com/users/18576371",
"pm_score": 0,
"selected": false,
"text": "/(?<=(function\\s))(\\w+)/g my_doc/desktop/customer=getCustomer()/getCsvFileName()/controller=getControllerName() let yourString = 'my_doc/desktop/customer=getCustomer()/getCsvFileName()/controller=getControllerName()';\n\nlet myReferenceString = 'SAMPLETEXTfunction sayHi()/function sayHello()';\n\n\nlet res = yourString.match(/(?<=(function\\s))(\\w+)/g);\nlet res2 = myReferenceString.match(/(?<=(function\\s))(\\w+)/g);\n\nconsole.log(\"Result of your string\", res);\nconsole.log(\"Result of my string\", res2); let myreferenceString = 'my_doc/desktop/customer=getCustomer()/getCsvFileName()/controller=getControllerName()'\n\nlet res = myreferenceString.match(/((?<==)(\\w+\\(\\)))|((?<=\\/)(\\w+\\(\\)))/g);\n\nconsole.log(\"Result\", res);"
},
{
"answer_id": 74500436,
"author": "Maniraj Murugan",
"author_id": 7785337,
"author_profile": "https://Stackoverflow.com/users/7785337",
"pm_score": 1,
"selected": false,
"text": "() /.*?\\([^)]*\\)/g = / item.split(/=|\\//) functionNames const string = `my_doc/desktop/customer=getCustomer()/getCsvFileName()/controller=getControllerName()`;\n\nconst functionNames = [];\n\nstring.match(/.*?\\([^)]*\\)/g).forEach(item => {\n const splitString = item.split(/=|\\//);\n const functionName = splitString[splitString.length - 1];\n functionNames.push(functionName);\n});\n\nconsole.log(functionNames);"
},
{
"answer_id": 74500524,
"author": "human bean",
"author_id": 17186475,
"author_profile": "https://Stackoverflow.com/users/17186475",
"pm_score": 2,
"selected": true,
"text": "const str = \"my_doc/desktop/customer=getCustomer()/getCsvFileName()/controller=getControllerName()\"\n\nlet tokens = [];\n\nfor (element of str.split(\"/\"))\n if (element.endsWith(\"()\"))\n tokens.push(element.split(\"=\")[1] ?? element.split(\"=\")[0])\n\nconsole.log(tokens); () = = const str = \"my_doc/desktop/customer=getCustomer()/getCsvFileName()/controller=getControllerName()\"\n\nlet tokens = str.split(\"/\")\n .filter(element => element.endsWith(\"()\"))\n .map(element => element.split(\"=\")[1] ?? element.split(\"=\")[0]);\n\nconsole.log(tokens);"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16915156/"
] |
74,499,805
|
<p>I want a <em>container</em> div:</p>
<ul>
<li>Which should take width of its children.</li>
<li>I want its children to align horizontally.</li>
<li>And container should be single horizontal line</li>
</ul>
<p>I don't want to use flex because then CSS tries to squeeze the children in containers width.
This is solution I came up with <strong>which seems to work</strong> but I want to better understand the properties I used, hence the questions.</p>
<pre><code> import React from 'react';
import './style.css';
export default function App() {
return (
<div className="container">
{[1, 2, 3, 4, 5, 6, 7, 8, 9].map((x) => {
return <div className="card">{x}</div>;
})}
</div>
);
}
</code></pre>
<p>css</p>
<pre><code> .container {
display: inline-block;
background: red;
white-space: nowrap;
}
.card {
display: inline-block;
width: 100px;
height: 100px;
}
</code></pre>
<ul>
<li>My main question is: why do we need <strong>two inline-block</strong> usages? (one on the container one on the cards)</li>
<li>You can see I had to add <code>white-space: nowrap;</code> was it necessary in this situation?</li>
</ul>
<p>Mainly I am interested in above questions, but if you <em>additionally</em> have a more elegant solution also, you can post it.</p>
|
[
{
"answer_id": 74500418,
"author": "Soorya J",
"author_id": 18576371,
"author_profile": "https://Stackoverflow.com/users/18576371",
"pm_score": 0,
"selected": false,
"text": "/(?<=(function\\s))(\\w+)/g my_doc/desktop/customer=getCustomer()/getCsvFileName()/controller=getControllerName() let yourString = 'my_doc/desktop/customer=getCustomer()/getCsvFileName()/controller=getControllerName()';\n\nlet myReferenceString = 'SAMPLETEXTfunction sayHi()/function sayHello()';\n\n\nlet res = yourString.match(/(?<=(function\\s))(\\w+)/g);\nlet res2 = myReferenceString.match(/(?<=(function\\s))(\\w+)/g);\n\nconsole.log(\"Result of your string\", res);\nconsole.log(\"Result of my string\", res2); let myreferenceString = 'my_doc/desktop/customer=getCustomer()/getCsvFileName()/controller=getControllerName()'\n\nlet res = myreferenceString.match(/((?<==)(\\w+\\(\\)))|((?<=\\/)(\\w+\\(\\)))/g);\n\nconsole.log(\"Result\", res);"
},
{
"answer_id": 74500436,
"author": "Maniraj Murugan",
"author_id": 7785337,
"author_profile": "https://Stackoverflow.com/users/7785337",
"pm_score": 1,
"selected": false,
"text": "() /.*?\\([^)]*\\)/g = / item.split(/=|\\//) functionNames const string = `my_doc/desktop/customer=getCustomer()/getCsvFileName()/controller=getControllerName()`;\n\nconst functionNames = [];\n\nstring.match(/.*?\\([^)]*\\)/g).forEach(item => {\n const splitString = item.split(/=|\\//);\n const functionName = splitString[splitString.length - 1];\n functionNames.push(functionName);\n});\n\nconsole.log(functionNames);"
},
{
"answer_id": 74500524,
"author": "human bean",
"author_id": 17186475,
"author_profile": "https://Stackoverflow.com/users/17186475",
"pm_score": 2,
"selected": true,
"text": "const str = \"my_doc/desktop/customer=getCustomer()/getCsvFileName()/controller=getControllerName()\"\n\nlet tokens = [];\n\nfor (element of str.split(\"/\"))\n if (element.endsWith(\"()\"))\n tokens.push(element.split(\"=\")[1] ?? element.split(\"=\")[0])\n\nconsole.log(tokens); () = = const str = \"my_doc/desktop/customer=getCustomer()/getCsvFileName()/controller=getControllerName()\"\n\nlet tokens = str.split(\"/\")\n .filter(element => element.endsWith(\"()\"))\n .map(element => element.split(\"=\")[1] ?? element.split(\"=\")[0]);\n\nconsole.log(tokens);"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,499,834
|
<p>I have Three datasets that I want to MERGE/JOIN.</p>
<p>This This examples only include the first participants I have a total of 25</p>
<p>df1</p>
<pre><code> ID Grup pretest
1 1 A 2
2 1 A 1
3 1 A 3
4 2 B NA
5 2 B 1
6 2 B 3
7 3 A 2
8 3 A 1
9 3 A NA
10 4 B 2
11 4 B 1
12 4 B 3
</code></pre>
<p>df2 (this is missing one ID (5)</p>
<pre><code> ID Grup posttest
1 1 A NA
2 1 A 5
3 1 A 4
4 2 B 2
5 2 B 4
6 2 B 3
7 3 A 5
8 3 A 6
9 3 A 3
10 6 B 4
11 6 B 2
12 6 B NA
</code></pre>
<p>Updated
df3( this have 5 Measurements for per ID)</p>
<pre><code> ID Grup traning
1 1 A 2
2 1 A 6
3 1 A 3
4 1 A NA
5 1 A 1
6 2 B 3
7 2 B 4
8 2 B 1
9 2 B NA
10 2 B 2
11 3 A 1
12 3 A 3
</code></pre>
<p>I’ve been trying <code>merge()</code> and <code>full_join()</code> but both end up creating duplicates that I don’t want.</p>
<p>It won’t recognize the <code>ID</code> as an independent value, it’s creating 9 <code>ID</code>s for every <code>ID</code> value.</p>
<pre><code>New <- merge(df1, df2, by= 'ID')
New <- full_join(df1, df2, By = "ID")
</code></pre>
<p>Setting <code>all = TRUE</code> doesn’t help.</p>
<p>I need the dataset to look like this</p>
<pre><code> ID Grup pretest posttest traning
1 1 A 2 NA. 3
2 1 A 1 5. 4
3 1 A 3 4. 4
4 1 A NA Na. 4
5 1. A NA Na. 3
6 2 B 3 3. Na
7 2 B. 2 5. 3
8 2 B Na 6. 2
9 2 B NA Na. 5
10 2 B Na Na. 4
11 3 A. 1 2. 3
12 3 A. 3 3. 4
</code></pre>
|
[
{
"answer_id": 74499882,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 2,
"selected": false,
"text": "df1 <- cbind(iid = 1:nrow(df1), df1)\ndf2 <- cbind(iid = 1:nrow(df2), df2)\n dplyr library(dplyr)\n\nleft_join(df1, df2, c(\"iid\", \"ID\", \"Grup\"))[,-1]\n ID Grup pretest posttest\n1 1 A 2 NA\n2 1 A 1 5\n3 1 A 3 4\n4 2 B NA 2\n5 2 B 1 4\n6 2 B 3 3\n7 3 A 2 5\n8 3 A 1 6\n9 3 A NA 3\n10 4 B 2 4\n11 4 B 1 2\n12 4 B 3 NA\n merge merge(df1, df2, c(\"iid\", \"ID\", \"Grup\"))[,-1]\n ID Grup pretest posttest\n1 1 A 2 NA\n2 4 B 2 4\n3 4 B 1 2\n4 4 B 3 NA\n5 1 A 1 5\n6 1 A 3 4\n7 2 B NA 2\n8 2 B 1 4\n9 2 B 3 3\n10 3 A 2 5\n11 3 A 1 6\n12 3 A NA 3\n df1 <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L,\n4L, 4L), Grup = c(\"A\", \"A\", \"A\", \"B\", \"B\", \"B\", \"A\", \"A\", \"A\",\n\"B\", \"B\", \"B\"), pretest = c(2L, 1L, 3L, NA, 1L, 3L, 2L, 1L, NA,\n2L, 1L, 3L)), class = \"data.frame\", row.names = c(\"1\", \"2\", \"3\",\n\"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\"))\n\ndf2 <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L,\n4L, 4L), Grup = c(\"A\", \"A\", \"A\", \"B\", \"B\", \"B\", \"A\", \"A\", \"A\",\n\"B\", \"B\", \"B\"), posttest = c(NA, 5L, 4L, 2L, 4L, 3L, 5L, 6L,\n3L, 4L, 2L, NA)), class = \"data.frame\", row.names = c(\"1\", \"2\",\n\"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\"))\n"
},
{
"answer_id": 74500269,
"author": "langtang",
"author_id": 4447540,
"author_profile": "https://Stackoverflow.com/users/4447540",
"pm_score": 2,
"selected": false,
"text": "cbind() cbind(df1,df2[,3,F])\n ID Grup pretest posttest\n1 1 A 2 NA\n2 1 A 1 5\n3 1 A 3 4\n4 2 B NA 2\n5 2 B 1 4\n6 2 B 3 3\n7 3 A 2 5\n8 3 A 1 6\n9 3 A NA 3\n10 4 B 2 4\n11 4 B 1 2\n12 4 B 3 NA\n"
},
{
"answer_id": 74500325,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 1,
"selected": false,
"text": "library(tibble)\nlibrary(dplyr)\n\nleft_join(rownames_to_column(df1), df2 %>% rownames_to_column() , by=\"rowname\") %>% \n select(ID = ID.x, Grup = Grup.x, pretest, posttest)\n ID Grup pretest posttest\n1 1 A 2 NA\n2 1 A 1 5\n3 1 A 3 4\n4 2 B NA 2\n5 2 B 1 4\n6 2 B 3 3\n7 3 A 2 5\n8 3 A 1 6\n9 3 A NA 3\n10 4 B 2 4\n11 4 B 1 2\n12 4 B 3 NA\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19944455/"
] |
74,499,856
|
<p>can somebody explain, why does this loop run endlessly?
I thought that the boolean **hasNext() ** is only true if there are no elements anymore. So when I type something in the loop runs like I typed something that goes endless too.
And what are these nmbers? please explain</p>
<pre><code>
import java.util.Scanner;
public class Vocabulary {
public static void main(String[] args) {
Scanner standardInput = new Scanner(System.in);
for(int i = 0; standardInput.hasNext(); i++){
System.out.print(i);
}
}
}
</code></pre>
<p>I researched in Internet about hasNext(). I know what it makes and I know how the for-loop works. But I don´t know why hasNext in for-loop makes the programm run endlessly.</p>
<p>Edit:</p>
<p>On the other hand, this code works. Why does this code work?</p>
<pre><code>import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
Scanner standardInput = new Scanner(System.in);
double sum = 0;
while(standardInput.hasNext()) {
double nextNumber = standardInput.nextDouble();
sum += nextNumber;
}
System.out.println("The Sum is " + sum + ".");
}
}
</code></pre>
|
[
{
"answer_id": 74499882,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 2,
"selected": false,
"text": "df1 <- cbind(iid = 1:nrow(df1), df1)\ndf2 <- cbind(iid = 1:nrow(df2), df2)\n dplyr library(dplyr)\n\nleft_join(df1, df2, c(\"iid\", \"ID\", \"Grup\"))[,-1]\n ID Grup pretest posttest\n1 1 A 2 NA\n2 1 A 1 5\n3 1 A 3 4\n4 2 B NA 2\n5 2 B 1 4\n6 2 B 3 3\n7 3 A 2 5\n8 3 A 1 6\n9 3 A NA 3\n10 4 B 2 4\n11 4 B 1 2\n12 4 B 3 NA\n merge merge(df1, df2, c(\"iid\", \"ID\", \"Grup\"))[,-1]\n ID Grup pretest posttest\n1 1 A 2 NA\n2 4 B 2 4\n3 4 B 1 2\n4 4 B 3 NA\n5 1 A 1 5\n6 1 A 3 4\n7 2 B NA 2\n8 2 B 1 4\n9 2 B 3 3\n10 3 A 2 5\n11 3 A 1 6\n12 3 A NA 3\n df1 <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L,\n4L, 4L), Grup = c(\"A\", \"A\", \"A\", \"B\", \"B\", \"B\", \"A\", \"A\", \"A\",\n\"B\", \"B\", \"B\"), pretest = c(2L, 1L, 3L, NA, 1L, 3L, 2L, 1L, NA,\n2L, 1L, 3L)), class = \"data.frame\", row.names = c(\"1\", \"2\", \"3\",\n\"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\"))\n\ndf2 <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L,\n4L, 4L), Grup = c(\"A\", \"A\", \"A\", \"B\", \"B\", \"B\", \"A\", \"A\", \"A\",\n\"B\", \"B\", \"B\"), posttest = c(NA, 5L, 4L, 2L, 4L, 3L, 5L, 6L,\n3L, 4L, 2L, NA)), class = \"data.frame\", row.names = c(\"1\", \"2\",\n\"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\"))\n"
},
{
"answer_id": 74500269,
"author": "langtang",
"author_id": 4447540,
"author_profile": "https://Stackoverflow.com/users/4447540",
"pm_score": 2,
"selected": false,
"text": "cbind() cbind(df1,df2[,3,F])\n ID Grup pretest posttest\n1 1 A 2 NA\n2 1 A 1 5\n3 1 A 3 4\n4 2 B NA 2\n5 2 B 1 4\n6 2 B 3 3\n7 3 A 2 5\n8 3 A 1 6\n9 3 A NA 3\n10 4 B 2 4\n11 4 B 1 2\n12 4 B 3 NA\n"
},
{
"answer_id": 74500325,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 1,
"selected": false,
"text": "library(tibble)\nlibrary(dplyr)\n\nleft_join(rownames_to_column(df1), df2 %>% rownames_to_column() , by=\"rowname\") %>% \n select(ID = ID.x, Grup = Grup.x, pretest, posttest)\n ID Grup pretest posttest\n1 1 A 2 NA\n2 1 A 1 5\n3 1 A 3 4\n4 2 B NA 2\n5 2 B 1 4\n6 2 B 3 3\n7 3 A 2 5\n8 3 A 1 6\n9 3 A NA 3\n10 4 B 2 4\n11 4 B 1 2\n12 4 B 3 NA\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20472612/"
] |
74,499,880
|
<p>In my build scripts I need to evaluate a Cypress configuration file. I'm using the following script:</p>
<pre class="lang-js prettyprint-override"><code>let appdata = process.env.LOCALAPPDATA;
let version = `11.0.1`;
let src = `${appdata}/Cypress/Cache/${version}/Cypress/resources/app/node_modules/@packages/data-context/src`;
const DataContext = require(`${src}/DataContext.js`).DataContext;
const ProjectConfigManager = require(`${src}/data/ProjectConfigManager.js`).ProjectConfigManager;
(async() => {
const ctx = new DataContext({
schema: null,
schemaCloud: null,
modeOptions: "run",
appApi: {},
localSettingsApi: {},
authApi: {
} ,
configApi: {
},
projectApi: {
} ,
electronApi: {
} ,
browserApi: {
},
})
let configManager = new ProjectConfigManager({
ctx,
configFile: 'C:\\work\\sample\\sample.config.ts',
projectRoot: 'C:\\work\\sample',
handlers: [],
hasCypressEnvFile: false,
eventRegistrar: null/*new EventRegistrar()*/,
onError: (error) => {},
onInitialConfigLoaded: () => {},
onFinalConfigLoaded: () => Promise.resolve(),
refreshLifecycle: () => Promise.resolve(),
})
configManager.configFilePath = "sample.config.ts"
configManager.setTestingType('e2e')
let cfg = await configManager.getConfigFileContents()
console.log(JSON.stringify(cfg));
})();
</code></pre>
<p>It works well for <code>Cypress 10</code> version.
However, <code>Cypress 11</code> has introduced some changes that break this script. Though I adjusted the paths, I'm still unable to make it work again.
It currently fails with this error:</p>
<pre><code>Error: Cannot find module 'C:\Users\mbolotov\AppData\Local\Cypress\Cache\11.0.1\Cypress\resources\app\node_modules\graphql\index'. Please verify that the package.json has a valid "main" entry
</code></pre>
<p>How can I fix this problem (without making changes to the Cypress installation)?</p>
<p>OR</p>
<p>Is there any other way to evaluate a Cypress configuration file (say from the command line) and obtain its values?</p>
|
[
{
"answer_id": 74505388,
"author": "Fody",
"author_id": 16997707,
"author_profile": "https://Stackoverflow.com/users/16997707",
"pm_score": 1,
"selected": false,
"text": "${process.env.CYPRESS_CACHE_FOLDER}/10.11.0/Cypress/resources/app /node_modules /node_modules/graphql/index.js /node_modules/graphql"
},
{
"answer_id": 74596893,
"author": "Paolo",
"author_id": 16791505,
"author_profile": "https://Stackoverflow.com/users/16791505",
"pm_score": 2,
"selected": false,
"text": "/scripts .cy.js const cypress = require('cypress')\nconst fs = require('fs')\n\nfs.writeFileSync('../cypress/e2e/null-test.cy.js', 'it(\"\", ()=>{})')\n\ncypress.run({\n project: '..',\n spec: '../cypress/e2e/null-test.cy.js',\n quiet: true\n}).then(results => {\n if (results.status === 'failed') {\n console.log(results)\n } else {\n console.log(results.config.resolved) // output resolved config\n }\n})\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13109074/"
] |
74,499,887
|
<pre><code>#include <iostream>
int binary_search(int arr[], int size, int target)
{
int first = 0;
int last = size - 1;
int midpoint = (last + first) / 2;
while(first <= last)
{
if(arr[midpoint] == target)
{
return midpoint;
}
else if(arr[midpoint] < target)
{
first = midpoint + 1;
}
else if(arr[midpoint] > target)
{
last = midpoint - 1;
}
}
return 0;
}
int main()
{
int arr[] = {4, 12, 23, 43, 50, 60, 230, 290};
int size = sizeof(arr)/sizeof(arr[0]);
int target = 12;
std::cout << binary_search(arr, size, target);
}
</code></pre>
<p>if the midpoint value is lesser than the target it increases 'first' and if it's greater than the target it instead decreases 'last'. This continues until 'first' is equal to 'last'.
I saw another program where they called the function recursively but i wanted to make it work without it, what exactly am i doing wrong?</p>
|
[
{
"answer_id": 74499936,
"author": "Nesmeg",
"author_id": 14871546,
"author_profile": "https://Stackoverflow.com/users/14871546",
"pm_score": 2,
"selected": false,
"text": "while(first <= last)\n{\n if(arr[midpoint] == target)\n {\n return midpoint;\n }\n else if(arr[midpoint] < target)\n {\n first = midpoint + 1;\n }\n else if(arr[midpoint] > target)\n {\n last = midpoint - 1;\n \n }\n}\n"
},
{
"answer_id": 74499974,
"author": "Pepijn Kramer",
"author_id": 16649550,
"author_profile": "https://Stackoverflow.com/users/16649550",
"pm_score": 3,
"selected": true,
"text": "#include <iostream>\n#include <vector>\n\nauto binary_search(const std::vector<int>& values, int value)\n{\n std::size_t first = 0;\n std::size_t last = values.size() - 1; // use vector it keeps track of its size\n \n while (first <= last)\n {\n std::size_t midpoint = (last + first) / 2; // you forgot to update midpoint each loop\n\n if (values[midpoint] == value)\n {\n return values[midpoint]; // <== do you want to return the position or the value?\n }\n \n if (values[midpoint] < value)\n {\n first = midpoint + 1;\n }\n else if (values[midpoint] > value)\n {\n last = midpoint - 1;\n }\n }\n\n return 0;\n}\n\nint main()\n{\n std::vector<int> values{ 4, 12, 23, 43, 50, 60, 230, 290 };\n std::cout << binary_search(values, 12);\n return 0;\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17188389/"
] |
74,499,911
|
<p><a href="https://i.stack.imgur.com/4J4Hm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4J4Hm.png" alt="enter image description here" /></a></p>
<p>I have an interface that contains the card shown in the picture, and as it appears that the card contains a date, but the date is in the form:</p>
<pre><code>'mm/dd/yyyy'
</code></pre>
<p>And I want it to be in the form:</p>
<pre><code>'dd/mm/yyyy'
</code></pre>
<p>Knowing that I want the content inside the parentheses to remain of type "date", not string or another type.</p>
<p>How do I do that?</p>
<p>in this file i am trying to use moment but i get "Invalid Date",</p>
<pre><code>date = {moment(w?.startingDate!, dateFormat).toDate()}
</code></pre>
<p>How can i solve my problem?</p>
<p>file.tsx:</p>
<pre><code>import React from 'react';
import { useDrop } from 'react-dnd';
import { FormattedMessage } from 'react-intl';
import PatientCard from './PatientCard';
import { useSchedule } from './ScheduleContext';
import moment from 'moment';
import { dateFormat } from "../../../constants";
export default function Queue() {
const { waitingListData, unschedule } = useSchedule();
const [{ isOver, name }, drop] = useDrop(
() => ({
accept: 'card',
// canDrop: () => content === '' || content === undefined,
drop: (item: any) => {
if (item.socketId === 0) return;
unschedule(item.scheduleId);
},
collect: (monitor) => ({
isOver: !!monitor.isOver(),
name: monitor.getItem()?.name,
}),
}),
[],
);
let StartingDate = (startingDate: string): any => {
console.log('ssss: ', startingDate);
let date: any = moment(startingDate).format('DD/MM/YYYY');
console.log('convertToDate: ', typeof(date), date);
return date;
}
return (
<div ref={drop} className='queue'>
<span style={{ position: 'absolute', left: '5px' }}>
<FormattedMessage id='appointmentRequests' />
</span>
{waitingListData?.items
// TODO: Check for ending date
?.filter((w) => w.endingDate === null)
.map((w) => (
<PatientCard
from='Queue'
socketId={0}
id={w.id}
waitingListId={w.id}
key={w.id}
name={w.patient?.label}
// date={StartingDate(w?.startingDate!)}
date = {moment(w?.startingDate!, dateFormat).toDate()}
sessionState={w.sessionState}
priority={w.priority}
city={w.city}
supervisoryDoctor={w?.supervisoryDoctor}
patientId={w?.patient?.value}
case={w?.case}
/>
))}
{isOver && <PatientCard.Shadow name={name} />}
</div>
);
}
</code></pre>
|
[
{
"answer_id": 74499936,
"author": "Nesmeg",
"author_id": 14871546,
"author_profile": "https://Stackoverflow.com/users/14871546",
"pm_score": 2,
"selected": false,
"text": "while(first <= last)\n{\n if(arr[midpoint] == target)\n {\n return midpoint;\n }\n else if(arr[midpoint] < target)\n {\n first = midpoint + 1;\n }\n else if(arr[midpoint] > target)\n {\n last = midpoint - 1;\n \n }\n}\n"
},
{
"answer_id": 74499974,
"author": "Pepijn Kramer",
"author_id": 16649550,
"author_profile": "https://Stackoverflow.com/users/16649550",
"pm_score": 3,
"selected": true,
"text": "#include <iostream>\n#include <vector>\n\nauto binary_search(const std::vector<int>& values, int value)\n{\n std::size_t first = 0;\n std::size_t last = values.size() - 1; // use vector it keeps track of its size\n \n while (first <= last)\n {\n std::size_t midpoint = (last + first) / 2; // you forgot to update midpoint each loop\n\n if (values[midpoint] == value)\n {\n return values[midpoint]; // <== do you want to return the position or the value?\n }\n \n if (values[midpoint] < value)\n {\n first = midpoint + 1;\n }\n else if (values[midpoint] > value)\n {\n last = midpoint - 1;\n }\n }\n\n return 0;\n}\n\nint main()\n{\n std::vector<int> values{ 4, 12, 23, 43, 50, 60, 230, 290 };\n std::cout << binary_search(values, 12);\n return 0;\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16377085/"
] |
74,499,924
|
<p>Having trouble with for loops on java.
How do I turn this while loop into a for loop?</p>
<pre><code>public static void main(String[] args) {
int down;
down = 5;
while (down > 0) {
System.out.println(down);
down = down - 1;
</code></pre>
<p>I want to just countdown from 5 (5 4 3 2 1)</p>
<p>for (down = 5; down > 0 down-- );</p>
<p>This just outputs:</p>
<p>5</p>
|
[
{
"answer_id": 74499936,
"author": "Nesmeg",
"author_id": 14871546,
"author_profile": "https://Stackoverflow.com/users/14871546",
"pm_score": 2,
"selected": false,
"text": "while(first <= last)\n{\n if(arr[midpoint] == target)\n {\n return midpoint;\n }\n else if(arr[midpoint] < target)\n {\n first = midpoint + 1;\n }\n else if(arr[midpoint] > target)\n {\n last = midpoint - 1;\n \n }\n}\n"
},
{
"answer_id": 74499974,
"author": "Pepijn Kramer",
"author_id": 16649550,
"author_profile": "https://Stackoverflow.com/users/16649550",
"pm_score": 3,
"selected": true,
"text": "#include <iostream>\n#include <vector>\n\nauto binary_search(const std::vector<int>& values, int value)\n{\n std::size_t first = 0;\n std::size_t last = values.size() - 1; // use vector it keeps track of its size\n \n while (first <= last)\n {\n std::size_t midpoint = (last + first) / 2; // you forgot to update midpoint each loop\n\n if (values[midpoint] == value)\n {\n return values[midpoint]; // <== do you want to return the position or the value?\n }\n \n if (values[midpoint] < value)\n {\n first = midpoint + 1;\n }\n else if (values[midpoint] > value)\n {\n last = midpoint - 1;\n }\n }\n\n return 0;\n}\n\nint main()\n{\n std::vector<int> values{ 4, 12, 23, 43, 50, 60, 230, 290 };\n std::cout << binary_search(values, 12);\n return 0;\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19665125/"
] |
74,499,934
|
<p>Im Try to create schedule job sample, buy task dont execute.</p>
<p>what's wrong?</p>
<pre><code>@ApplicationScoped
public class CustomApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(FileService.class);
return classes;
}
}
</code></pre>
<pre><code>public class FileService {
public void schedulerFeature() throws InterruptedException {
Scheduling.fixedRateBuilder()
.delay(4)
.initialDelay(2)
.timeUnit(TimeUnit.SECONDS)
.task(inv -> {
System.out.println("Running in:" + Thread.currentThread().getName());
System.out.println("Every 4 seconds an action, with an initial delay");
})
.build();
Thread.sleep(12000);
}
}
</code></pre>
<p>Im Try to create schedule job sample, buy task dont execute.</p>
|
[
{
"answer_id": 74524955,
"author": "Laird Nelson",
"author_id": 208288,
"author_profile": "https://Stackoverflow.com/users/208288",
"pm_score": 2,
"selected": false,
"text": "FileService Application#getClasses() FileService Feature"
},
{
"answer_id": 74631499,
"author": "Abner Bessi",
"author_id": 20547477,
"author_profile": "https://Stackoverflow.com/users/20547477",
"pm_score": 3,
"selected": true,
"text": "<dependency>\n <groupId>io.helidon.microprofile.scheduling</groupId>\n <artifactId>helidon-microprofile-scheduling</artifactId>\n <version>3.0.2</version>\n</dependency>\n import java.util.HashSet;\nimport java.util.Set;\n\n@ApplicationScoped\npublic class CustomApplication extends Application {\n @Override\n public Set<Class<?>> getClasses() {\n Set<Class<?>> classes = new HashSet<Class<?>>();\n classes.add(FileService.class);\n return classes;\n }\n\n}\n import io.helidon.microprofile.scheduling.Scheduled;\nimport jakarta.enterprise.context.ApplicationScoped;\n\n\n/**\n * File service.\n */\n\n@ApplicationScoped\npublic class FileService {\n\n @Scheduled(\"0/2 * * * * ? *\")\n //@FixedRate(1)\n public void schedulerFeature() {\n System.out.println(\"Running\");\n }\n\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20547477/"
] |
74,499,953
|
<p>I have an <code>express.js</code> app running in cluster mode (nodejs cluster module) on a linux production server. I'm using <code>PM2</code> to manage this app. It usually uses less than 3% CPU. However, sometimes the CPU usage spikes up to 100% for a short period of time (less than a minute). I'm not able to reproduce this issue. This only happens once a day or two.
Is there any way to find out which function or route is causing the sudden CPU spikes, using PM2? Thanks.</p>
|
[
{
"answer_id": 74524955,
"author": "Laird Nelson",
"author_id": 208288,
"author_profile": "https://Stackoverflow.com/users/208288",
"pm_score": 2,
"selected": false,
"text": "FileService Application#getClasses() FileService Feature"
},
{
"answer_id": 74631499,
"author": "Abner Bessi",
"author_id": 20547477,
"author_profile": "https://Stackoverflow.com/users/20547477",
"pm_score": 3,
"selected": true,
"text": "<dependency>\n <groupId>io.helidon.microprofile.scheduling</groupId>\n <artifactId>helidon-microprofile-scheduling</artifactId>\n <version>3.0.2</version>\n</dependency>\n import java.util.HashSet;\nimport java.util.Set;\n\n@ApplicationScoped\npublic class CustomApplication extends Application {\n @Override\n public Set<Class<?>> getClasses() {\n Set<Class<?>> classes = new HashSet<Class<?>>();\n classes.add(FileService.class);\n return classes;\n }\n\n}\n import io.helidon.microprofile.scheduling.Scheduled;\nimport jakarta.enterprise.context.ApplicationScoped;\n\n\n/**\n * File service.\n */\n\n@ApplicationScoped\npublic class FileService {\n\n @Scheduled(\"0/2 * * * * ? *\")\n //@FixedRate(1)\n public void schedulerFeature() {\n System.out.println(\"Running\");\n }\n\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1800333/"
] |
74,499,955
|
<p>I'm now learning about calculus and want to depict a graph of <code>x^2 + 6x + y^4 = 7</code>, which I can using online graphing tool desmos.</p>
<p>But when I'm not sure how this is achievable on R. The first thing I thought is convert it in a form of <code>y = f(x)</code>, but <code>return (x^2 + 6*x - 7)^(1/4)</code> gave me a different result.</p>
<p>At the same time, it seems impossible to return a equation in a function (<code>return (x^2 + 6*x + y^4 = 7)</code>). So how can I depict it on R?</p>
<p>Here is a sample code I usually use to depict a continuous graph.</p>
<pre><code>f <- function(x) {
return () # return an equation
}
ggplot(data.frame(x=seq(-10,10,length.out=10)), aes(x)) + stat_function(fun=f)
</code></pre>
|
[
{
"answer_id": 74524955,
"author": "Laird Nelson",
"author_id": 208288,
"author_profile": "https://Stackoverflow.com/users/208288",
"pm_score": 2,
"selected": false,
"text": "FileService Application#getClasses() FileService Feature"
},
{
"answer_id": 74631499,
"author": "Abner Bessi",
"author_id": 20547477,
"author_profile": "https://Stackoverflow.com/users/20547477",
"pm_score": 3,
"selected": true,
"text": "<dependency>\n <groupId>io.helidon.microprofile.scheduling</groupId>\n <artifactId>helidon-microprofile-scheduling</artifactId>\n <version>3.0.2</version>\n</dependency>\n import java.util.HashSet;\nimport java.util.Set;\n\n@ApplicationScoped\npublic class CustomApplication extends Application {\n @Override\n public Set<Class<?>> getClasses() {\n Set<Class<?>> classes = new HashSet<Class<?>>();\n classes.add(FileService.class);\n return classes;\n }\n\n}\n import io.helidon.microprofile.scheduling.Scheduled;\nimport jakarta.enterprise.context.ApplicationScoped;\n\n\n/**\n * File service.\n */\n\n@ApplicationScoped\npublic class FileService {\n\n @Scheduled(\"0/2 * * * * ? *\")\n //@FixedRate(1)\n public void schedulerFeature() {\n System.out.println(\"Running\");\n }\n\n}\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74499955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2360798/"
] |
74,500,008
|
<p>In <a href="https://dbfiddle.uk/a7ghieoW" rel="nofollow noreferrer">this dbfiddle demo</a> I have a <code>DELETE FROM... WHERE</code> at the end like so:</p>
<pre><code> ......
DELETE FROM data_table
WHERE
(location, param_id, ref_time, fcst_time) NOT IN (SELECT location, param_id, ref_time, fcst_time FROM sel1)
AND
(location, param_id, ref_time, fcst_time) NOT IN (SELECT location, param_id, ref_time, fcst_time FROM sel2);
</code></pre>
<p>Although it works, it seems unnecessarily wordy, and possibly also not optimal in terms of performance?</p>
<p>Is there any way in which this can be simplified, e.g. by using a single <code>NOT IN</code> statement?</p>
<p>Because of the way that they are defined, there is no overlap/intersection between <code>sel1</code> and <code>sel2</code>.</p>
<p><code>status_table</code> has 8033 rows</p>
<p><code>data_table</code> has 116432724 rows</p>
<p><code>sel1</code> has 61860084 rows</p>
<p><code>sel2</code> has 53706188 rows</p>
<p>Numbers don't necessarily add up because it's a live database and data is going in all the time. And yes, at the moment there are few if any rows to delete because most/all of the data is current.</p>
|
[
{
"answer_id": 74506515,
"author": "tmg",
"author_id": 8398504,
"author_profile": "https://Stackoverflow.com/users/8398504",
"pm_score": 0,
"selected": false,
"text": "WITH d AS (\nWITH\n stats AS (\n SELECT ref_time\n , max(updated) < (round(extract(epoch from now()) / 60) - 200) AS settled\n , (count(*) FILTER (WHERE processed) = count(*)) AND (max(updated) < (round(extract(epoch from now()) / 60) - 200)) AS ready\n FROM status_table\n GROUP BY ref_time\n ),\n min_ts AS (\n SELECT ref_time FROM stats WHERE ready ORDER BY ref_time DESC LIMIT 1\n ),\n sel1 AS (\n -- records that would be selected by an actual data lookup (use same logic)... we need to keep these (don't delete)\n SELECT DISTINCT ON (d.location, d.timestamp, d.param_id)\n d.location, d.param_id, d.ref_time, d.fcst_time\n FROM data_table AS d\n INNER JOIN stats s USING (ref_time)\n WHERE s.ready AND d.timestamp >= (SELECT ref_time FROM min_ts)\n ORDER BY d.location, d.timestamp, d.param_id, d.ref_time DESC\n ),\n sel2 AS (\n -- also keep all records that are in-progress (not 'settled')\n SELECT\n d.location, d.param_id, d.ref_time, d.fcst_time\n FROM data_table AS d\n INNER JOIN stats AS s USING (ref_time)\n WHERE NOT s.settled\n )\nSELECT data_table.*\nFROM\n data_table LEFT JOIN\n sel1 ON sel1.location=data_table.location AND sel1.param_id=data_table.param_id AND sel1.ref_time = data_table.ref_time AND sel1.fcst_time = data_table.fcst_time LEFT JOIN\n sel2 ON sel2.location=data_table.location AND sel2.param_id=data_table.param_id AND sel2.ref_time = data_table.ref_time AND sel2.fcst_time = data_table.fcst_time\nWHERE\n sel1.location IS NULL AND\n sel2.location IS NULL\n) \nDELETE FROM data_table\nWHERE (location, param_id, ref_time, fcst_time) IN (SELECT location, param_id, ref_time, fcst_time FROM d)\n"
},
{
"answer_id": 74530698,
"author": "Zegarek",
"author_id": 5298879,
"author_profile": "https://Stackoverflow.com/users/5298879",
"pm_score": 3,
"selected": true,
"text": "......\nDELETE FROM data_table \n WHERE\n (location, param_id, ref_time, fcst_time) \n NOT IN \n (SELECT location, param_id, ref_time, fcst_time FROM sel1\n UNION ALL\n SELECT location, param_id, ref_time, fcst_time FROM sel2);\n WHERE (a) NOT IN (b) AND NOT IN (c) WHERE (a) NOT IN (b UNION c) b c UNION UNION ALL WHERE (a) NOT IN (b UNION c) b c a WHERE (a) NOT IN (b UNION ALL c) union union all"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4070848/"
] |
74,500,016
|
<p>i have some basic knowledge in AI and machine learning, but a bit confused solving a concrete problem.</p>
<p>i have the following scenario: Given are features and labeled data (0 or 1). I want to predict the probability, new data takes 0 based on the feature values of this new data.</p>
<p>I know this is supervised learning, but what method can I use for predicting here (i think logistic regression or neural networks should be an option?) and if theres any preimplemented libaries in Python I can just fed the data to and it will presict?</p>
|
[
{
"answer_id": 74506515,
"author": "tmg",
"author_id": 8398504,
"author_profile": "https://Stackoverflow.com/users/8398504",
"pm_score": 0,
"selected": false,
"text": "WITH d AS (\nWITH\n stats AS (\n SELECT ref_time\n , max(updated) < (round(extract(epoch from now()) / 60) - 200) AS settled\n , (count(*) FILTER (WHERE processed) = count(*)) AND (max(updated) < (round(extract(epoch from now()) / 60) - 200)) AS ready\n FROM status_table\n GROUP BY ref_time\n ),\n min_ts AS (\n SELECT ref_time FROM stats WHERE ready ORDER BY ref_time DESC LIMIT 1\n ),\n sel1 AS (\n -- records that would be selected by an actual data lookup (use same logic)... we need to keep these (don't delete)\n SELECT DISTINCT ON (d.location, d.timestamp, d.param_id)\n d.location, d.param_id, d.ref_time, d.fcst_time\n FROM data_table AS d\n INNER JOIN stats s USING (ref_time)\n WHERE s.ready AND d.timestamp >= (SELECT ref_time FROM min_ts)\n ORDER BY d.location, d.timestamp, d.param_id, d.ref_time DESC\n ),\n sel2 AS (\n -- also keep all records that are in-progress (not 'settled')\n SELECT\n d.location, d.param_id, d.ref_time, d.fcst_time\n FROM data_table AS d\n INNER JOIN stats AS s USING (ref_time)\n WHERE NOT s.settled\n )\nSELECT data_table.*\nFROM\n data_table LEFT JOIN\n sel1 ON sel1.location=data_table.location AND sel1.param_id=data_table.param_id AND sel1.ref_time = data_table.ref_time AND sel1.fcst_time = data_table.fcst_time LEFT JOIN\n sel2 ON sel2.location=data_table.location AND sel2.param_id=data_table.param_id AND sel2.ref_time = data_table.ref_time AND sel2.fcst_time = data_table.fcst_time\nWHERE\n sel1.location IS NULL AND\n sel2.location IS NULL\n) \nDELETE FROM data_table\nWHERE (location, param_id, ref_time, fcst_time) IN (SELECT location, param_id, ref_time, fcst_time FROM d)\n"
},
{
"answer_id": 74530698,
"author": "Zegarek",
"author_id": 5298879,
"author_profile": "https://Stackoverflow.com/users/5298879",
"pm_score": 3,
"selected": true,
"text": "......\nDELETE FROM data_table \n WHERE\n (location, param_id, ref_time, fcst_time) \n NOT IN \n (SELECT location, param_id, ref_time, fcst_time FROM sel1\n UNION ALL\n SELECT location, param_id, ref_time, fcst_time FROM sel2);\n WHERE (a) NOT IN (b) AND NOT IN (c) WHERE (a) NOT IN (b UNION c) b c UNION UNION ALL WHERE (a) NOT IN (b UNION c) b c a WHERE (a) NOT IN (b UNION ALL c) union union all"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19893493/"
] |
74,500,047
|
<p>In this <code>geom_segment</code> plot I would like to have a <strong>tickmark for every 1,000 ms</strong> on the x-axis. The code below works fine -- just <strong>except for the negative tickmark with the value <code>-1000</code> on it</strong>. How can that value and the corresponding tickmark be removed?</p>
<p><a href="https://i.stack.imgur.com/x0cPM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x0cPM.png" alt="enter image description here" /></a></p>
<p>My code so far:</p>
<pre><code>library(dplyr)
library(stringr)
library(ggplot2)
df_3 %>%
# mutate `Mutual_Gaze` to German labels:
mutate(Mutual_Gaze = ifelse(Mutual_Gaze == "rechts_Mitte", "Center_Right",
ifelse(Mutual_Gaze == "rechts_links", "Left_Right",
"Center_Left"))) %>%
# mutate `Mutual_Gaze` so it also contains `Subject` suffix:
mutate(Mutual_Gaze = str_c(Mutual_Gaze,"_R", str_extract(Subject, "\\d$"))) %>%
### Group by:
group_by(Mutual_Gaze) %>%
# plot:
ggplot(aes(x = Starttime_ms, xend = Endtime_ms,
y = Mutual_Gaze, yend = Mutual_Gaze,
color = Subject
)) +
geom_segment(size = 6) +
labs(title = paste0(
#"Annotation Density Plot\n",
df_3$File, " (Study 1)"),
x ="Timeline"
) +
# determine number of x-axis tickmarks:
scale_x_continuous(n.breaks = 35,
# limits ??? # <---
limits = c(0, max(df_3$Endtime_ms))) +
# rotate x-axis tickmark labels:
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
#scale_y_continuous(n.breaks = 10)
#theme_minimal() +
theme(legend.position = "none")
</code></pre>
<p>Data:</p>
<pre><code>df_3 <- structure(list(Subject = c("Rater_1", "Rater_1", "Rater_1", "Rater_1",
"Rater_1", "Rater_1", "Rater_1", "Rater_1", "Rater_1", "Rater_1",
"Rater_1", "Rater_1", "Rater_1", "Rater_1", "Rater_1", "Rater_1",
"Rater_1", "Rater_1", "Rater_1", "Rater_1", "Rater_2", "Rater_2",
"Rater_2", "Rater_2", "Rater_2", "Rater_2", "Rater_2", "Rater_2",
"Rater_2", "Rater_2", "Rater_2", "Rater_2", "Rater_2", "Rater_2",
"Rater_2", "Rater_2", "Rater_2", "Rater_2", "Rater_2", "Rater_2",
"Rater_2", "Rater_2", "Rater_2", "Rater_2", "Rater_3", "Rater_3",
"Rater_3", "Rater_3", "Rater_3", "Rater_3", "Rater_3", "Rater_3",
"Rater_3", "Rater_3", "Rater_3", "Rater_3", "Rater_3", "Rater_3",
"Rater_3", "Rater_3", "Rater_3", "Rater_3", "Rater_3", "Rater_3",
"Rater_3", "Rater_4", "Rater_4", "Rater_4", "Rater_4", "Rater_4",
"Rater_4", "Rater_4", "Rater_4", "Rater_4", "Rater_4", "Rater_4",
"Rater_4", "Rater_4", "Rater_4", "Rater_4", "Rater_4", "Rater_4",
"Rater_4", "Rater_4", "Rater_4", "Rater_5", "Rater_5", "Rater_5",
"Rater_5", "Rater_5", "Rater_5", "Rater_5", "Rater_5", "Rater_5",
"Rater_5", "Rater_5", "Rater_5", "Rater_5", "Rater_5", "Rater_5",
"Rater_5", "Rater_5", "Rater_5", "Rater_5", "Rater_5", "Rater_5"
), Mutual_Gaze = c("rechts_Mitte", "rechts_links", "Mitte_links",
"Mitte_links", "rechts_links", "Mitte_links", "rechts_links",
"Mitte_links", "rechts_links", "rechts_links", "Mitte_links",
"Mitte_links", "Mitte_links", "rechts_links", "Mitte_links",
"Mitte_links", "rechts_links", "rechts_links", "rechts_links",
"rechts_links", "rechts_Mitte", "rechts_links", "Mitte_links",
"rechts_links", "Mitte_links", "rechts_links", "Mitte_links",
"rechts_links", "rechts_links", "rechts_Mitte", "Mitte_links",
"Mitte_links", "Mitte_links", "Mitte_links", "rechts_links",
"rechts_links", "rechts_links", "rechts_links", "Mitte_links",
"Mitte_links", "rechts_links", "rechts_links", "rechts_links",
"rechts_links", "rechts_Mitte", "rechts_links", "Mitte_links",
"rechts_links", "Mitte_links", "rechts_links", "Mitte_links",
"rechts_links", "rechts_links", "Mitte_links", "Mitte_links",
"Mitte_links", "rechts_links", "rechts_links", "rechts_links",
"rechts_links", "Mitte_links", "Mitte_links", "rechts_links",
"rechts_links", "rechts_links", "rechts_Mitte", "Mitte_links",
"rechts_links", "Mitte_links", "rechts_links", "Mitte_links",
"rechts_links", "rechts_links", "Mitte_links", "Mitte_links",
"Mitte_links", "rechts_links", "rechts_links", "rechts_links",
"Mitte_links", "Mitte_links", "rechts_links", "rechts_links",
"rechts_links", "rechts_links", "rechts_Mitte", "rechts_Mitte",
"rechts_links", "Mitte_links", "rechts_links", "Mitte_links",
"rechts_links", "Mitte_links", "rechts_links", "rechts_links",
"rechts_links", "Mitte_links", "Mitte_links", "Mitte_links",
"rechts_links", "Mitte_links", "Mitte_links", "rechts_links",
"rechts_links", "rechts_links", "rechts_links"), Starttime_ms = c(500,
1520, 2313, 3139, 3767, 7354, 8993, 9566, 10702, 13180, 14144,
17447, 19121, 19766, 24721, 25436, 26522, 30597, 31952, 34187,
350, 1490, 2210, 3710, 7300, 8920, 9500, 10670, 13170, 13880,
14120, 17400, 18120, 19080, 19610, 19790, 21465, 21650, 24610,
25360, 26480, 30620, 31930, 34160, 550, 1521, 2256, 3717, 7362,
8951, 9561, 10702, 13174, 14139, 17326, 19111, 19816, 21288,
21447, 21634, 24564, 25349, 26505, 30610, 34194, 570, 2355, 3800,
7423, 8999, 9614, 10799, 13352, 14244, 17526, 19110, 19953, 21269,
21444, 24735, 25403, 26501, 30607, 31960, 34456, 7, 665, 1520,
2316, 3705, 7335, 8958, 9631, 10728, 11325, 13179, 14139, 17492,
19176, 19636, 24645, 25415, 30634, 30653, 31954, 34204), Endtime_ms = c(1350,
1620, 2958, 3534, 4255, 8581, 9269, 10287, 11377, 13710, 14874,
17843, 19418, 23861, 25029, 26136, 26627, 31289, 33115, 34690,
1360, 1630, 3500, 4260, 8570, 9280, 10280, 11380, 13720, 13930,
14880, 17770, 18190, 19400, 19660, 21350, 21565, 23870, 25000,
26130, 26590, 31280, 33120, 34690, 1334, 1630, 3491, 4256, 8578,
9272, 10318, 11372, 13717, 14847, 18134, 19411, 21221, 21344,
21534, 23969, 25016, 26126, 26591, 33154, 34690, 1255, 3466,
4191, 8533, 9239, 10276, 11360, 13683, 14814, 18119, 19414, 21228,
21343, 23866, 25030, 26128, 26586, 31283, 33160, 34684, 665,
1324, 1608, 3487, 4225, 8567, 9271, 10287, 11325, 11394, 13697,
14845, 17738, 19396, 23900, 25030, 26072, 30653, 31250, 33119,
34641), File = c("Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A",
"Triad A", "Triad A", "Triad A", "Triad A", "Triad A", "Triad A"
)), class = "data.frame", row.names = c(NA, -106L))
</code></pre>
|
[
{
"answer_id": 74506515,
"author": "tmg",
"author_id": 8398504,
"author_profile": "https://Stackoverflow.com/users/8398504",
"pm_score": 0,
"selected": false,
"text": "WITH d AS (\nWITH\n stats AS (\n SELECT ref_time\n , max(updated) < (round(extract(epoch from now()) / 60) - 200) AS settled\n , (count(*) FILTER (WHERE processed) = count(*)) AND (max(updated) < (round(extract(epoch from now()) / 60) - 200)) AS ready\n FROM status_table\n GROUP BY ref_time\n ),\n min_ts AS (\n SELECT ref_time FROM stats WHERE ready ORDER BY ref_time DESC LIMIT 1\n ),\n sel1 AS (\n -- records that would be selected by an actual data lookup (use same logic)... we need to keep these (don't delete)\n SELECT DISTINCT ON (d.location, d.timestamp, d.param_id)\n d.location, d.param_id, d.ref_time, d.fcst_time\n FROM data_table AS d\n INNER JOIN stats s USING (ref_time)\n WHERE s.ready AND d.timestamp >= (SELECT ref_time FROM min_ts)\n ORDER BY d.location, d.timestamp, d.param_id, d.ref_time DESC\n ),\n sel2 AS (\n -- also keep all records that are in-progress (not 'settled')\n SELECT\n d.location, d.param_id, d.ref_time, d.fcst_time\n FROM data_table AS d\n INNER JOIN stats AS s USING (ref_time)\n WHERE NOT s.settled\n )\nSELECT data_table.*\nFROM\n data_table LEFT JOIN\n sel1 ON sel1.location=data_table.location AND sel1.param_id=data_table.param_id AND sel1.ref_time = data_table.ref_time AND sel1.fcst_time = data_table.fcst_time LEFT JOIN\n sel2 ON sel2.location=data_table.location AND sel2.param_id=data_table.param_id AND sel2.ref_time = data_table.ref_time AND sel2.fcst_time = data_table.fcst_time\nWHERE\n sel1.location IS NULL AND\n sel2.location IS NULL\n) \nDELETE FROM data_table\nWHERE (location, param_id, ref_time, fcst_time) IN (SELECT location, param_id, ref_time, fcst_time FROM d)\n"
},
{
"answer_id": 74530698,
"author": "Zegarek",
"author_id": 5298879,
"author_profile": "https://Stackoverflow.com/users/5298879",
"pm_score": 3,
"selected": true,
"text": "......\nDELETE FROM data_table \n WHERE\n (location, param_id, ref_time, fcst_time) \n NOT IN \n (SELECT location, param_id, ref_time, fcst_time FROM sel1\n UNION ALL\n SELECT location, param_id, ref_time, fcst_time FROM sel2);\n WHERE (a) NOT IN (b) AND NOT IN (c) WHERE (a) NOT IN (b UNION c) b c UNION UNION ALL WHERE (a) NOT IN (b UNION c) b c a WHERE (a) NOT IN (b UNION ALL c) union union all"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8039978/"
] |
74,500,059
|
<p>I have a DataFrame <code>df</code> and I create <code>gb = df.groupby("column1")</code>. Now I would like to do the following:</p>
<p><code>x = gb.apply(lambda x: x["column2"].sum() / df["column2"].sum())</code></p>
<p>It works but I would like to based everytinh on <code>x</code> not <code>x</code> and <code>df</code>. Ideally I expected that there is a function <code>x.get_source_df</code> and then my solution would be:</p>
<p><code>x = gb.apply(lambda x: x["column2"].sum() / x.get_source_df()["column2"].sum())</code></p>
<p>and in that case I could save this lambda function in a dictionary which I could use for any <code>df</code>. Is it possible?</p>
|
[
{
"answer_id": 74506515,
"author": "tmg",
"author_id": 8398504,
"author_profile": "https://Stackoverflow.com/users/8398504",
"pm_score": 0,
"selected": false,
"text": "WITH d AS (\nWITH\n stats AS (\n SELECT ref_time\n , max(updated) < (round(extract(epoch from now()) / 60) - 200) AS settled\n , (count(*) FILTER (WHERE processed) = count(*)) AND (max(updated) < (round(extract(epoch from now()) / 60) - 200)) AS ready\n FROM status_table\n GROUP BY ref_time\n ),\n min_ts AS (\n SELECT ref_time FROM stats WHERE ready ORDER BY ref_time DESC LIMIT 1\n ),\n sel1 AS (\n -- records that would be selected by an actual data lookup (use same logic)... we need to keep these (don't delete)\n SELECT DISTINCT ON (d.location, d.timestamp, d.param_id)\n d.location, d.param_id, d.ref_time, d.fcst_time\n FROM data_table AS d\n INNER JOIN stats s USING (ref_time)\n WHERE s.ready AND d.timestamp >= (SELECT ref_time FROM min_ts)\n ORDER BY d.location, d.timestamp, d.param_id, d.ref_time DESC\n ),\n sel2 AS (\n -- also keep all records that are in-progress (not 'settled')\n SELECT\n d.location, d.param_id, d.ref_time, d.fcst_time\n FROM data_table AS d\n INNER JOIN stats AS s USING (ref_time)\n WHERE NOT s.settled\n )\nSELECT data_table.*\nFROM\n data_table LEFT JOIN\n sel1 ON sel1.location=data_table.location AND sel1.param_id=data_table.param_id AND sel1.ref_time = data_table.ref_time AND sel1.fcst_time = data_table.fcst_time LEFT JOIN\n sel2 ON sel2.location=data_table.location AND sel2.param_id=data_table.param_id AND sel2.ref_time = data_table.ref_time AND sel2.fcst_time = data_table.fcst_time\nWHERE\n sel1.location IS NULL AND\n sel2.location IS NULL\n) \nDELETE FROM data_table\nWHERE (location, param_id, ref_time, fcst_time) IN (SELECT location, param_id, ref_time, fcst_time FROM d)\n"
},
{
"answer_id": 74530698,
"author": "Zegarek",
"author_id": 5298879,
"author_profile": "https://Stackoverflow.com/users/5298879",
"pm_score": 3,
"selected": true,
"text": "......\nDELETE FROM data_table \n WHERE\n (location, param_id, ref_time, fcst_time) \n NOT IN \n (SELECT location, param_id, ref_time, fcst_time FROM sel1\n UNION ALL\n SELECT location, param_id, ref_time, fcst_time FROM sel2);\n WHERE (a) NOT IN (b) AND NOT IN (c) WHERE (a) NOT IN (b UNION c) b c UNION UNION ALL WHERE (a) NOT IN (b UNION c) b c a WHERE (a) NOT IN (b UNION ALL c) union union all"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19315438/"
] |
74,500,089
|
<p>I have a question about images in a flutter. I have a Column and inside of it I have an image, I need to stretch it at full width but I could not. There are a few spaces left on the left and right for the white circle at the end of the screen. Where is the wrong statement in my code?</p>
<p>Thanks,</p>
<pre><code>home: Scaffold(
backgroundColor: HexColor(primary),
body: SafeArea(
bottom: false,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
// Header text & Pawline image
Row(
...
),
// Banner image
Row(...
),
// Circle
// TODO: Stretch circle image to the both ends
Expanded(
child: Image.asset(
"assets/images/circle.png",
fit: BoxFit.contain,
),
),
],
),
),
),
);
</code></pre>
<p><a href="https://i.stack.imgur.com/KSzl2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KSzl2.png" alt="enter image description here" /></a></p>
<p>Edit: Circle image:</p>
<p><a href="https://i.stack.imgur.com/JT9yJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JT9yJ.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74506515,
"author": "tmg",
"author_id": 8398504,
"author_profile": "https://Stackoverflow.com/users/8398504",
"pm_score": 0,
"selected": false,
"text": "WITH d AS (\nWITH\n stats AS (\n SELECT ref_time\n , max(updated) < (round(extract(epoch from now()) / 60) - 200) AS settled\n , (count(*) FILTER (WHERE processed) = count(*)) AND (max(updated) < (round(extract(epoch from now()) / 60) - 200)) AS ready\n FROM status_table\n GROUP BY ref_time\n ),\n min_ts AS (\n SELECT ref_time FROM stats WHERE ready ORDER BY ref_time DESC LIMIT 1\n ),\n sel1 AS (\n -- records that would be selected by an actual data lookup (use same logic)... we need to keep these (don't delete)\n SELECT DISTINCT ON (d.location, d.timestamp, d.param_id)\n d.location, d.param_id, d.ref_time, d.fcst_time\n FROM data_table AS d\n INNER JOIN stats s USING (ref_time)\n WHERE s.ready AND d.timestamp >= (SELECT ref_time FROM min_ts)\n ORDER BY d.location, d.timestamp, d.param_id, d.ref_time DESC\n ),\n sel2 AS (\n -- also keep all records that are in-progress (not 'settled')\n SELECT\n d.location, d.param_id, d.ref_time, d.fcst_time\n FROM data_table AS d\n INNER JOIN stats AS s USING (ref_time)\n WHERE NOT s.settled\n )\nSELECT data_table.*\nFROM\n data_table LEFT JOIN\n sel1 ON sel1.location=data_table.location AND sel1.param_id=data_table.param_id AND sel1.ref_time = data_table.ref_time AND sel1.fcst_time = data_table.fcst_time LEFT JOIN\n sel2 ON sel2.location=data_table.location AND sel2.param_id=data_table.param_id AND sel2.ref_time = data_table.ref_time AND sel2.fcst_time = data_table.fcst_time\nWHERE\n sel1.location IS NULL AND\n sel2.location IS NULL\n) \nDELETE FROM data_table\nWHERE (location, param_id, ref_time, fcst_time) IN (SELECT location, param_id, ref_time, fcst_time FROM d)\n"
},
{
"answer_id": 74530698,
"author": "Zegarek",
"author_id": 5298879,
"author_profile": "https://Stackoverflow.com/users/5298879",
"pm_score": 3,
"selected": true,
"text": "......\nDELETE FROM data_table \n WHERE\n (location, param_id, ref_time, fcst_time) \n NOT IN \n (SELECT location, param_id, ref_time, fcst_time FROM sel1\n UNION ALL\n SELECT location, param_id, ref_time, fcst_time FROM sel2);\n WHERE (a) NOT IN (b) AND NOT IN (c) WHERE (a) NOT IN (b UNION c) b c UNION UNION ALL WHERE (a) NOT IN (b UNION c) b c a WHERE (a) NOT IN (b UNION ALL c) union union all"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12347681/"
] |
74,500,112
|
<p>My connection handshake times out when trying to connect to my RDS Aurora Serverless (v1) MySQL Cluster from an external source.</p>
<p>I'm specifying the cluster and its security group in terraform, and leveraging the default AWS VPC for the account/region.</p>
<p>Parameters for my cluster:</p>
<pre><code> cluster_identifier = "some-cluster-name",
engine = "aurora-mysql",
engine_mode = "serverless",
database_name = "db",
master_username = "********",
master_password = "********",
backup_retention_period = 5,
preferred_backup_window = "07:00-09:00",
skip_final_snapshot = true,
storage_encrypted = true,
scaling_configuration = {
max_capacity = 4,
min_capacity = 1,
seconds_until_auto_pause = 300
},
vpc_security_group_ids = ["${aws_security_group.my_sg_defined_elsewhere.id}"]
</code></pre>
<p>Security group rules:</p>
<pre><code> type = "ingress",
from_port = 3306,
to_port = 3306,
protocol = "tcp",
cidr_blocks = ["0.0.0.0/0"],
ipv6_cidr_blocks = ["::/0"],
security_group_id = "${aws_security_group.my_sg_defined_elsewhere.id}"
</code></pre>
<pre><code> type = "egress",
from_port = 0,
to_port = 0,
protocol = "-1",
cidr_blocks = ["0.0.0.0/0"],
ipv6_cidr_blocks = ["::/0"],
security_group_id = "${aws_security_group.my_sg_defined_elsewhere.id}"
</code></pre>
<p>Since I'm just using the default VPC, which I believe has public subnets, I'm assuming that if my security group rules are sufficient for public MySQL access then this should just work. Unfortunately using the cluster's generated endpoint and the correct credentials, I just get a timeout when trying to connect.</p>
|
[
{
"answer_id": 74506515,
"author": "tmg",
"author_id": 8398504,
"author_profile": "https://Stackoverflow.com/users/8398504",
"pm_score": 0,
"selected": false,
"text": "WITH d AS (\nWITH\n stats AS (\n SELECT ref_time\n , max(updated) < (round(extract(epoch from now()) / 60) - 200) AS settled\n , (count(*) FILTER (WHERE processed) = count(*)) AND (max(updated) < (round(extract(epoch from now()) / 60) - 200)) AS ready\n FROM status_table\n GROUP BY ref_time\n ),\n min_ts AS (\n SELECT ref_time FROM stats WHERE ready ORDER BY ref_time DESC LIMIT 1\n ),\n sel1 AS (\n -- records that would be selected by an actual data lookup (use same logic)... we need to keep these (don't delete)\n SELECT DISTINCT ON (d.location, d.timestamp, d.param_id)\n d.location, d.param_id, d.ref_time, d.fcst_time\n FROM data_table AS d\n INNER JOIN stats s USING (ref_time)\n WHERE s.ready AND d.timestamp >= (SELECT ref_time FROM min_ts)\n ORDER BY d.location, d.timestamp, d.param_id, d.ref_time DESC\n ),\n sel2 AS (\n -- also keep all records that are in-progress (not 'settled')\n SELECT\n d.location, d.param_id, d.ref_time, d.fcst_time\n FROM data_table AS d\n INNER JOIN stats AS s USING (ref_time)\n WHERE NOT s.settled\n )\nSELECT data_table.*\nFROM\n data_table LEFT JOIN\n sel1 ON sel1.location=data_table.location AND sel1.param_id=data_table.param_id AND sel1.ref_time = data_table.ref_time AND sel1.fcst_time = data_table.fcst_time LEFT JOIN\n sel2 ON sel2.location=data_table.location AND sel2.param_id=data_table.param_id AND sel2.ref_time = data_table.ref_time AND sel2.fcst_time = data_table.fcst_time\nWHERE\n sel1.location IS NULL AND\n sel2.location IS NULL\n) \nDELETE FROM data_table\nWHERE (location, param_id, ref_time, fcst_time) IN (SELECT location, param_id, ref_time, fcst_time FROM d)\n"
},
{
"answer_id": 74530698,
"author": "Zegarek",
"author_id": 5298879,
"author_profile": "https://Stackoverflow.com/users/5298879",
"pm_score": 3,
"selected": true,
"text": "......\nDELETE FROM data_table \n WHERE\n (location, param_id, ref_time, fcst_time) \n NOT IN \n (SELECT location, param_id, ref_time, fcst_time FROM sel1\n UNION ALL\n SELECT location, param_id, ref_time, fcst_time FROM sel2);\n WHERE (a) NOT IN (b) AND NOT IN (c) WHERE (a) NOT IN (b UNION c) b c UNION UNION ALL WHERE (a) NOT IN (b UNION c) b c a WHERE (a) NOT IN (b UNION ALL c) union union all"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/389765/"
] |
74,500,157
|
<p>Possibly stupid question. In the docs they give this example</p>
<pre><code>calculator.Add(1, 2).Returns(3);
Assert.That(calculator.Add(1, 2), Is.EqualTo(3));
</code></pre>
<p>Am I testing that the actual calculator returns 3 or just that the substitute does? If the latter, what is the point?</p>
|
[
{
"answer_id": 74506515,
"author": "tmg",
"author_id": 8398504,
"author_profile": "https://Stackoverflow.com/users/8398504",
"pm_score": 0,
"selected": false,
"text": "WITH d AS (\nWITH\n stats AS (\n SELECT ref_time\n , max(updated) < (round(extract(epoch from now()) / 60) - 200) AS settled\n , (count(*) FILTER (WHERE processed) = count(*)) AND (max(updated) < (round(extract(epoch from now()) / 60) - 200)) AS ready\n FROM status_table\n GROUP BY ref_time\n ),\n min_ts AS (\n SELECT ref_time FROM stats WHERE ready ORDER BY ref_time DESC LIMIT 1\n ),\n sel1 AS (\n -- records that would be selected by an actual data lookup (use same logic)... we need to keep these (don't delete)\n SELECT DISTINCT ON (d.location, d.timestamp, d.param_id)\n d.location, d.param_id, d.ref_time, d.fcst_time\n FROM data_table AS d\n INNER JOIN stats s USING (ref_time)\n WHERE s.ready AND d.timestamp >= (SELECT ref_time FROM min_ts)\n ORDER BY d.location, d.timestamp, d.param_id, d.ref_time DESC\n ),\n sel2 AS (\n -- also keep all records that are in-progress (not 'settled')\n SELECT\n d.location, d.param_id, d.ref_time, d.fcst_time\n FROM data_table AS d\n INNER JOIN stats AS s USING (ref_time)\n WHERE NOT s.settled\n )\nSELECT data_table.*\nFROM\n data_table LEFT JOIN\n sel1 ON sel1.location=data_table.location AND sel1.param_id=data_table.param_id AND sel1.ref_time = data_table.ref_time AND sel1.fcst_time = data_table.fcst_time LEFT JOIN\n sel2 ON sel2.location=data_table.location AND sel2.param_id=data_table.param_id AND sel2.ref_time = data_table.ref_time AND sel2.fcst_time = data_table.fcst_time\nWHERE\n sel1.location IS NULL AND\n sel2.location IS NULL\n) \nDELETE FROM data_table\nWHERE (location, param_id, ref_time, fcst_time) IN (SELECT location, param_id, ref_time, fcst_time FROM d)\n"
},
{
"answer_id": 74530698,
"author": "Zegarek",
"author_id": 5298879,
"author_profile": "https://Stackoverflow.com/users/5298879",
"pm_score": 3,
"selected": true,
"text": "......\nDELETE FROM data_table \n WHERE\n (location, param_id, ref_time, fcst_time) \n NOT IN \n (SELECT location, param_id, ref_time, fcst_time FROM sel1\n UNION ALL\n SELECT location, param_id, ref_time, fcst_time FROM sel2);\n WHERE (a) NOT IN (b) AND NOT IN (c) WHERE (a) NOT IN (b UNION c) b c UNION UNION ALL WHERE (a) NOT IN (b UNION c) b c a WHERE (a) NOT IN (b UNION ALL c) union union all"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2184077/"
] |
74,500,161
|
<p>I installed MLRun to the docker and I got</p>
<pre><code>Error invoking remote method 'docker-start-container': Error: (HTTP code 500) server error - driver failed programming external connectivity on endpoint desktopdockertools-mlrun-api-1 (a5a67db8a74bf4981d44477ffb77dccb25d2401d8fdd95c64262de30ed6d1a56): Bind for 0.0.0.0:8080 failed: port is already allocated
</code></pre>
<p>Do you have any experience?</p>
<p>I installed different MLRun versions with Jupyter (usage compose.with-jupyter.yaml) and without Jupyter (compose.yaml), but I still see the same issue. I made installation based on <a href="https://docs.mlrun.org/en/latest/install/local-docker.html#install-local-docker" rel="nofollow noreferrer">https://docs.mlrun.org/en/latest/install/local-docker.html#install-local-docker</a>.</p>
|
[
{
"answer_id": 74500384,
"author": "psafarcik",
"author_id": 5035543,
"author_profile": "https://Stackoverflow.com/users/5035543",
"pm_score": 1,
"selected": false,
"text": "localhost 8080 MLRun MLRun compose.yaml. services:\n mlrun-api:\n image: \"mlrun/mlrun-api:${TAG:-1.0.6}\"\n ports:\n - \"8180:8080\"\n environment:\n MLRUN_ARTIFACT_PATH: \"${SHARED_DIR}/{{project}}\"\n # using local storage, meaning files / artifacts are stored locally, so we want to allow access to them\n MLRUN_HTTPDB__REAL_PATH: /data\n MLRUN_HTTPDB__DATA_VOLUME: \"${SHARED_DIR}\"\n MLRUN_LOG_LEVEL: DEBUG\n MLRUN_NUCLIO_DASHBOARD_URL: http://nuclio:8070\n MLRUN_HTTPDB__DSN: \"sqlite:////data/mlrun.db?check_same_thread=false\"\n MLRUN_UI__URL: http://localhost:8060\n # not running on k8s meaning no need to store secrets\n MLRUN_SECRET_STORES__KUBERNETES__AUTO_ADD_PROJECT_SECRETS: \"false\"\n # let mlrun control nuclio resources\n MLRUN_HTTPDB__PROJECTS__FOLLOWERS: \"nuclio\"\n volumes:\n - \"${SHARED_DIR:?err}:/data\"\n networks:\n - mlrun\n\n mlrun-ui:\n image: \"mlrun/mlrun-ui:${TAG:-1.0.6}\"\n ports:\n - \"8060:8090\"\n environment:\n MLRUN_API_PROXY_URL: http://mlrun-api:8080\n MLRUN_NUCLIO_MODE: enable\n MLRUN_NUCLIO_API_URL: http://nuclio:8070\n MLRUN_NUCLIO_UI_URL: http://localhost:8070\n networks:\n - mlrun\n\n nuclio:\n image: \"quay.io/nuclio/dashboard:${NUCLIO_TAG:-stable-amd64}\"\n ports:\n - \"8070:8070\"\n environment:\n NUCLIO_DASHBOARD_EXTERNAL_IP_ADDRESSES: \"${HOST_IP:-127.0.0.1}\"\n volumes:\n - /var/run/docker.sock:/var/run/docker.sock\n networks:\n - mlrun\n\nnetworks:\n mlrun: {}\n docker ps -a 8080 docker stop <container_id / container_name>; docker rm <container_id / container_name> MLRun 8080 # for unix like systems\n# if you are using Windows, try to find the similar one command\n\nnetstat -ltnp | grep -w ':8080' \nlsof -i :8080\n 8080 kill <PROCESS_ID> MLRun"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,500,169
|
<p>[user checks relation]
[1]<a href="https://i.stack.imgur.com/DtLLP.png" rel="nofollow noreferrer">checks table</a>
<a href="https://i.stack.imgur.com/sPGTZ.png" rel="nofollow noreferrer">users table</a>got this console query to get the result i want but can't figure out how to make it a function in laravel.</p>
<pre><code>select DATE(c.check_in),
group_concat(users.id),
sec_to_time(sum(TIME_TO_SEC(c.check_hours))) AS total_time
from users
join checks c on users.id = c.user_id
where c.check_hours is not null
and DATE(c.check_in) = '2022-11-17'
group by DATE(c.check_in)
</code></pre>
<pre><code>DB::connection()->enableQueryLog();
$today = Carbon::yesterday();
$asdf = User::query()
->byNotWhereAdmin()
->with(['checks' => function ($query) {
$query->where('check_hours', '08:00')
->where('check_hours', '!=', null)
->selectRaw('sum(TIME_TO_SEC(`check_hours`)) as total_time')
->whereDate('check_in', '2022-11-17');
}])
->get();
</code></pre>
<p>i did smth like this but cant figure out how to make the selectRaw() method to make a sum of times</p>
<pre><code>sec_to_time(sum(TIME_TO_SEC(c.check_hours))) AS total_time
</code></pre>
<p>the result should be like this:</p>
<pre><code>DATE(c.check_in) group_concat(users.id) total_time
2022-11-17, "2,8,11,5,15,16,4,6,14,7,13", 88:00:00
</code></pre>
<p><a href="https://i.stack.imgur.com/7MiVz.png" rel="nofollow noreferrer">console results</a></p>
<p>I got a solution by changing the query from Users to Checks smth liek this:</p>
<pre><code> Check::query()
->select(DB::raw('DATE_FORMAT(check_in, "%d-%b-%Y") as datetime'))
->selectRaw('sec_to_time(sum(time_to_sec(`check_hours`))) as total_time')
->with('user')
->where('check_hours', '!=', null)
->when($this->selectDate && $this->selectDate2, function ($query) {
$query->whereBetween('check_in', [$this->selectDate, Carbon::parse($this->selectDate2)->addDays(1)]);
}, function ($query) {
$query->whereBetween('check_in', [$this->selectDate, $this->selectDate2]);
})
->groupBy('check_in', 'check_hours')
->get();
</code></pre>
<p>and i did whereBetween to make a range date to search</p>
|
[
{
"answer_id": 74500384,
"author": "psafarcik",
"author_id": 5035543,
"author_profile": "https://Stackoverflow.com/users/5035543",
"pm_score": 1,
"selected": false,
"text": "localhost 8080 MLRun MLRun compose.yaml. services:\n mlrun-api:\n image: \"mlrun/mlrun-api:${TAG:-1.0.6}\"\n ports:\n - \"8180:8080\"\n environment:\n MLRUN_ARTIFACT_PATH: \"${SHARED_DIR}/{{project}}\"\n # using local storage, meaning files / artifacts are stored locally, so we want to allow access to them\n MLRUN_HTTPDB__REAL_PATH: /data\n MLRUN_HTTPDB__DATA_VOLUME: \"${SHARED_DIR}\"\n MLRUN_LOG_LEVEL: DEBUG\n MLRUN_NUCLIO_DASHBOARD_URL: http://nuclio:8070\n MLRUN_HTTPDB__DSN: \"sqlite:////data/mlrun.db?check_same_thread=false\"\n MLRUN_UI__URL: http://localhost:8060\n # not running on k8s meaning no need to store secrets\n MLRUN_SECRET_STORES__KUBERNETES__AUTO_ADD_PROJECT_SECRETS: \"false\"\n # let mlrun control nuclio resources\n MLRUN_HTTPDB__PROJECTS__FOLLOWERS: \"nuclio\"\n volumes:\n - \"${SHARED_DIR:?err}:/data\"\n networks:\n - mlrun\n\n mlrun-ui:\n image: \"mlrun/mlrun-ui:${TAG:-1.0.6}\"\n ports:\n - \"8060:8090\"\n environment:\n MLRUN_API_PROXY_URL: http://mlrun-api:8080\n MLRUN_NUCLIO_MODE: enable\n MLRUN_NUCLIO_API_URL: http://nuclio:8070\n MLRUN_NUCLIO_UI_URL: http://localhost:8070\n networks:\n - mlrun\n\n nuclio:\n image: \"quay.io/nuclio/dashboard:${NUCLIO_TAG:-stable-amd64}\"\n ports:\n - \"8070:8070\"\n environment:\n NUCLIO_DASHBOARD_EXTERNAL_IP_ADDRESSES: \"${HOST_IP:-127.0.0.1}\"\n volumes:\n - /var/run/docker.sock:/var/run/docker.sock\n networks:\n - mlrun\n\nnetworks:\n mlrun: {}\n docker ps -a 8080 docker stop <container_id / container_name>; docker rm <container_id / container_name> MLRun 8080 # for unix like systems\n# if you are using Windows, try to find the similar one command\n\nnetstat -ltnp | grep -w ':8080' \nlsof -i :8080\n 8080 kill <PROCESS_ID> MLRun"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19665419/"
] |
74,500,254
|
<p>I'm having a problem in flutter on vs code
I imported the audioplayers
here's my pubspec.yaml</p>
<p><img src="https://i.stack.imgur.com/WbrvG.png" alt="enter image description here" /></p>
<p>here's my homepage where I call the audio players</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.brown,
title: Text('anghami'),
),
body: Container(
color: Colors.brown[200],
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Card(
child: ListTile(
title: Text(
"benab",
style: TextStyle(color: Colors.red),
),
//tileColor: Colors.red,
leading: Icon(Icons.music_note),
iconColor: Colors.red,
onTap: () async {
final player = AudioPlayer();
await player
.setSource(AssetSource('assets/music/music1.mp3'));
},
),
),
],
),
),
),
);
}
}
</code></pre>
<p>whenever i try to play the music from the phone I get this error</p>
<p><img src="https://i.stack.imgur.com/KusIG.png" alt="enter image description here" /></p>
<p>P.S: the vs code has no problem in loading images or using other type of assets .</p>
<p>i've tried using Audiocache it doesn't work especially they deleted it in the last version ^1.1.1 ,
[enter image description here][https://i.stack.imgur.com/u9kKR.png]</p>
|
[
{
"answer_id": 74500384,
"author": "psafarcik",
"author_id": 5035543,
"author_profile": "https://Stackoverflow.com/users/5035543",
"pm_score": 1,
"selected": false,
"text": "localhost 8080 MLRun MLRun compose.yaml. services:\n mlrun-api:\n image: \"mlrun/mlrun-api:${TAG:-1.0.6}\"\n ports:\n - \"8180:8080\"\n environment:\n MLRUN_ARTIFACT_PATH: \"${SHARED_DIR}/{{project}}\"\n # using local storage, meaning files / artifacts are stored locally, so we want to allow access to them\n MLRUN_HTTPDB__REAL_PATH: /data\n MLRUN_HTTPDB__DATA_VOLUME: \"${SHARED_DIR}\"\n MLRUN_LOG_LEVEL: DEBUG\n MLRUN_NUCLIO_DASHBOARD_URL: http://nuclio:8070\n MLRUN_HTTPDB__DSN: \"sqlite:////data/mlrun.db?check_same_thread=false\"\n MLRUN_UI__URL: http://localhost:8060\n # not running on k8s meaning no need to store secrets\n MLRUN_SECRET_STORES__KUBERNETES__AUTO_ADD_PROJECT_SECRETS: \"false\"\n # let mlrun control nuclio resources\n MLRUN_HTTPDB__PROJECTS__FOLLOWERS: \"nuclio\"\n volumes:\n - \"${SHARED_DIR:?err}:/data\"\n networks:\n - mlrun\n\n mlrun-ui:\n image: \"mlrun/mlrun-ui:${TAG:-1.0.6}\"\n ports:\n - \"8060:8090\"\n environment:\n MLRUN_API_PROXY_URL: http://mlrun-api:8080\n MLRUN_NUCLIO_MODE: enable\n MLRUN_NUCLIO_API_URL: http://nuclio:8070\n MLRUN_NUCLIO_UI_URL: http://localhost:8070\n networks:\n - mlrun\n\n nuclio:\n image: \"quay.io/nuclio/dashboard:${NUCLIO_TAG:-stable-amd64}\"\n ports:\n - \"8070:8070\"\n environment:\n NUCLIO_DASHBOARD_EXTERNAL_IP_ADDRESSES: \"${HOST_IP:-127.0.0.1}\"\n volumes:\n - /var/run/docker.sock:/var/run/docker.sock\n networks:\n - mlrun\n\nnetworks:\n mlrun: {}\n docker ps -a 8080 docker stop <container_id / container_name>; docker rm <container_id / container_name> MLRun 8080 # for unix like systems\n# if you are using Windows, try to find the similar one command\n\nnetstat -ltnp | grep -w ':8080' \nlsof -i :8080\n 8080 kill <PROCESS_ID> MLRun"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20339266/"
] |
74,500,258
|
<p>I am working on an Excel sheet where I need to determine my duration in hours, however the start time and end time are given in date. So I need to convert the duration from day to time in hours.</p>
<p>I subtract the start time from end time and I got the duration in day. But I need the duration to be in hours</p>
|
[
{
"answer_id": 74500384,
"author": "psafarcik",
"author_id": 5035543,
"author_profile": "https://Stackoverflow.com/users/5035543",
"pm_score": 1,
"selected": false,
"text": "localhost 8080 MLRun MLRun compose.yaml. services:\n mlrun-api:\n image: \"mlrun/mlrun-api:${TAG:-1.0.6}\"\n ports:\n - \"8180:8080\"\n environment:\n MLRUN_ARTIFACT_PATH: \"${SHARED_DIR}/{{project}}\"\n # using local storage, meaning files / artifacts are stored locally, so we want to allow access to them\n MLRUN_HTTPDB__REAL_PATH: /data\n MLRUN_HTTPDB__DATA_VOLUME: \"${SHARED_DIR}\"\n MLRUN_LOG_LEVEL: DEBUG\n MLRUN_NUCLIO_DASHBOARD_URL: http://nuclio:8070\n MLRUN_HTTPDB__DSN: \"sqlite:////data/mlrun.db?check_same_thread=false\"\n MLRUN_UI__URL: http://localhost:8060\n # not running on k8s meaning no need to store secrets\n MLRUN_SECRET_STORES__KUBERNETES__AUTO_ADD_PROJECT_SECRETS: \"false\"\n # let mlrun control nuclio resources\n MLRUN_HTTPDB__PROJECTS__FOLLOWERS: \"nuclio\"\n volumes:\n - \"${SHARED_DIR:?err}:/data\"\n networks:\n - mlrun\n\n mlrun-ui:\n image: \"mlrun/mlrun-ui:${TAG:-1.0.6}\"\n ports:\n - \"8060:8090\"\n environment:\n MLRUN_API_PROXY_URL: http://mlrun-api:8080\n MLRUN_NUCLIO_MODE: enable\n MLRUN_NUCLIO_API_URL: http://nuclio:8070\n MLRUN_NUCLIO_UI_URL: http://localhost:8070\n networks:\n - mlrun\n\n nuclio:\n image: \"quay.io/nuclio/dashboard:${NUCLIO_TAG:-stable-amd64}\"\n ports:\n - \"8070:8070\"\n environment:\n NUCLIO_DASHBOARD_EXTERNAL_IP_ADDRESSES: \"${HOST_IP:-127.0.0.1}\"\n volumes:\n - /var/run/docker.sock:/var/run/docker.sock\n networks:\n - mlrun\n\nnetworks:\n mlrun: {}\n docker ps -a 8080 docker stop <container_id / container_name>; docker rm <container_id / container_name> MLRun 8080 # for unix like systems\n# if you are using Windows, try to find the similar one command\n\nnetstat -ltnp | grep -w ':8080' \nlsof -i :8080\n 8080 kill <PROCESS_ID> MLRun"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20547464/"
] |
74,500,291
|
<p>I am trying to extract the <strong>objectId</strong> and <strong>displayName</strong> from below JSON format http result. But I have not been successful at all. can someone suggest me to extract <strong>objectId</strong> and <strong>displayName</strong>.</p>
<p>My code so far:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> var httpClient = new HttpClient
{
BaseAddress = new Uri("https://graph.windows.net/")
};
string URI = $"/{TenantID}/users?$filter=userPrincipalName%20eq%20'{EmailAddress}'&api-version=1.6";
httpClient.DefaultRequestHeaders.Remove("Authorization");
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + MSGraphToken);
HttpResponseMessage response = await httpClient.GetAsync(URI).ConfigureAwait(false);
var HttpsResponse = await response.Content.ReadAsStringAsync();
dynamic Result = JsonConvert.DeserializeObject<object>(HttpsResponse);
UserDetails UserDetailsList = new UserDetails();
dynamic OdataResult = Result["value"];
if (Result != null)
{
UserDetailsList.DisplayName = OdataResult.displayName ?? "N/A";
UserDetailsList.ObjectID = OdataResult.objectId ?? "N/A";
}
return UserDetailsList;</code></pre>
</div>
</div>
</p>
<p>JSON result:</p>
<pre><code>{{
"value": [
{
"odata.type": "Microsoft.DirectoryServices.User",
"objectType": "User",
"objectId": "00000000-0000-0000-0000-000000000000",
"assignedPlans": [
{
"assignedTimestamp": "2022-09-06T20:38:49Z",
"capabilityStatus": "Enabled",
"service": "RMSOnline",
"servicePlanId": "00000000-0000-0000-0000-000000000000"
},
{
"assignedTimestamp": "2022-09-06T20:38:49Z",
"capabilityStatus": "Enabled",
"service": "Adallom",
"servicePlanId": "00000000-0000-0000-0000-000000000000"
},
],
"displayName": "Sachin Tendulkar (alt_sachint)",
"employeeId": "000000",
"userPrincipalName": "alt_sachint@pme.gbl.msidentity.com"
}
]
}}
</code></pre>
|
[
{
"answer_id": 74500566,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 1,
"selected": false,
"text": "{\n \"value\": [{\n \"odata.type\": \"Microsoft.DirectoryServices.User\",\n \"objectType\": \"User\",\n \"objectId\": \"00000000-0000-0000-0000-000000000000\",\n \"assignedPlans\": [{\n \"assignedTimestamp\": \"2022-09-06T20:38:49Z\",\n \"capabilityStatus\": \"Enabled\",\n \"service\": \"RMSOnline\",\n \"servicePlanId\": \"00000000-0000-0000-0000-000000000000\"\n },\n {\n \"assignedTimestamp\": \"2022-09-06T20:38:49Z\",\n \"capabilityStatus\": \"Enabled\",\n \"service\": \"Adallom\",\n \"servicePlanId\": \"00000000-0000-0000-0000-000000000000\"\n }\n ],\n \"displayName\": \"Sachin Tendulkar (alt_sachint)\",\n \"employeeId\": \"000000\",\n \"userPrincipalName\": \"alt_sachint@pme.gbl.msidentity.com\"\n }]\n\n}\n Root obj = JsonConvert.DeserializeObject<Root>(myJsonResponse);\npublic class AssignedPlan\n{\n public DateTime assignedTimestamp { get; set; }\n public string capabilityStatus { get; set; }\n public string service { get; set; }\n public string servicePlanId { get; set; }\n}\n\npublic class Root\n{\n public List<Value> value { get; set; }\n}\n\npublic class Value\n{\n [JsonProperty(\"odata.type\")]\n public string odatatype { get; set; }\n public string objectType { get; set; }\n public string objectId { get; set; }\n public List<AssignedPlan> assignedPlans { get; set; }\n public string displayName { get; set; }\n public string employeeId { get; set; }\n public string userPrincipalName { get; set; }\n}\n obj.value Value objectId employeeId foreach for"
},
{
"answer_id": 74500775,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": 2,
"selected": true,
"text": "var json = await response.Content.ReadAsStringAsync();\nvar value = JObject.Parse(json)[\"value\"];\nstring objectId = (string)value[0][\"objectId\"]; // 00000000-0000-0000-0000-000000000000\nstring displayName = (string)value[0][\"displayName\"]; // Sachin Tendulkar (alt_sachint)\n"
},
{
"answer_id": 74500782,
"author": "Pradeep Kumar",
"author_id": 18704952,
"author_profile": "https://Stackoverflow.com/users/18704952",
"pm_score": 0,
"selected": false,
"text": "Using Strong Type private void ReadJson()\n {\n string json = @\"{\"\"value\"\":[{\"\"odata.type\"\":\"\"Microsoft.DirectoryServices.User\"\",\"\"objectType\"\":\"\"User\"\",\"\"objectId\"\":\"\"00000000 - 0000 - 0000 - 0000 - 000000000000\"\",\"\"assignedPlans\"\":[{\"\"assignedTimestamp\"\":\"\"2022 - 09 - 06T20: 38:49Z\"\",\"\"capabilityStatus\"\":\"\"Enabled\"\",\"\"service\"\":\"\"RMSOnline\"\",\"\"servicePlanId\"\":\"\"00000000 - 0000 - 0000 - 0000 - 000000000000\"\"},{\"\"assignedTimestamp\"\":\"\"2022 - 09 - 06T20: 38:49Z\"\",\"\"capabilityStatus\"\":\"\"Enabled\"\",\"\"service\"\":\"\"Adallom\"\",\"\"servicePlanId\"\":\"\"00000000 - 0000 - 0000 - 0000 - 000000000000\"\"},],\"\"displayName\"\":\"\"Sachin Tendulkar(alt_sachint)\"\",\"\"employeeId\"\":\"\"000000\"\",\"\"userPrincipalName\"\":\"\"alt_sachint @pme.gbl.msidentity.com\"\"}]}\";\n var response = JsonConvert.DeserializeObject<Result>(json);\n\n var objid = response.value[0].objectId;\n var displayname = response.value[0].displayName;\n\n // using for loop \n\n foreach( var res in response.value)\n {\n objid = res.objectId;\n displayname = res.displayName;\n }\n\n // you can use linq if you need object id and display name for specific condition\n\n \n }\n public class Result\n {\n public List<Response> value { get; set; }\n }\n\npublic class Response\n {\n public string objectId { get; set; }\n\n public string displayName { get; set; }\n\n [JsonProperty(\"odata.type\")]\n public string odatatype { get; set; }\n\n public string objectType { get; set; }\n\n public List<AssignedPlan> assignedPlans { get; set; }\n\n public string employeeId { get; set; }\n\n public string userPrincipalName { get; set; }\n }\n\n public class AssignedPlan\n {\n public DateTime assignedTimestamp { get; set; }\n public string capabilityStatus { get; set; }\n public string service { get; set; }\n public string servicePlanId { get; set; }\n }\n using dynamic // 2. using dynamic\n dynamic Result = JsonConvert.DeserializeObject<object>(json);\n JArray jsonObject = JArray.FromObject(Result[\"value\"]);\n //JArray jsonObject = JArray.Parse(Result[\"value\"]);\n foreach (JObject content in jsonObject.Children<JObject>())\n {\n // you can get value from one of the approach\n // 1. Approach\n foreach (JProperty prop in content.Properties().Where(p => p.Name == \"objectId\"))\n {\n objid = prop.Value.ToString();\n }\n\n foreach (JProperty prop in content.Properties().Where(p => p.Name == \"displayName\"))\n {\n displayname = prop.Value.ToString();\n }\n\n // 2. Apprach\n foreach (JProperty prop in content.Properties())\n {\n if (prop.Name == \"objectId\")\n {\n objid = prop.Value.ToString();\n }\n else if(prop.Name == \"displayName\")\n {\n displayname = prop.Value.ToString();\n }\n }\n\n }\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10964894/"
] |
74,500,331
|
<p>I need to create function that will change several elements in 1 string
Without declaring this as a function - it work properly, but in the function it changing only 1 random char
can u help me pls</p>
<pre><code>import Foundation
func makeItCool(_ string: String) -> String {
var newCoolString = string
let replaces = [
"a" : "@",
"o" : "0",
"t" : "+",
"i" : "1",
"s" : "$",
]
for (key, value) in replaces {
newCoolString = string.lowercased().replacingOccurrences(of: key, with: value)
}
return newCoolString
}
print(makeItCool("Swift is Awesame"))
</code></pre>
<p>//sw1ft 1s awesame</p>
<p>Working code</p>
<pre><code>var string = "Swift is Awesaome"
let replaces = [
"a" : "@",
"o" : "0",
"t" : "+",
"i" : "1",
"s" : "$",
]
for (key, value) in replaces {
string = string.lowercased().replacingOccurrences(of: key, with: value)
}
print(string)
</code></pre>
<p>// $w1f+ 1$ @we$@0me</p>
|
[
{
"answer_id": 74500566,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 1,
"selected": false,
"text": "{\n \"value\": [{\n \"odata.type\": \"Microsoft.DirectoryServices.User\",\n \"objectType\": \"User\",\n \"objectId\": \"00000000-0000-0000-0000-000000000000\",\n \"assignedPlans\": [{\n \"assignedTimestamp\": \"2022-09-06T20:38:49Z\",\n \"capabilityStatus\": \"Enabled\",\n \"service\": \"RMSOnline\",\n \"servicePlanId\": \"00000000-0000-0000-0000-000000000000\"\n },\n {\n \"assignedTimestamp\": \"2022-09-06T20:38:49Z\",\n \"capabilityStatus\": \"Enabled\",\n \"service\": \"Adallom\",\n \"servicePlanId\": \"00000000-0000-0000-0000-000000000000\"\n }\n ],\n \"displayName\": \"Sachin Tendulkar (alt_sachint)\",\n \"employeeId\": \"000000\",\n \"userPrincipalName\": \"alt_sachint@pme.gbl.msidentity.com\"\n }]\n\n}\n Root obj = JsonConvert.DeserializeObject<Root>(myJsonResponse);\npublic class AssignedPlan\n{\n public DateTime assignedTimestamp { get; set; }\n public string capabilityStatus { get; set; }\n public string service { get; set; }\n public string servicePlanId { get; set; }\n}\n\npublic class Root\n{\n public List<Value> value { get; set; }\n}\n\npublic class Value\n{\n [JsonProperty(\"odata.type\")]\n public string odatatype { get; set; }\n public string objectType { get; set; }\n public string objectId { get; set; }\n public List<AssignedPlan> assignedPlans { get; set; }\n public string displayName { get; set; }\n public string employeeId { get; set; }\n public string userPrincipalName { get; set; }\n}\n obj.value Value objectId employeeId foreach for"
},
{
"answer_id": 74500775,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": 2,
"selected": true,
"text": "var json = await response.Content.ReadAsStringAsync();\nvar value = JObject.Parse(json)[\"value\"];\nstring objectId = (string)value[0][\"objectId\"]; // 00000000-0000-0000-0000-000000000000\nstring displayName = (string)value[0][\"displayName\"]; // Sachin Tendulkar (alt_sachint)\n"
},
{
"answer_id": 74500782,
"author": "Pradeep Kumar",
"author_id": 18704952,
"author_profile": "https://Stackoverflow.com/users/18704952",
"pm_score": 0,
"selected": false,
"text": "Using Strong Type private void ReadJson()\n {\n string json = @\"{\"\"value\"\":[{\"\"odata.type\"\":\"\"Microsoft.DirectoryServices.User\"\",\"\"objectType\"\":\"\"User\"\",\"\"objectId\"\":\"\"00000000 - 0000 - 0000 - 0000 - 000000000000\"\",\"\"assignedPlans\"\":[{\"\"assignedTimestamp\"\":\"\"2022 - 09 - 06T20: 38:49Z\"\",\"\"capabilityStatus\"\":\"\"Enabled\"\",\"\"service\"\":\"\"RMSOnline\"\",\"\"servicePlanId\"\":\"\"00000000 - 0000 - 0000 - 0000 - 000000000000\"\"},{\"\"assignedTimestamp\"\":\"\"2022 - 09 - 06T20: 38:49Z\"\",\"\"capabilityStatus\"\":\"\"Enabled\"\",\"\"service\"\":\"\"Adallom\"\",\"\"servicePlanId\"\":\"\"00000000 - 0000 - 0000 - 0000 - 000000000000\"\"},],\"\"displayName\"\":\"\"Sachin Tendulkar(alt_sachint)\"\",\"\"employeeId\"\":\"\"000000\"\",\"\"userPrincipalName\"\":\"\"alt_sachint @pme.gbl.msidentity.com\"\"}]}\";\n var response = JsonConvert.DeserializeObject<Result>(json);\n\n var objid = response.value[0].objectId;\n var displayname = response.value[0].displayName;\n\n // using for loop \n\n foreach( var res in response.value)\n {\n objid = res.objectId;\n displayname = res.displayName;\n }\n\n // you can use linq if you need object id and display name for specific condition\n\n \n }\n public class Result\n {\n public List<Response> value { get; set; }\n }\n\npublic class Response\n {\n public string objectId { get; set; }\n\n public string displayName { get; set; }\n\n [JsonProperty(\"odata.type\")]\n public string odatatype { get; set; }\n\n public string objectType { get; set; }\n\n public List<AssignedPlan> assignedPlans { get; set; }\n\n public string employeeId { get; set; }\n\n public string userPrincipalName { get; set; }\n }\n\n public class AssignedPlan\n {\n public DateTime assignedTimestamp { get; set; }\n public string capabilityStatus { get; set; }\n public string service { get; set; }\n public string servicePlanId { get; set; }\n }\n using dynamic // 2. using dynamic\n dynamic Result = JsonConvert.DeserializeObject<object>(json);\n JArray jsonObject = JArray.FromObject(Result[\"value\"]);\n //JArray jsonObject = JArray.Parse(Result[\"value\"]);\n foreach (JObject content in jsonObject.Children<JObject>())\n {\n // you can get value from one of the approach\n // 1. Approach\n foreach (JProperty prop in content.Properties().Where(p => p.Name == \"objectId\"))\n {\n objid = prop.Value.ToString();\n }\n\n foreach (JProperty prop in content.Properties().Where(p => p.Name == \"displayName\"))\n {\n displayname = prop.Value.ToString();\n }\n\n // 2. Apprach\n foreach (JProperty prop in content.Properties())\n {\n if (prop.Name == \"objectId\")\n {\n objid = prop.Value.ToString();\n }\n else if(prop.Name == \"displayName\")\n {\n displayname = prop.Value.ToString();\n }\n }\n\n }\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20547706/"
] |
74,500,334
|
<p>I have a design with a glass morphism card, behind it 2 circles are orbiting it.
Here is the ref pic from where I took the inspiration <a href="https://cdn.dribbble.com/users/172469/screenshots/14675787/media/45fb06bdf05226d49be086b3dd4a960a.png?compress=1&resize=400x300" rel="nofollow noreferrer">here</a>.
So, I have somewhat achieved my result, but the main problem is those outer circles are creating scrollbars both vertically and horizontally along the way which I don't want it to create.
How do I tell the browser to not create the scrollbars. Like for example the browser cuts them whenever the circles are not visible, just like <code>overlay:hidden;</code>. I've also used this method, but they still create the scrollbars.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const downloadbtn = document.querySelector(".download_btn");
downloadbtn.addEventListener("click", () => {
let time = Number(downloadbtn.dataset.time);
downloadbtn.classList.add("timer");
downloadbtn.innerHTML = `Your file will download in<b>${time}</b>seconds.`;
const initCounter = setInterval(() => {
if (time > 0) {
time--;
return (downloadbtn.innerHTML = `Your file will download in<b>${time}</b>seconds.`);
}
downloadbtn.innerHTML = `Your file is downloading...`;
clearInterval(initCounter);
setTimeout(() => {
downloadbtn.classList.remove("timer");
downloadbtn.innerHTML = `
<i class="fa-solid fa-download"></i>
<span class="text">Download Again!</span>`;
}, 5000);
}, 1000);
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
@keyframes rotate {
from {
-webkit-transform: rotate(0deg);
}
to {
-webkit-transform: rotate(360deg);
}
}
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
position: relative;
background: rgb(128, 237, 153);
background: linear-gradient( 19deg, rgba(128, 237, 153, 1) 0%, rgba(56, 163, 165, 1) 100%);
}
.download_btn_wrapper {
background: red;
width: 365px;
height: 350px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 10px;
background: rgba(255, 255, 255, 0.3);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
border: 1px solid rgba(255, 255, 255, 0.18);
}
.download_btn {
display: block;
background: #4a98f7;
padding: 1rem 1.2rem;
color: white;
border-radius: 6px;
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease-in-out;
cursor: pointer;
}
.download_btn:hover {
background: #2382f6;
}
.download_btn.timer {
background: transparent;
color: black;
box-shadow: none;
transition: none;
pointer-events: none;
}
.download_btn.timer b {
color: #4a98f7;
padding: 0 8px;
}
.rotate_div {
width: 70%;
height: 360px;
border-radius: 50%;
position: absolute;
z-index: -1;
-webkit-animation: rotate 32s infinite linear;
}
.rotate_div:before,
.rotate_div:after {
content: "";
display: inline-block;
width: 160px;
height: 160px;
position: absolute;
border-radius: 50%;
filter: blur(1px);
}
.rotate_div:before {
z-index: -2;
background: black;
top: -10%;
left: -10%;
}
.rotate_div:after {
z-index: -3;
background: #9d4edd;
bottom: -10%;
right: -10%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="download_btn_wrapper">
<div class="download_btn" data-time=5>
<i class="fa-solid fa-download"></i>
<span class="text">Download Now</span>
</div>
</section>
<div class="rotate_div">&nbsp;</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74500689,
"author": "tacoshy",
"author_id": 14072420,
"author_profile": "https://Stackoverflow.com/users/14072420",
"pm_score": 0,
"selected": false,
"text": "overflow: hidden fixed height width max- height width const downloadbtn = document.querySelector(\".download_btn\");\ndownloadbtn.addEventListener(\"click\", () => {\n let time = Number(downloadbtn.dataset.time);\n downloadbtn.classList.add(\"timer\");\n downloadbtn.innerHTML = `Your file will download in<b>${time}</b>seconds.`;\n const initCounter = setInterval(() => {\n if (time > 0) {\n time--;\n return (downloadbtn.innerHTML = `Your file will download in<b>${time}</b>seconds.`);\n }\n downloadbtn.innerHTML = `Your file is downloading...`;\n clearInterval(initCounter);\n setTimeout(() => {\n downloadbtn.classList.remove(\"timer\");\n downloadbtn.innerHTML = ` \n <i class=\"fa-solid fa-download\"></i>\n <span class=\"text\">Download Again!</span>`;\n }, 5000);\n }, 1000);\n}); body {\n max-width: 100vw;\n max-height: 100vh;\n overflow: hidden;\n}\n\n/* original css */\n* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n font-family: \"Poppins\", sans-serif;\n}\n\n@keyframes rotate {\n from {\n -webkit-transform: rotate(0deg);\n }\n to {\n -webkit-transform: rotate(360deg);\n }\n}\n\nbody {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100vh;\n position: relative;\n background: rgb(128, 237, 153);\n background: linear-gradient( 19deg, rgba(128, 237, 153, 1) 0%, rgba(56, 163, 165, 1) 100%);\n}\n\n.download_btn_wrapper {\n background: red;\n width: 365px;\n height: 350px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 10px;\n background: rgba(255, 255, 255, 0.3);\n backdrop-filter: blur(14px);\n -webkit-backdrop-filter: blur(14px);\n border: 1px solid rgba(255, 255, 255, 0.18);\n}\n\n.download_btn {\n display: block;\n background: #4a98f7;\n padding: 1rem 1.2rem;\n color: white;\n border-radius: 6px;\n box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);\n transition: all 0.3s ease-in-out;\n cursor: pointer;\n}\n\n.download_btn:hover {\n background: #2382f6;\n}\n\n.download_btn.timer {\n background: transparent;\n color: black;\n box-shadow: none;\n transition: none;\n pointer-events: none;\n}\n\n.download_btn.timer b {\n color: #4a98f7;\n padding: 0 8px;\n}\n\n.rotate_div {\n width: 70%;\n height: 360px;\n border-radius: 50%;\n position: absolute;\n z-index: -1;\n -webkit-animation: rotate 32s infinite linear;\n}\n\n.rotate_div:before,\n.rotate_div:after {\n content: \"\";\n display: inline-block;\n width: 160px;\n height: 160px;\n position: absolute;\n border-radius: 50%;\n filter: blur(1px);\n}\n\n.rotate_div:before {\n z-index: -2;\n background: black;\n top: -10%;\n left: -10%;\n}\n\n.rotate_div:after {\n z-index: -3;\n background: #9d4edd;\n bottom: -10%;\n right: -10%;\n} <section class=\"download_btn_wrapper\">\n <div class=\"download_btn\" data-time=5>\n <i class=\"fa-solid fa-download\"></i>\n <span class=\"text\">Download Now</span>\n </div>\n</section>\n<div class=\"rotate_div\"> </div>"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20182014/"
] |
74,500,363
|
<p>I want to display an image in my app.
Like this :</p>
<pre><code>class _OnBoardingDataPage1State extends State<OnBoardingDataPage1> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: SingleChildScrollView(
child: SizedBox(
width: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(height: 5.h),
Text(
"MugiwarApp",
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.titleLarge,
),
SizedBox(
height: 5.h,
),
Image.asset(
"assets/images/th-2465707242.png",
height: 250.0,
width: 250.0,
)
]),
)),
));
}
}
</code></pre>
<p>Every images are displaying great, except ONE: my logo.</p>
<p>My pubspec.yaml :</p>
<pre><code>flutter:
assets:
- assets/
</code></pre>
<p>I can't figure why only my logo can't be displayed.</p>
|
[
{
"answer_id": 74500689,
"author": "tacoshy",
"author_id": 14072420,
"author_profile": "https://Stackoverflow.com/users/14072420",
"pm_score": 0,
"selected": false,
"text": "overflow: hidden fixed height width max- height width const downloadbtn = document.querySelector(\".download_btn\");\ndownloadbtn.addEventListener(\"click\", () => {\n let time = Number(downloadbtn.dataset.time);\n downloadbtn.classList.add(\"timer\");\n downloadbtn.innerHTML = `Your file will download in<b>${time}</b>seconds.`;\n const initCounter = setInterval(() => {\n if (time > 0) {\n time--;\n return (downloadbtn.innerHTML = `Your file will download in<b>${time}</b>seconds.`);\n }\n downloadbtn.innerHTML = `Your file is downloading...`;\n clearInterval(initCounter);\n setTimeout(() => {\n downloadbtn.classList.remove(\"timer\");\n downloadbtn.innerHTML = ` \n <i class=\"fa-solid fa-download\"></i>\n <span class=\"text\">Download Again!</span>`;\n }, 5000);\n }, 1000);\n}); body {\n max-width: 100vw;\n max-height: 100vh;\n overflow: hidden;\n}\n\n/* original css */\n* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n font-family: \"Poppins\", sans-serif;\n}\n\n@keyframes rotate {\n from {\n -webkit-transform: rotate(0deg);\n }\n to {\n -webkit-transform: rotate(360deg);\n }\n}\n\nbody {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100vh;\n position: relative;\n background: rgb(128, 237, 153);\n background: linear-gradient( 19deg, rgba(128, 237, 153, 1) 0%, rgba(56, 163, 165, 1) 100%);\n}\n\n.download_btn_wrapper {\n background: red;\n width: 365px;\n height: 350px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 10px;\n background: rgba(255, 255, 255, 0.3);\n backdrop-filter: blur(14px);\n -webkit-backdrop-filter: blur(14px);\n border: 1px solid rgba(255, 255, 255, 0.18);\n}\n\n.download_btn {\n display: block;\n background: #4a98f7;\n padding: 1rem 1.2rem;\n color: white;\n border-radius: 6px;\n box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);\n transition: all 0.3s ease-in-out;\n cursor: pointer;\n}\n\n.download_btn:hover {\n background: #2382f6;\n}\n\n.download_btn.timer {\n background: transparent;\n color: black;\n box-shadow: none;\n transition: none;\n pointer-events: none;\n}\n\n.download_btn.timer b {\n color: #4a98f7;\n padding: 0 8px;\n}\n\n.rotate_div {\n width: 70%;\n height: 360px;\n border-radius: 50%;\n position: absolute;\n z-index: -1;\n -webkit-animation: rotate 32s infinite linear;\n}\n\n.rotate_div:before,\n.rotate_div:after {\n content: \"\";\n display: inline-block;\n width: 160px;\n height: 160px;\n position: absolute;\n border-radius: 50%;\n filter: blur(1px);\n}\n\n.rotate_div:before {\n z-index: -2;\n background: black;\n top: -10%;\n left: -10%;\n}\n\n.rotate_div:after {\n z-index: -3;\n background: #9d4edd;\n bottom: -10%;\n right: -10%;\n} <section class=\"download_btn_wrapper\">\n <div class=\"download_btn\" data-time=5>\n <i class=\"fa-solid fa-download\"></i>\n <span class=\"text\">Download Now</span>\n </div>\n</section>\n<div class=\"rotate_div\"> </div>"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19904553/"
] |
74,500,379
|
<p>I would like to undestand where a <em>stdin</em> redirection goes in an expression like <code>< <(cmd)</code></p>
<p>as a test to learn more about bash I tried to write a bash function with <code>while .. do .. done</code> and to have it working I had to use a trial and error method , mainly because I did not know the behavior or the first redirection in <code>< <(find ...)</code>:</p>
<pre class="lang-bash prettyprint-override"><code>while read L ;do basename "$L";((k++));done < <(
find -maxdepth 1 -type d -name '.*' |
sort
)
</code></pre>
<p>With only <code><(find ...</code> it does not work . I suppose it's because <em>stdout</em> of <code>find</code> command line goes to a tmp file ( so I read ) ; so I added one more <code><</code> to "push" further the copy of <em>stdout</em> . That I can understand , but how can I know that <em>stdout</em> copied in the tmp file does not stop at the first command encountered : <code>basename</code> and goes as far as <em>stdin</em> of <code>while</code> command ?</p>
|
[
{
"answer_id": 74500774,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": true,
"text": "<(...) $ echo <(echo foo)\n/dev/fd/63\n$ cat <(echo foo; echo bar)\nfoo\nbar\n while $ while read x; do echo \"$x\"; done <(echo foo; echo bar)\nbash: syntax error near unexpected token `<(echo foo; echo bar)'\n while $ while read x; do echo \"$x\"; done < <(echo foo; echo bar)\nfoo\nbar\n while while read read read"
},
{
"answer_id": 74500794,
"author": "KamilCuk",
"author_id": 9072753,
"author_profile": "https://Stackoverflow.com/users/9072753",
"pm_score": 0,
"selected": false,
"text": "Simple command (see Simple Commands)\n\nPipeline (see Pipelines)\n\nList compound-list (see Lists)\n\nCompound command (see Compound Commands)\n\nFunction definition (see Function Definition Command)\n while while while\n redirected here\ndo\n redirected here\ndone < redirection\n\nif\n redirected here\nthen\n redirected here\nelse\n redirected here\nfi < redirection\n\netc.\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20547655/"
] |
74,500,427
|
<p>I would like to format a string with authors' names.</p>
<p><code>Daenerys Targaryen</code> to <code>TARGARYEN, D.</code></p>
<p><code>George R. R. Martin</code> to <code>MARTIN, G. G. R.</code></p>
<p><code>Luís Inácio Lula da Silva</code> to <code>SILVA, L. I. L. da</code></p>
<p>The pattern is
<code>LAST, 1st. 2nd. 3rd. ...</code>.</p>
<p>It would be awesome if it's possible to format multiple names in one string, like</p>
<p><code>Daenerys Targaryen, Luís Inácio Lula da Silva</code> to <code>TARGARYEN, D.; SILVA, L. I. L. da</code></p>
|
[
{
"answer_id": 74500540,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 2,
"selected": false,
"text": "fun <- function(x) {\n y <- strsplit(x, \" \")\n sapply(y, \\(s) {\n if(any(nchar(s) == 0L))\n s <- s[nchar(s) > 0L]\n if(all(nchar(s))) {\n n <- length(s)\n out <- character(n)\n out[1L] <- toupper(s[n])\n if(n > 1L)\n out[1L] <- paste0(out[1L], \",\")\n first <- substr(s[seq.int(n)[-n]], 1L, 1L)\n i <- first == toupper(first)\n out[-1L][i] <- paste0(first[i], \".\")\n out[-1L][!i] <- s[!i]\n paste(out, collapse = \" \")\n } else \"\"\n })\n}\n\nx <- c(\"Daenerys Targaryen\",\n \"George R. R. Martin\",\n \"Luís Inácio Lula da Silva\")\n\nfun(x)\n#> [1] \"TARGARYEN, D.\" \"MARTIN, G. R. R.\" \"SILVA, L. I. L. da\"\n y <- c(\"Daenerys Targaryen, Luís Inácio Lula da Silva\")\nll <- lapply(strsplit(y, \", \"), fun)\ndo.call(\\(x) paste(x, collapse = \"; \"), ll)\n#> [1] \"TARGARYEN, D.; SILVA, L. I. L. da\"\n"
},
{
"answer_id": 74500712,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "gsub() \"\\\\U...\\\\E\" library(magrittr)\n\nx <- c(\"Daenerys Targaryen, George R. R. Martin, Luís Inácio Lula da Silva\")\n\nx %>%\n strsplit(\", \") %>%\n unlist() %>% \n gsub(\"(.*?) (\\\\w+$)\", \"\\\\U\\\\2\\\\E, \\\\1\", ., perl = TRUE) %>%\n gsub(\" ([A-Z])\\\\w*\\\\.?\", \" \\\\1.\", .) %>%\n paste(collapse = \"; \")\n\n# [1] \"TARGARYEN, D.; MARTIN, G. R. R.; SILVA, L. I. L. da\"\n"
}
] |
2022/11/19
|
[
"https://Stackoverflow.com/questions/74500427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15611828/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.