content
stringlengths 86
88.9k
| title
stringlengths 0
150
| question
stringlengths 1
35.8k
| answers
sequence | answers_scores
sequence | non_answers
sequence | non_answers_scores
sequence | tags
sequence | name
stringlengths 30
130
|
---|---|---|---|---|---|---|---|---|
Q:
How to "select DISTINCT" many tables in oledb in vb.net
I wanted to do the sql command "select DISTINCT" but it didn't work if there was another solution. I have four tables namely GSDTS, GSGTS, STFTS and TEMPTABL.
Thanks
error
Private Sub PopulateComboBox()
Dim query As String = "SELECT DISTINCT PNM FROM GSDTS"
Try
Using con As OleDbConnection = New OleDbConnection(cn)
Using sda As OleDbDataAdapter = New OleDbDataAdapter(query, con)
'Fill the DataTable with records from Table.
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
'Insert the Default Item to DataTable.
Dim row As DataRow = dt.NewRow()
row(0) = ""
dt.Rows.InsertAt(row, 0)
'Assign DataTable as DataSource
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "PNM"
ComboBox1.ValueMember = "PNM"
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
A:
you neeed to cnage the query to
SELECT DISTINCT PNM FROM GSDTS
UNION
SELECT DISTINCT PNM FROM GSGTS
UNION
SELECT DISTINCT PNM FROM STFTS
UNION
SELECT DISTINCT PNM FROM TEMPTAB
ORDER BY PNM
the DISINCT will only take UNIQUE OMN and the UNION will take care of all duplicates.
But you will so never know,. which PMN belongs to which table.
| How to "select DISTINCT" many tables in oledb in vb.net | I wanted to do the sql command "select DISTINCT" but it didn't work if there was another solution. I have four tables namely GSDTS, GSGTS, STFTS and TEMPTABL.
Thanks
error
Private Sub PopulateComboBox()
Dim query As String = "SELECT DISTINCT PNM FROM GSDTS"
Try
Using con As OleDbConnection = New OleDbConnection(cn)
Using sda As OleDbDataAdapter = New OleDbDataAdapter(query, con)
'Fill the DataTable with records from Table.
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
'Insert the Default Item to DataTable.
Dim row As DataRow = dt.NewRow()
row(0) = ""
dt.Rows.InsertAt(row, 0)
'Assign DataTable as DataSource
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "PNM"
ComboBox1.ValueMember = "PNM"
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
| [
"you neeed to cnage the query to\nSELECT DISTINCT PNM FROM GSDTS\nUNION\nSELECT DISTINCT PNM FROM GSGTS\nUNION\nSELECT DISTINCT PNM FROM STFTS \nUNION\nSELECT DISTINCT PNM FROM TEMPTAB\nORDER BY PNM\n\nthe DISINCT will only take UNIQUE OMN and the UNION will take care of all duplicates.\nBut you will so never know,. which PMN belongs to which table.\n"
] | [
0
] | [] | [] | [
"dbf",
"distinct",
"oledb",
"select",
"sql"
] | stackoverflow_0074677356_dbf_distinct_oledb_select_sql.txt |
Q:
Skewness and Kurtosis Calculation on BigQuery and Standard SQL
How can I create Skewness and Kurtosis statistical functions, which are like Python scipy/pandas on Big query?
I have researched UDFs, but I know that these structures do not allow aggregated and windowed operations. These two statistical calculations are not included in Big Query by default.
A:
You won't need a UDF for that - the definition of the statistical moments isn't so complex.
The first two may have built in versions, but let's cover them as well as the two you're interested in:
mean
The first statistical moment is the mean. As a simple aggregate value: SUM(field)/COUNT(field)
You could create a new column with this value using a window function (which you mentioned)
SELECT
COUNT(field) OVER(w) AS n,
SUM(field) OVER(w) / COUNT(field) OVER(w) AS mean
FROM
some_table
Here w would be the definition of a window. I have added a field n for later convenience.
variance
Okay, so now we have the mean. The variance is the second statistical moment, and builds on the definition of the mean:
SELECT
POW(SUM(field - mean), 2) OVER(w) / n AS variance
FROM
some_table
You can see that defining n previously made this more concise.
The square root of the variance (SQRT(variance) AS sdev) is the standard deviation. Let's also add this sdev column for future convenience.
skewness
On to the third moment! The skewness continues to build on the first two moments:
SELECT
POW(SUM(field - mean), 3) OVER(w) / (n * POW(sdev, 3)) OVER(w) AS skewness,
FROM
some_table
(note how defining sdev makes this more concise)
kurtosis
And so we arrive at my favourite, the fourth statistical moment, the one with a name that makes you sound clever if you know it. There are actually two slightly different definitions, but moving between them is simple.
SELECT
POW(SUM(field - mean), 4) OVER(w) / (n * POW(sdev, 4)) OVER(w) AS kurtosis,
FROM
some_table
And we could define kurtosis - 3 AS x_kurtosis if we prefer that definition (kurtosis of a Normal distribution is 3, so subtracting 3 makes it 0 - then a kurtosis of, say 3.1 is an 'excess kurtosis' of 0.1).
| Skewness and Kurtosis Calculation on BigQuery and Standard SQL | How can I create Skewness and Kurtosis statistical functions, which are like Python scipy/pandas on Big query?
I have researched UDFs, but I know that these structures do not allow aggregated and windowed operations. These two statistical calculations are not included in Big Query by default.
| [
"You won't need a UDF for that - the definition of the statistical moments isn't so complex.\nThe first two may have built in versions, but let's cover them as well as the two you're interested in:\nmean\nThe first statistical moment is the mean. As a simple aggregate value: SUM(field)/COUNT(field)\nYou could create a new column with this value using a window function (which you mentioned)\n SELECT\n COUNT(field) OVER(w) AS n,\n SUM(field) OVER(w) / COUNT(field) OVER(w) AS mean\n FROM\n some_table\n\nHere w would be the definition of a window. I have added a field n for later convenience.\nvariance\nOkay, so now we have the mean. The variance is the second statistical moment, and builds on the definition of the mean:\n SELECT\n POW(SUM(field - mean), 2) OVER(w) / n AS variance\n FROM\n some_table\n\nYou can see that defining n previously made this more concise.\nThe square root of the variance (SQRT(variance) AS sdev) is the standard deviation. Let's also add this sdev column for future convenience.\nskewness\nOn to the third moment! The skewness continues to build on the first two moments:\n SELECT\n POW(SUM(field - mean), 3) OVER(w) / (n * POW(sdev, 3)) OVER(w) AS skewness,\n FROM\n some_table\n\n(note how defining sdev makes this more concise)\nkurtosis\nAnd so we arrive at my favourite, the fourth statistical moment, the one with a name that makes you sound clever if you know it. There are actually two slightly different definitions, but moving between them is simple.\n SELECT\n POW(SUM(field - mean), 4) OVER(w) / (n * POW(sdev, 4)) OVER(w) AS kurtosis,\n FROM\n some_table\n\nAnd we could define kurtosis - 3 AS x_kurtosis if we prefer that definition (kurtosis of a Normal distribution is 3, so subtracting 3 makes it 0 - then a kurtosis of, say 3.1 is an 'excess kurtosis' of 0.1).\n"
] | [
0
] | [] | [] | [
"google_bigquery",
"statistics"
] | stackoverflow_0074677116_google_bigquery_statistics.txt |
Q:
Writing the header file of my own library
I write some functions to use dinamic arrays in c, without the problem of pointers ecc. , and
now that i write enough code to use it properly, i want to encapsulate all this functions in a library.
Anyway in many of this function i use memcpy() method of the string.h.
So my question is:
Need i to include string.h in the .h file?
if i use string.h in the application where i will include my own library, will it be compilated two times?
is there a way to optimising the compilation?
There aren't some guides about it online, and if there are, they are so ambiguos and confusing.
I found something about the ifdef but i don't really understand how and why use it.
Can somebody give me an example of the header file with a similar scenario, or at least a tutorial for writing header files?
This is the first time that i try to write a library in c, so all tips will be appreciate.
A:
Your header file will be shared between the final application and your library. Therefore, the best place to include <string.h> is your header file.
Do not worry about system or standard headers being included more than once. They normally have protective #ifdefs which take care of including the code only once.
As a good practice you can also insert a custom #ifdef in your header. For instance, your header file would look like this:
/* Beginning of header file */
#ifndef ALEX_XXX_HEADER
#define ALEX_XXX_HEADER
/* Your header constants, prototypes, etc. here */
#endif
/* End of header file */
In this way, the compiler will first check whether _ALEX_XXX_HEADER has been defined. If it hasn't, it means it is the first time it hits this file. Then, it defines your header macro _ALEX_XXX_HEADER and processes all the code in the header.
If the header is included more than once, the next time the compiler finds the #ifndef line, it will skip the entire #ifndef clause. In other words, it will skip the entire header file. As a result, the header code will be included once only.
| Writing the header file of my own library | I write some functions to use dinamic arrays in c, without the problem of pointers ecc. , and
now that i write enough code to use it properly, i want to encapsulate all this functions in a library.
Anyway in many of this function i use memcpy() method of the string.h.
So my question is:
Need i to include string.h in the .h file?
if i use string.h in the application where i will include my own library, will it be compilated two times?
is there a way to optimising the compilation?
There aren't some guides about it online, and if there are, they are so ambiguos and confusing.
I found something about the ifdef but i don't really understand how and why use it.
Can somebody give me an example of the header file with a similar scenario, or at least a tutorial for writing header files?
This is the first time that i try to write a library in c, so all tips will be appreciate.
| [
"Your header file will be shared between the final application and your library. Therefore, the best place to include <string.h> is your header file.\nDo not worry about system or standard headers being included more than once. They normally have protective #ifdefs which take care of including the code only once.\nAs a good practice you can also insert a custom #ifdef in your header. For instance, your header file would look like this:\n/* Beginning of header file */\n#ifndef ALEX_XXX_HEADER\n\n#define ALEX_XXX_HEADER\n\n/* Your header constants, prototypes, etc. here */\n\n#endif\n/* End of header file */\n\nIn this way, the compiler will first check whether _ALEX_XXX_HEADER has been defined. If it hasn't, it means it is the first time it hits this file. Then, it defines your header macro _ALEX_XXX_HEADER and processes all the code in the header.\nIf the header is included more than once, the next time the compiler finds the #ifndef line, it will skip the entire #ifndef clause. In other words, it will skip the entire header file. As a result, the header code will be included once only.\n"
] | [
1
] | [] | [] | [
"c",
"c_preprocessor",
"header_files",
"include",
"static_libraries"
] | stackoverflow_0074677388_c_c_preprocessor_header_files_include_static_libraries.txt |
Q:
Tutorial - Adding OpenCV JS to an ELECTRON project
I've been stuck on this for the last few hours so I'll just post the answer to my question here so you won't have to.
I'm running windows 10 and am developing an Electron application running Node v12.16.1 and electron v8.2.0.
I've been following various tutorials and none of them worked or managed to break in some other convoluted way. I tried opencv4nodejs and various other solution and this ended up the most reliable way to get OpenCV js to work.
This is the way I managed to get it to work:
<script async src="https://docs.opencv.org/master/opencv.js" onload="onOpenCvReady()" type="text/javascript"></script>
just add this line at the end of your HTML file. This script will automatically load a pre-compiled js file from the OpenCV site which I'm pretty sure they never mention. This script is pretty much equivalent to let cv = require('cv') or similar things I've seen come by. Once this file is loaded it will call onOpenCvReady().
In your HTML file, you can now just run the example from the OpenCV website.
<script>
let imgElement = document.getElementById('imageSrc');
let inputElement = document.getElementById('fileInput');
inputElement.addEventListener('change', (e) => {
imgElement.src = URL.createObjectURL(e.target.files[0]);
}, false);
imgElement.onload = function() {
let mat = cv.imread(imgElement);
cv.imshow('canvasOutput', mat);
mat.delete();
};
// Entry Point:
function onOpenCvReady() {
document.getElementById('status').innerHTML = 'OpenCV.js is ready.';
}
</script>
I hope this works for you!
My total example roughly looked like this:
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="mainWindow.css">
<head>
<title>Man Machine Exhibition</title>
</head>
<body>
<div class='container'>
<p id="status">OpenCV.js is loading...</p>
</div>
<div class="container">
<div class="inputoutput">
<img id="imageSrc" alt="No Image" />
<div class="caption">imageSrc <input type="file" id="fileInput" name="file" /></div>
</div>
<div class="inputoutput">
<canvas id="canvasOutput" ></canvas>
<div class="caption">canvasOutput</div>
</div>
</div>
</body>
<script>
let imgElement = document.getElementById('imageSrc');
let inputElement = document.getElementById('fileInput');
inputElement.addEventListener('change', (e) => {
imgElement.src = URL.createObjectURL(e.target.files[0]);
}, false);
imgElement.onload = function() {
let mat = cv.imread(imgElement);
cv.imshow('canvasOutput', mat);
mat.delete();
};
function onOpenCvReady() {
document.getElementById('status').innerHTML = 'OpenCV.js is ready.';
}
</script>
<script async src="https://docs.opencv.org/master/opencv.js" onload="onOpenCvReady()" type="text/javascript"></script>
</html>
A:
Opencv-flow is a Web and Electron Project and this project is opensource too.
I think you need to check how it works.
Links:
https://opencvflow.org/
| Tutorial - Adding OpenCV JS to an ELECTRON project | I've been stuck on this for the last few hours so I'll just post the answer to my question here so you won't have to.
I'm running windows 10 and am developing an Electron application running Node v12.16.1 and electron v8.2.0.
I've been following various tutorials and none of them worked or managed to break in some other convoluted way. I tried opencv4nodejs and various other solution and this ended up the most reliable way to get OpenCV js to work.
This is the way I managed to get it to work:
<script async src="https://docs.opencv.org/master/opencv.js" onload="onOpenCvReady()" type="text/javascript"></script>
just add this line at the end of your HTML file. This script will automatically load a pre-compiled js file from the OpenCV site which I'm pretty sure they never mention. This script is pretty much equivalent to let cv = require('cv') or similar things I've seen come by. Once this file is loaded it will call onOpenCvReady().
In your HTML file, you can now just run the example from the OpenCV website.
<script>
let imgElement = document.getElementById('imageSrc');
let inputElement = document.getElementById('fileInput');
inputElement.addEventListener('change', (e) => {
imgElement.src = URL.createObjectURL(e.target.files[0]);
}, false);
imgElement.onload = function() {
let mat = cv.imread(imgElement);
cv.imshow('canvasOutput', mat);
mat.delete();
};
// Entry Point:
function onOpenCvReady() {
document.getElementById('status').innerHTML = 'OpenCV.js is ready.';
}
</script>
I hope this works for you!
My total example roughly looked like this:
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="mainWindow.css">
<head>
<title>Man Machine Exhibition</title>
</head>
<body>
<div class='container'>
<p id="status">OpenCV.js is loading...</p>
</div>
<div class="container">
<div class="inputoutput">
<img id="imageSrc" alt="No Image" />
<div class="caption">imageSrc <input type="file" id="fileInput" name="file" /></div>
</div>
<div class="inputoutput">
<canvas id="canvasOutput" ></canvas>
<div class="caption">canvasOutput</div>
</div>
</div>
</body>
<script>
let imgElement = document.getElementById('imageSrc');
let inputElement = document.getElementById('fileInput');
inputElement.addEventListener('change', (e) => {
imgElement.src = URL.createObjectURL(e.target.files[0]);
}, false);
imgElement.onload = function() {
let mat = cv.imread(imgElement);
cv.imshow('canvasOutput', mat);
mat.delete();
};
function onOpenCvReady() {
document.getElementById('status').innerHTML = 'OpenCV.js is ready.';
}
</script>
<script async src="https://docs.opencv.org/master/opencv.js" onload="onOpenCvReady()" type="text/javascript"></script>
</html>
| [
"\nOpencv-flow is a Web and Electron Project and this project is opensource too.\nI think you need to check how it works.\nLinks:\nhttps://opencvflow.org/\n"
] | [
0
] | [] | [] | [
"electron",
"javascript",
"node.js",
"opencv"
] | stackoverflow_0061022781_electron_javascript_node.js_opencv.txt |
Q:
Which protocol (AMQP or MQTT) should I use with RabbitMQ for internal communication among microservices?
I need help on following:
I want to use RabbitMQ message broker for internal communication among microservices. For example shopping cart, order, product, payment etc.
Can I use AMQP for internal communication among microservices &
MQTT for push notification to mobile & web browser?
Can I use both AMQP & MQTT with RabbitMQ at the same time or only one can be used not both?
A:
You can use both AMQP and MQTT with RabbitMQ at the same time. RabbitMQ supports both protocols, and you can use them for different purposes.
AMQP is a more robust and feature-rich protocol than MQTT, and it is well-suited for implementing complex messaging scenarios and communication between different services. It is often used for internal communication among microservices.
MQTT, on the other hand, is a lightweight protocol designed for low-bandwidth, high-latency networks. It is often used for push notifications to mobile and web browsers, as well as for sending messages to IoT devices.
In your case, you could use AMQP for communication among your microservices, and use MQTT for push notifications to mobile and web browsers. This would allow you to take advantage of the strengths of both protocols, and use the best one for each specific use case.
| Which protocol (AMQP or MQTT) should I use with RabbitMQ for internal communication among microservices? | I need help on following:
I want to use RabbitMQ message broker for internal communication among microservices. For example shopping cart, order, product, payment etc.
Can I use AMQP for internal communication among microservices &
MQTT for push notification to mobile & web browser?
Can I use both AMQP & MQTT with RabbitMQ at the same time or only one can be used not both?
| [
"You can use both AMQP and MQTT with RabbitMQ at the same time. RabbitMQ supports both protocols, and you can use them for different purposes.\nAMQP is a more robust and feature-rich protocol than MQTT, and it is well-suited for implementing complex messaging scenarios and communication between different services. It is often used for internal communication among microservices.\nMQTT, on the other hand, is a lightweight protocol designed for low-bandwidth, high-latency networks. It is often used for push notifications to mobile and web browsers, as well as for sending messages to IoT devices.\nIn your case, you could use AMQP for communication among your microservices, and use MQTT for push notifications to mobile and web browsers. This would allow you to take advantage of the strengths of both protocols, and use the best one for each specific use case.\n"
] | [
1
] | [] | [] | [
"amqp",
"messagebroker",
"mqtt",
"rabbitmq"
] | stackoverflow_0074677360_amqp_messagebroker_mqtt_rabbitmq.txt |
Q:
Can I host my wordpress blog on github pages as a static webpage
I would like to make my WordPress blog installed on Localhost to push into GitHub and run that on GitHub as a static page. Can I do it, and if yes please give me a detailed answer with the steps and problems involved?
I don't care if my page is static, but will I be able to host it on GitHub pages?
A:
This website gives a good answer on how to do this: https://www.hywel.me/static/site/wordpress/2016/07/17/fast-free-static-website-with-wordpress-and-github-pages.html
In short:
Set-up GitHub pages.
Install Simply static plugin into WordPress.
Push the export from the plug-in back to your git repository and you are done!
A:
You can't. You would use WordPress if you want a dynamic page - that is the whole point of using it. You could of course grab the html generated by WordPress and push that to your GitHub, but that I think that would be a lot of manual work.
You could try a static page generator, i.e. https://github.com/jekyll/jekyll
A:
If you absolutely can't switch from wordpress, but absolutely need to host on github pages, then your only option is probably to look into some wordpress plugin that will take your entire site and spit out a static website (sort of like jekyll, but for wordpress specifically).
edit: There actually is such a plugin: https://wordpress.org/plugins/static-html-output-plugin/
I just tested it out on a brand new WP installation and it seems to work alright, but a few things seem not to work.
A:
Unfortunately, and simply you can't do this as WordPress is a WebApp, that is, requires a database. Sorry to be the bringer of bad news.
If you are considering an alternative, consider the following static site generators which can be hosted from GitHub Pages:
Cryogen (Clojure)
Jekyll (Ruby)
A:
You can migrate fromwordpress to jekyll static site generator, the one powering github pages.
You will find migration documentation on the jekyll site.
A:
No, for that you would need:
static site generator (like Hugo)
following a process similar to Andy's "Simple Workflow Deploy to Github Pages using Git".
It might not address your wordpress aspect of the question, but can help other wanting to publish static pages on GitHub.
(And yes, you can migrate from wordpress to Hugo, plus there is an pending request)
Go to Github, create a new repository with this convention: .github.io.
For clarity sake, my repo would be andy4thehuynh.github.io.
Also, create a local instance of a hugo repo.
Cd into an empty directory on your local machine and execute hugo new site ./.
Initialize a git repo with git init and add your remote git remote add origin [email protected]:<your_handle>/<your_handle>.github.io.git.
Cool, we have a fresh blog repo.
Let’s add a test post; execute hugo new post/test.md and echo 'Your live on Github Pages' >> ./content/post/test.md.
Set the draft flag to true to make sure your post renders.
Tell Hugo to build your site by running hugo.
Your public directory should be populated with a freshly generated site. Awesome!
Here comes the sauce; perform a echo 'public' >> .gitignore. Now, Git will have no idea of your public directory (your compiled public content users will view in a browser). You’ll see why quickly.
Switch out of the master branch with git checkout -b source. We do this since GH pages doesn’t care about our source code (aka our source branch). It only cares about the public content.
Add and commit your source changes. Do a git add -A and git commit -m 'Initial Commit'. Push your changes with git push origin source.
Lastly, cd into your public folder. Notice Git is not keeping track of changes here. This was for intended purposes. Do a git init, git add -A and git commit -m 'Initial commit'. Push your changes with git push origin master.
Open a browser to your repo named .github.io and switch between your source and master branches.
All your compiled content should be in your master branch.
GH pages will see that and render it at <your_handle>.github.io.
You’ll write your drafts in your source branch. Compile it with the hugo command. When your happy with your compiled changes, push your public folder and become a rock star.
A:
Yes you can and it's extremely easy. Benefits:
You can use as always the wp-adnin features
Sites will be host by GitHub pages (extremely fast)
As the site is static you will not have security issues unless you do things badly.
Steps:
Create a complete wordpress site on subdomain, example: static.mydomain.com
Install Simply Static Pro version that allows you to easily generate a static site and automatically upload it to GitHub (just follow documentation)
Enjoy your free hosted and extremely fast static site.
Bonus:
Use wp-rocket optimizations. When the static site is created it will benefit from those.
As there is no databases, plugin forms ninja Forms will not work so use the ones accepted by the simply static plugin or third party like Typeform or google forms.
For security purpose configure your server to only accept you IP connection to static.mydomain.com this will increase your security and avoid google from indexing this subdomain.
| Can I host my wordpress blog on github pages as a static webpage | I would like to make my WordPress blog installed on Localhost to push into GitHub and run that on GitHub as a static page. Can I do it, and if yes please give me a detailed answer with the steps and problems involved?
I don't care if my page is static, but will I be able to host it on GitHub pages?
| [
"This website gives a good answer on how to do this: https://www.hywel.me/static/site/wordpress/2016/07/17/fast-free-static-website-with-wordpress-and-github-pages.html\nIn short:\n\nSet-up GitHub pages.\nInstall Simply static plugin into WordPress.\nPush the export from the plug-in back to your git repository and you are done!\n\n",
"You can't. You would use WordPress if you want a dynamic page - that is the whole point of using it. You could of course grab the html generated by WordPress and push that to your GitHub, but that I think that would be a lot of manual work.\nYou could try a static page generator, i.e. https://github.com/jekyll/jekyll\n",
"If you absolutely can't switch from wordpress, but absolutely need to host on github pages, then your only option is probably to look into some wordpress plugin that will take your entire site and spit out a static website (sort of like jekyll, but for wordpress specifically).\nedit: There actually is such a plugin: https://wordpress.org/plugins/static-html-output-plugin/\nI just tested it out on a brand new WP installation and it seems to work alright, but a few things seem not to work.\n",
"Unfortunately, and simply you can't do this as WordPress is a WebApp, that is, requires a database. Sorry to be the bringer of bad news. \nIf you are considering an alternative, consider the following static site generators which can be hosted from GitHub Pages:\n\nCryogen (Clojure)\nJekyll (Ruby)\n\n",
"You can migrate fromwordpress to jekyll static site generator, the one powering github pages.\nYou will find migration documentation on the jekyll site.\n",
"No, for that you would need:\n\nstatic site generator (like Hugo)\nfollowing a process similar to Andy's \"Simple Workflow Deploy to Github Pages using Git\".\nIt might not address your wordpress aspect of the question, but can help other wanting to publish static pages on GitHub.\n(And yes, you can migrate from wordpress to Hugo, plus there is an pending request)\n\n\n\nGo to Github, create a new repository with this convention: .github.io.\n For clarity sake, my repo would be andy4thehuynh.github.io. \nAlso, create a local instance of a hugo repo.\n Cd into an empty directory on your local machine and execute hugo new site ./.\n Initialize a git repo with git init and add your remote git remote add origin [email protected]:<your_handle>/<your_handle>.github.io.git.\n Cool, we have a fresh blog repo.\nLet’s add a test post; execute hugo new post/test.md and echo 'Your live on Github Pages' >> ./content/post/test.md.\n Set the draft flag to true to make sure your post renders.\nTell Hugo to build your site by running hugo.\n Your public directory should be populated with a freshly generated site. Awesome!\nHere comes the sauce; perform a echo 'public' >> .gitignore. Now, Git will have no idea of your public directory (your compiled public content users will view in a browser). You’ll see why quickly.\nSwitch out of the master branch with git checkout -b source. We do this since GH pages doesn’t care about our source code (aka our source branch). It only cares about the public content.\nAdd and commit your source changes. Do a git add -A and git commit -m 'Initial Commit'. Push your changes with git push origin source.\nLastly, cd into your public folder. Notice Git is not keeping track of changes here. This was for intended purposes. Do a git init, git add -A and git commit -m 'Initial commit'. Push your changes with git push origin master.\n\nOpen a browser to your repo named .github.io and switch between your source and master branches.\n All your compiled content should be in your master branch.\n GH pages will see that and render it at <your_handle>.github.io.\n You’ll write your drafts in your source branch. Compile it with the hugo command. When your happy with your compiled changes, push your public folder and become a rock star. \n\n",
"Yes you can and it's extremely easy. Benefits:\n\nYou can use as always the wp-adnin features\nSites will be host by GitHub pages (extremely fast)\nAs the site is static you will not have security issues unless you do things badly.\n\nSteps:\n\nCreate a complete wordpress site on subdomain, example: static.mydomain.com\nInstall Simply Static Pro version that allows you to easily generate a static site and automatically upload it to GitHub (just follow documentation)\nEnjoy your free hosted and extremely fast static site.\n\nBonus:\n\nUse wp-rocket optimizations. When the static site is created it will benefit from those.\n\nAs there is no databases, plugin forms ninja Forms will not work so use the ones accepted by the simply static plugin or third party like Typeform or google forms.\n\nFor security purpose configure your server to only accept you IP connection to static.mydomain.com this will increase your security and avoid google from indexing this subdomain.\n\n\n"
] | [
26,
13,
7,
4,
4,
3,
0
] | [] | [] | [
"github",
"github_pages",
"self_hosting",
"web_hosting",
"wordpress"
] | stackoverflow_0032902472_github_github_pages_self_hosting_web_hosting_wordpress.txt |
Q:
How to have onTap gestures on Map and MapAnnotation both, without the two interferring with each other?
I have a SwiftUI Map with MapAnnotations.
I would like to have an onTap gesture on the Map, so it deselects the selected annotations, and dissmisses a bottom sheet, etc. Also would like to have an onTap gesture on the annotation item (or just having a button as annotation view with an action there), which selects the annotation and do stuff.
The problem: whenever I tap the annotation, the map's ontap gesture is triggered too. (When I tap on the map, it only triggers the map's action, so no problems there.)
Here's some sample code:
import SwiftUI
import MapKit
import CoreLocation
struct ContentView: View {
@State var region: MKCoordinateRegion =
MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 47.333,
longitude: 19.222),
span: MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002))
var body: some View {
Map(coordinateRegion: $region,
annotationItems: AnnotationItem.sample) { annotation in
MapAnnotation(coordinate: annotation.location.coordinate) {
VStack {
Circle()
.foregroundColor(.red)
.frame(width: 50)
Text(annotation.name)
}
.onTapGesture {
print(">> tapped child")
}
}
}
.onTapGesture {
print(">> tapped parent")
}
}
}
I tap on the annotation, then:
>> tapped parent
>> tapped child
I tap on the map, then:
>> tapped parent
EDIT:
I have tried and didn't work:
make parent action depend on a boolean, which is set to prevent map's action when child is tapped. See in comment: I can only delay the parents action with this, cannot cancel it.
add on custom tap gesture for each, and set .exclusivelyBefore(:) modifier on one of them
A:
This seems to me to be a bug, since the default behavior is that only one gesture recognizer fires at a time, see here.
A similar problem occurs in a ScrollView, but there exists a property .delaysContentTouches to solve it, see here. This does unfortunately not exist for a View.
A possible workaround is to delay the parent tap action until it is ensured that no child tap action follows. You could add to your ContentView a @State var childTapTriggered = false and set this var to true if it triggered. Then you could use as parent tap gesture closure something like
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
if !childTapTriggered {
// do parent action
}
}
| How to have onTap gestures on Map and MapAnnotation both, without the two interferring with each other? | I have a SwiftUI Map with MapAnnotations.
I would like to have an onTap gesture on the Map, so it deselects the selected annotations, and dissmisses a bottom sheet, etc. Also would like to have an onTap gesture on the annotation item (or just having a button as annotation view with an action there), which selects the annotation and do stuff.
The problem: whenever I tap the annotation, the map's ontap gesture is triggered too. (When I tap on the map, it only triggers the map's action, so no problems there.)
Here's some sample code:
import SwiftUI
import MapKit
import CoreLocation
struct ContentView: View {
@State var region: MKCoordinateRegion =
MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 47.333,
longitude: 19.222),
span: MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002))
var body: some View {
Map(coordinateRegion: $region,
annotationItems: AnnotationItem.sample) { annotation in
MapAnnotation(coordinate: annotation.location.coordinate) {
VStack {
Circle()
.foregroundColor(.red)
.frame(width: 50)
Text(annotation.name)
}
.onTapGesture {
print(">> tapped child")
}
}
}
.onTapGesture {
print(">> tapped parent")
}
}
}
I tap on the annotation, then:
>> tapped parent
>> tapped child
I tap on the map, then:
>> tapped parent
EDIT:
I have tried and didn't work:
make parent action depend on a boolean, which is set to prevent map's action when child is tapped. See in comment: I can only delay the parents action with this, cannot cancel it.
add on custom tap gesture for each, and set .exclusivelyBefore(:) modifier on one of them
| [
"This seems to me to be a bug, since the default behavior is that only one gesture recognizer fires at a time, see here.\nA similar problem occurs in a ScrollView, but there exists a property .delaysContentTouches to solve it, see here. This does unfortunately not exist for a View.\nA possible workaround is to delay the parent tap action until it is ensured that no child tap action follows. You could add to your ContentView a @State var childTapTriggered = false and set this var to true if it triggered. Then you could use as parent tap gesture closure something like\nDispatchQueue.main.asyncAfter(deadline: .now() + delay) {\n if !childTapTriggered {\n // do parent action\n }\n}\n\n"
] | [
0
] | [] | [] | [
"ios",
"mapkit",
"swift",
"swiftui",
"swiftui_ontapgesture"
] | stackoverflow_0074675989_ios_mapkit_swift_swiftui_swiftui_ontapgesture.txt |
Q:
Android Automotive Unable to create media player and setDataSource failed
I have been trying to use a simple audio audio player for android auto and just stream a audio from a link. But when the function is called the media player cant set the data source from url. and it will return the following error.
Code :
class HelloWorldScreen(carContext: CarContext) : Screen(carContext) {
override fun onGetTemplate(): Template {
val mGridIcon = IconCompat.createWithResource(
carContext, R.drawable.mainscreenlogo
)
val gridItemCar = GridItem.Builder()
.setTitle("Car Info")
.setImage(
CarIcon.Builder(mGridIcon).build(),
GridItem.IMAGE_TYPE_LARGE
).setOnClickListener(this::player).build()
val gridList = ItemList.Builder()
.addItem(gridItemCar).build()
return GridTemplate.Builder()
.setSingleList(gridList)
.build()
}
private fun player(){
var mediaPlayer = MediaPlayer()
var audioUrl = "https://url"
var customUri: Uri = Uri.parse(audioUrl)
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)
mediaPlayer.setAudioAttributes(
AudioAttributes. Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build()
)
if(!mediaPlayer.isPlaying){
try {
mediaPlayer.setDataSource(audioUrl)
mediaPlayer.prepareAsync()
mediaPlayer.setOnPreparedListener {
mediaPlayer.start()
}
} catch (e: Exception) {
e.printStackTrace()
}
Log.d("Player" , "Audio started playing..") }
else {
if (mediaPlayer.isPlaying) {
mediaPlayer.stop()
mediaPlayer.reset()
// mediaPlayer.release()
Log.d("Player" , "Player Released")
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)
} else {
Log.d("Player" , "Audio not played.. Check Error")
}
}
}}
I used the player function to invoke the player .
The Error:
E/MediaPlayerNative: Unable to create media player W/System.err: java.io.IOException: setDataSource failed.: status=0x80000000
W/System.err: at
android.media.MediaPlayer.nativeSetDataSource(Native Method)
W/System.err: at
android.media.MediaPlayer.setDataSource(MediaPlayer.java:1173)
W/System.err: at
android.media.MediaPlayer.setDataSource(MediaPlayer.java:1160)
W/System.err: at
android.media.MediaPlayer.setDataSource(MediaPlayer.java:1125)
W/System.err: at
com.auslanka.app.common.HelloWorldService.player(HelloWorldService.kt:42)
W/System.err: at
com.auslanka.app.common.HelloWorldService.onCreateSession(HelloWorldService.kt:14)
W/System.err: at
androidx.car.app.CarAppService.onCreateSession(CarAppService.java:283)
W/System.err: at
androidx.car.app.CarAppBinder.lambda$onAppCreate$0$androidx-car-app-CarAppBinder(CarAppBinder.java:115)
W/System.err: at
androidx.car.app.CarAppBinder$$ExternalSyntheticLambda6.dispatch(Unknown
Source:8) W/System.err: at
androidx.car.app.utils.RemoteUtils.lambda$dispatchCallFromHost$0(RemoteUtils.java:149)
W/System.err: at
androidx.car.app.utils.RemoteUtils$$ExternalSyntheticLambda2.run(Unknown
Source:6) W/System.err: at
android.os.Handler.handleCallback(Handler.java:883) W/System.err:
at android.os.Handler.dispatchMessage(Handler.java:100) W/System.err:
at android.os.Looper.loop(Looper.java:214) W/System.err: at
android.app.ActivityThread.main(ActivityThread.java:7356)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
W/System.err: at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Am I doing this wrong, if so a small code guide of how to play audio in android auto will be much appreciated. Thank you.
A:
In my opinion:
There could be several reasons why the media player is unable to create and set the data source from the URL. First, check that you have the correct URL. Make sure it is not a broken or invalid URL. Also, make sure that the URL has been whitelisted in the Android Auto app settings, if applicable. Additionally, make sure your app has the required permissions to access the URL. Finally, make sure the audio format is supported by Android Auto. If all of the above fail, then it could be an issue with the Android Auto app itself, in which case you should contact the developer for assistance.
See this example maybe can help you out:
// Create a MediaSource instance
MediaSource source = new MediaSource.Factory(dataSourceFactory)
.createMediaSource(uri);
// Create an AudioSource instance
AudioSource audioSource = new AudioSource.Factory(dataSourceFactory)
.setTag(TAG)
.createAudioSource();
// Create a media player instance
SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(context);
// Prepare the player with the MediaSource
player.prepare(source);
// Set the audio source
player.setAudioSource(audioSource);
// Set the playback parameters
player.setPlaybackParameters(new PlaybackParameters(speed, pitch));
// Start playback
player.playWhenReady(true);
A:
Technically this happened due to my own mistake of not adding the network the permissions in manifest. It turns out both Mediaplayer and HLS link I was using supported in Automotive Emulator just fine. If anyone out there see this question, make sure you add the network permissions properly. Thanks.
<uses-permission android:name="android.permission.INTERNET"/>
and
<application....
android:usesCleartextTraffic="true" .../>
| Android Automotive Unable to create media player and setDataSource failed | I have been trying to use a simple audio audio player for android auto and just stream a audio from a link. But when the function is called the media player cant set the data source from url. and it will return the following error.
Code :
class HelloWorldScreen(carContext: CarContext) : Screen(carContext) {
override fun onGetTemplate(): Template {
val mGridIcon = IconCompat.createWithResource(
carContext, R.drawable.mainscreenlogo
)
val gridItemCar = GridItem.Builder()
.setTitle("Car Info")
.setImage(
CarIcon.Builder(mGridIcon).build(),
GridItem.IMAGE_TYPE_LARGE
).setOnClickListener(this::player).build()
val gridList = ItemList.Builder()
.addItem(gridItemCar).build()
return GridTemplate.Builder()
.setSingleList(gridList)
.build()
}
private fun player(){
var mediaPlayer = MediaPlayer()
var audioUrl = "https://url"
var customUri: Uri = Uri.parse(audioUrl)
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)
mediaPlayer.setAudioAttributes(
AudioAttributes. Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build()
)
if(!mediaPlayer.isPlaying){
try {
mediaPlayer.setDataSource(audioUrl)
mediaPlayer.prepareAsync()
mediaPlayer.setOnPreparedListener {
mediaPlayer.start()
}
} catch (e: Exception) {
e.printStackTrace()
}
Log.d("Player" , "Audio started playing..") }
else {
if (mediaPlayer.isPlaying) {
mediaPlayer.stop()
mediaPlayer.reset()
// mediaPlayer.release()
Log.d("Player" , "Player Released")
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)
} else {
Log.d("Player" , "Audio not played.. Check Error")
}
}
}}
I used the player function to invoke the player .
The Error:
E/MediaPlayerNative: Unable to create media player W/System.err: java.io.IOException: setDataSource failed.: status=0x80000000
W/System.err: at
android.media.MediaPlayer.nativeSetDataSource(Native Method)
W/System.err: at
android.media.MediaPlayer.setDataSource(MediaPlayer.java:1173)
W/System.err: at
android.media.MediaPlayer.setDataSource(MediaPlayer.java:1160)
W/System.err: at
android.media.MediaPlayer.setDataSource(MediaPlayer.java:1125)
W/System.err: at
com.auslanka.app.common.HelloWorldService.player(HelloWorldService.kt:42)
W/System.err: at
com.auslanka.app.common.HelloWorldService.onCreateSession(HelloWorldService.kt:14)
W/System.err: at
androidx.car.app.CarAppService.onCreateSession(CarAppService.java:283)
W/System.err: at
androidx.car.app.CarAppBinder.lambda$onAppCreate$0$androidx-car-app-CarAppBinder(CarAppBinder.java:115)
W/System.err: at
androidx.car.app.CarAppBinder$$ExternalSyntheticLambda6.dispatch(Unknown
Source:8) W/System.err: at
androidx.car.app.utils.RemoteUtils.lambda$dispatchCallFromHost$0(RemoteUtils.java:149)
W/System.err: at
androidx.car.app.utils.RemoteUtils$$ExternalSyntheticLambda2.run(Unknown
Source:6) W/System.err: at
android.os.Handler.handleCallback(Handler.java:883) W/System.err:
at android.os.Handler.dispatchMessage(Handler.java:100) W/System.err:
at android.os.Looper.loop(Looper.java:214) W/System.err: at
android.app.ActivityThread.main(ActivityThread.java:7356)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
W/System.err: at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Am I doing this wrong, if so a small code guide of how to play audio in android auto will be much appreciated. Thank you.
| [
"In my opinion:\nThere could be several reasons why the media player is unable to create and set the data source from the URL. First, check that you have the correct URL. Make sure it is not a broken or invalid URL. Also, make sure that the URL has been whitelisted in the Android Auto app settings, if applicable. Additionally, make sure your app has the required permissions to access the URL. Finally, make sure the audio format is supported by Android Auto. If all of the above fail, then it could be an issue with the Android Auto app itself, in which case you should contact the developer for assistance.\nSee this example maybe can help you out:\n// Create a MediaSource instance\nMediaSource source = new MediaSource.Factory(dataSourceFactory)\n .createMediaSource(uri);\n\n// Create an AudioSource instance\nAudioSource audioSource = new AudioSource.Factory(dataSourceFactory)\n .setTag(TAG)\n .createAudioSource();\n\n// Create a media player instance\nSimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(context);\n\n// Prepare the player with the MediaSource\nplayer.prepare(source);\n\n// Set the audio source\nplayer.setAudioSource(audioSource);\n\n// Set the playback parameters\nplayer.setPlaybackParameters(new PlaybackParameters(speed, pitch));\n\n// Start playback\nplayer.playWhenReady(true);\n\n",
"Technically this happened due to my own mistake of not adding the network the permissions in manifest. It turns out both Mediaplayer and HLS link I was using supported in Automotive Emulator just fine. If anyone out there see this question, make sure you add the network permissions properly. Thanks.\n<uses-permission android:name=\"android.permission.INTERNET\"/>\n\nand\n<application....\n\nandroid:usesCleartextTraffic=\"true\" .../>\n\n"
] | [
1,
0
] | [] | [] | [
"android",
"android_auto",
"android_automotive",
"kotlin"
] | stackoverflow_0074671750_android_android_auto_android_automotive_kotlin.txt |
Q:
gcc preprocessor variables to string literals
I know there a bazillion question like this, but I couldn't find a good answer.
I'm compiling a source with preprocessor tokens defined in CFLAGS:
-D X=string1 -D Y=string2
I'm trying to create a string literal in my header file that combines these two values and use it in my sources like:
printf("%s", COMBINED);
But this doesn't work:
#define _COMBINED(x, y) x ## y
#define COMBINED _COMBINED(X, Y)
Thanks
A:
You did not show an example how you call the compiler, so I made some experiments. Since commas (and other non-alphanumerical characters) will get in the way, it boiled down to the need to pass quotation marks as delimiters of the replacement text of the macros.
So I think your real issue is how to pass the strings in an equivalent way to:
#define X "hello, "
#define Y "world!"
Note: Here extra difficult because of comma and exclamation mark.
If the macro replacement text is passed including the quotation marks, the C source gets simple. In C, you concatenate string without any intermediate operator. "abc" "def" is the same as "abcdef".
#include <stdio.h>
#define COMBINED X Y
int main(void) {
printf("%s\n", COMBINED);
}
Depending on your real use case, you could even simplify this to:
#include <stdio.h>
int main(void) {
printf("%s\n", X Y);
}
In a Bash you need to escape the command line arguments like this, for example:
gcc -Wall -pedantic -D 'X="hello, "' -D 'Y="world!"' combine.c -s -O3 -o combine
For Windows' CMD I cannot present an example, since today I have no access to a Windows machine.
A:
To pass a string-ized token to a concatenating macro, you need a level of indirection. That means you pass it to a different macro.
#define COMBINED(a, b) (a##b)
#define COMBINE(a, b) COMBINED(a, b)
Then you pass off the params in COMBINE, in your case, X and Y
int main (void) // best practice is to void-erize non-param-ed functions
{
printf("%s\n", COMBINE(X,Y));
}
If you really want to do it "directly", you can do it like this:
#define DEFAULT_COMBINE COMBINE(X,Y)
And call:
printf("%s\n", DEFAULT_COMBINE);
Now, let's end with a caveat, as this is also about "best practice" so it's quite important even though it might not seem that way to you, it is, trust me on this one. Never ever, and i mean NEVER EVER start off your own preprocessor defines or constants with an underscore. Never, under any circumstances. Even if your brother works at Microsoft or worked on the Linux kernel.
In the standard and best-practice C and C++ world, the _COMBINED macro is illegal. No, not invalid, it just means you shouldn't name it like that. The short version is that constants, intrisincs and macros startign with an underscore are compiler or internal only. It's a "marker" to know that it's not something someone set.
| gcc preprocessor variables to string literals | I know there a bazillion question like this, but I couldn't find a good answer.
I'm compiling a source with preprocessor tokens defined in CFLAGS:
-D X=string1 -D Y=string2
I'm trying to create a string literal in my header file that combines these two values and use it in my sources like:
printf("%s", COMBINED);
But this doesn't work:
#define _COMBINED(x, y) x ## y
#define COMBINED _COMBINED(X, Y)
Thanks
| [
"You did not show an example how you call the compiler, so I made some experiments. Since commas (and other non-alphanumerical characters) will get in the way, it boiled down to the need to pass quotation marks as delimiters of the replacement text of the macros.\nSo I think your real issue is how to pass the strings in an equivalent way to:\n#define X \"hello, \"\n#define Y \"world!\"\n\nNote: Here extra difficult because of comma and exclamation mark.\nIf the macro replacement text is passed including the quotation marks, the C source gets simple. In C, you concatenate string without any intermediate operator. \"abc\" \"def\" is the same as \"abcdef\".\n#include <stdio.h>\n\n#define COMBINED X Y\n\nint main(void) {\n printf(\"%s\\n\", COMBINED);\n}\n\nDepending on your real use case, you could even simplify this to:\n#include <stdio.h>\n\nint main(void) {\n printf(\"%s\\n\", X Y);\n}\n\nIn a Bash you need to escape the command line arguments like this, for example:\ngcc -Wall -pedantic -D 'X=\"hello, \"' -D 'Y=\"world!\"' combine.c -s -O3 -o combine\n\nFor Windows' CMD I cannot present an example, since today I have no access to a Windows machine.\n",
"To pass a string-ized token to a concatenating macro, you need a level of indirection. That means you pass it to a different macro.\n#define COMBINED(a, b) (a##b)\n#define COMBINE(a, b) COMBINED(a, b)\n\nThen you pass off the params in COMBINE, in your case, X and Y\nint main (void) // best practice is to void-erize non-param-ed functions\n{\n printf(\"%s\\n\", COMBINE(X,Y));\n}\n\nIf you really want to do it \"directly\", you can do it like this:\n#define DEFAULT_COMBINE COMBINE(X,Y)\n\nAnd call:\nprintf(\"%s\\n\", DEFAULT_COMBINE);\n\nNow, let's end with a caveat, as this is also about \"best practice\" so it's quite important even though it might not seem that way to you, it is, trust me on this one. Never ever, and i mean NEVER EVER start off your own preprocessor defines or constants with an underscore. Never, under any circumstances. Even if your brother works at Microsoft or worked on the Linux kernel.\nIn the standard and best-practice C and C++ world, the _COMBINED macro is illegal. No, not invalid, it just means you shouldn't name it like that. The short version is that constants, intrisincs and macros startign with an underscore are compiler or internal only. It's a \"marker\" to know that it's not something someone set.\n"
] | [
0,
0
] | [] | [] | [
"c",
"c_preprocessor"
] | stackoverflow_0074675245_c_c_preprocessor.txt |
Q:
MikroORM - validate the current SQL db schema as with hbm2ddl.auto=validate
Is it possible in MikroORM to validate the current SQL database schema (Postgres)?
I would like run this validation on application start as Hibernate does with hbm2ddl.auto=validate
A:
You can use schema generator programatically, this way you can easily check if the schema is up to date after the init:
const orm = await MikroORM.init();
const diff = await orm.schema.getUpdateSchemaSQL();
if (diff) {
throw new Error('schema is out of sync');
}
I will consider adding something similar to v6, at least some syntax sugar in the schema generator.
| MikroORM - validate the current SQL db schema as with hbm2ddl.auto=validate | Is it possible in MikroORM to validate the current SQL database schema (Postgres)?
I would like run this validation on application start as Hibernate does with hbm2ddl.auto=validate
| [
"You can use schema generator programatically, this way you can easily check if the schema is up to date after the init:\nconst orm = await MikroORM.init();\nconst diff = await orm.schema.getUpdateSchemaSQL();\n\nif (diff) {\n throw new Error('schema is out of sync');\n}\n\nI will consider adding something similar to v6, at least some syntax sugar in the schema generator.\n"
] | [
0
] | [] | [] | [
"mikro_orm",
"nestjs",
"node.js",
"orm"
] | stackoverflow_0074677382_mikro_orm_nestjs_node.js_orm.txt |
Q:
I have a problem with my python Minecraft copy
I was working with "Ursina Engine"
My project is to make a copy of Minecraft, then I found out a problem that every time I run the program
and when I want to right-click to place a block, nothing happens.
Thanks to someone who can help me find the issue and tell me how to fix it * Here is my Code:*
from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController
class Vovel(Button):
def __init__(self, position = (0,0,0)):
super().__init__(
parent=scene,
position=position,
model='cube',
origin_y = 0.5,
texture= 'white_cube',
color= color.white,
highlight_color = color.lime,
)
def Input(self, key):
if self.hovered:
if key == 'left mouse down':
vovel = Vovel(position= self.position + mouse.normal)
if key == 'right mouse down':
destroy(self)
app = Ursina()
for z in range(8):
for x in range(8):
vovel = Vovel(position= (x,0,z))
player = FirstPersonController()
app.run()
End.
A:
The name of the input function is wrong. Input should be input
A:
The input function should be input and not Input, rest of the code is absolutely correct. So, your code should be:
from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController
class Vovel(Button):
def __init__(self, position=(0, 0, 0)):
super().__init__(
parent=scene,
position=position,
model='cube',
origin_y=0.5,
texture='white_cube',
color=color.white,
highlight_color=color.lime,
)
def input(self, key):
if self.hovered:
if key == 'left mouse down':
vovel = Vovel(position=self.position + mouse.normal)
if key == 'right mouse down':
destroy(self)
app = Ursina()
for z in range(8):
for x in range(8):
vovel = Vovel(position=(x, 0, z))
player = FirstPersonController()
app.run()
This code works, you can place a block with left click and remove a block with right click!
A:
You only have to replace left mouse down with right mouse down and right mouse down with left mouse down, but I'm using this code for "Minecraft":
`
from ursina.prefabs.first_person_controller import *
app=Ursina()
FirstPersonController()
Sky()
def voxel(position:Vec3):
Voxel=Entity(model="assets/block.obj", position=position, collider="box", texture="assets/sand_block.jpg",origin_y=0.5,scale=0.5,on_click=lambda:destroy(Voxel))
for x in range(20):
for z in range(20):
voxel(position=Vec3(x,0,z))
def input(key):
if key=="right mouse down":
vox=voxel(position=Vec3(round(mouse.world_point.x),ceil(mouse.world_point.y),round(mouse.world_point.z)))
app.run()`
| I have a problem with my python Minecraft copy | I was working with "Ursina Engine"
My project is to make a copy of Minecraft, then I found out a problem that every time I run the program
and when I want to right-click to place a block, nothing happens.
Thanks to someone who can help me find the issue and tell me how to fix it * Here is my Code:*
from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController
class Vovel(Button):
def __init__(self, position = (0,0,0)):
super().__init__(
parent=scene,
position=position,
model='cube',
origin_y = 0.5,
texture= 'white_cube',
color= color.white,
highlight_color = color.lime,
)
def Input(self, key):
if self.hovered:
if key == 'left mouse down':
vovel = Vovel(position= self.position + mouse.normal)
if key == 'right mouse down':
destroy(self)
app = Ursina()
for z in range(8):
for x in range(8):
vovel = Vovel(position= (x,0,z))
player = FirstPersonController()
app.run()
End.
| [
"The name of the input function is wrong. Input should be input\n",
"The input function should be input and not Input, rest of the code is absolutely correct. So, your code should be:\nfrom ursina import *\nfrom ursina.prefabs.first_person_controller import FirstPersonController\n\n\nclass Vovel(Button):\ndef __init__(self, position=(0, 0, 0)):\n super().__init__(\n parent=scene,\n position=position,\n model='cube',\n origin_y=0.5,\n texture='white_cube',\n color=color.white,\n highlight_color=color.lime,\n )\n\ndef input(self, key):\n if self.hovered:\n if key == 'left mouse down':\n vovel = Vovel(position=self.position + mouse.normal)\n if key == 'right mouse down':\n destroy(self)\n\n\napp = Ursina()\nfor z in range(8):\nfor x in range(8):\n vovel = Vovel(position=(x, 0, z))\nplayer = FirstPersonController()\napp.run()\n\nThis code works, you can place a block with left click and remove a block with right click!\n",
"You only have to replace left mouse down with right mouse down and right mouse down with left mouse down, but I'm using this code for \"Minecraft\":\n`\nfrom ursina.prefabs.first_person_controller import *\napp=Ursina()\nFirstPersonController()\nSky()\ndef voxel(position:Vec3):\n Voxel=Entity(model=\"assets/block.obj\", position=position, collider=\"box\", texture=\"assets/sand_block.jpg\",origin_y=0.5,scale=0.5,on_click=lambda:destroy(Voxel))\nfor x in range(20):\n for z in range(20):\n voxel(position=Vec3(x,0,z))\ndef input(key):\n if key==\"right mouse down\":\n vox=voxel(position=Vec3(round(mouse.world_point.x),ceil(mouse.world_point.y),round(mouse.world_point.z)))\napp.run()`\n\n"
] | [
6,
4,
0
] | [
"Ah now I'm understanding your problem, you have to change input to Input, the rest is fine.\n"
] | [
-1
] | [
"python",
"ursina",
"user_interface"
] | stackoverflow_0069450738_python_ursina_user_interface.txt |
Q:
console gives a string isn't a function error
I'm creating a quiz and console shows a problem with split, that it's not a function, but it worked before. I've tried using toString method but it doesn't help, console says instead that can't read properties of null. If someone could help me, it would be appreciated.
let correctAnswer = document.getElementById("correct-answers");
document.querySelector(".check").onclick = function () {
/* Hide unneeded sections and showing scores */
quiz.classList.add("hidden");
correctAnswer.classList.remove("hidden");
/*Showing all previous scores */
const lastScore = localStorage.getItem("latestScore") || [];
const scoreDetail = lastScore.split(',');
scoreDetail.push(score);
localStorage.setItem("latestScore", scoreDetail);
let userScoreTemplate = `<h2>This Round's Score: ${score}</h2>`;
scoreDetail.map((items, index) => {
userScoreTemplate += `<h3>Score ${index}: ${items}</h3>`
});
let userScoreBoard = document.getElementById("user-score");
userScoreBoard.innerHTML = userScoreTemplate;
A:
localStorage.getItem() will return a string.
You need adjust your code accordingly to default to a string in case the item is not defined:
const lastScore = localStorage.getItem("latestScore") || "";
A:
In your code lastScore is an array, not a string, so the split method will not work on it. It works only on strings.You can use JSON.Parse like that. This will convert array data into javascript array.
const scoreDetail = JSON.parse(lastScore) || [];
scoreDetail.push(score);
And after that convert the array into a JSON string :
localStorage.setItem("latestScore", JSON.stringify(scoreDetail));
A:
is latest score is a obj/array/string or what?
If it's an array/object then wrap localStorage.getItem in JSON.parse() so js can convert array data into js array
| console gives a string isn't a function error | I'm creating a quiz and console shows a problem with split, that it's not a function, but it worked before. I've tried using toString method but it doesn't help, console says instead that can't read properties of null. If someone could help me, it would be appreciated.
let correctAnswer = document.getElementById("correct-answers");
document.querySelector(".check").onclick = function () {
/* Hide unneeded sections and showing scores */
quiz.classList.add("hidden");
correctAnswer.classList.remove("hidden");
/*Showing all previous scores */
const lastScore = localStorage.getItem("latestScore") || [];
const scoreDetail = lastScore.split(',');
scoreDetail.push(score);
localStorage.setItem("latestScore", scoreDetail);
let userScoreTemplate = `<h2>This Round's Score: ${score}</h2>`;
scoreDetail.map((items, index) => {
userScoreTemplate += `<h3>Score ${index}: ${items}</h3>`
});
let userScoreBoard = document.getElementById("user-score");
userScoreBoard.innerHTML = userScoreTemplate;
| [
"localStorage.getItem() will return a string.\nYou need adjust your code accordingly to default to a string in case the item is not defined:\nconst lastScore = localStorage.getItem(\"latestScore\") || \"\";\n\n",
"In your code lastScore is an array, not a string, so the split method will not work on it. It works only on strings.You can use JSON.Parse like that. This will convert array data into javascript array.\n const scoreDetail = JSON.parse(lastScore) || [];\n\nscoreDetail.push(score);\n\nAnd after that convert the array into a JSON string :\n localStorage.setItem(\"latestScore\", JSON.stringify(scoreDetail));\n\n",
"is latest score is a obj/array/string or what?\nIf it's an array/object then wrap localStorage.getItem in JSON.parse() so js can convert array data into js array\n"
] | [
1,
0,
0
] | [] | [] | [
"arrays",
"javascript",
"split",
"string"
] | stackoverflow_0074675966_arrays_javascript_split_string.txt |
Q:
Does this warrant many-to-many relationship?
I'm creating a db for PC components inventory. I got component, component type, count (how many of it there is) and manufacturer.
My question is mainly about type. To explain, lets take hard drives as an example.
Component: Hard Drive
Type: SSD or SATA
Manufacturer: Samsung, HP, WD
The count will differ depending on the different combinations you can make from the previous information.
As I have many components (monitors, CPUs, HDs...etc.) and many types for each component, does that mean I have many to many relationship?
Also, each manufacturer manufactures different components and accordingly different types of these components. Does this mean I have many to many relationship between manufacturers and types?
Finally, I can't understand how I can have just ONE model for Type. Types of HD are different that types for CPUs or batteries! Should I split Type class into multiple classes for each component?
Thank you!
A:
Firstly, for relationship between Component and Type, I don't think it is many to many relationship. It suppose to be one to many relationship because one storage drive for example can only be SSD or HDD, but not both. The business logic here is
"One Type can be assigned to many Component, but every Component is only one Type."
Secondly, you do not need to make a relationship directly between Manufacturer and Type. Indeed Manufacturer and Type relationship is actually many to many, but we have a natural bridge Entity here which is you guess it; Component! One Manufacturer will be making many Component, but one Component is only been manufactured by only one Manufacturer. And the same apply for other side of entity Component relationship to the Type. One Component is only Type, but one Type can have many Component associated to it.
Lastly, you don't need to create different class of Type for data storaga or monitor or CPU or any other Component. Sharing a single Type class will do its job perfectly. This way you can dinamically add your Component and Type associated with it without the nees to manually add new classes.
| Does this warrant many-to-many relationship? | I'm creating a db for PC components inventory. I got component, component type, count (how many of it there is) and manufacturer.
My question is mainly about type. To explain, lets take hard drives as an example.
Component: Hard Drive
Type: SSD or SATA
Manufacturer: Samsung, HP, WD
The count will differ depending on the different combinations you can make from the previous information.
As I have many components (monitors, CPUs, HDs...etc.) and many types for each component, does that mean I have many to many relationship?
Also, each manufacturer manufactures different components and accordingly different types of these components. Does this mean I have many to many relationship between manufacturers and types?
Finally, I can't understand how I can have just ONE model for Type. Types of HD are different that types for CPUs or batteries! Should I split Type class into multiple classes for each component?
Thank you!
| [
"Firstly, for relationship between Component and Type, I don't think it is many to many relationship. It suppose to be one to many relationship because one storage drive for example can only be SSD or HDD, but not both. The business logic here is\n\"One Type can be assigned to many Component, but every Component is only one Type.\"\nSecondly, you do not need to make a relationship directly between Manufacturer and Type. Indeed Manufacturer and Type relationship is actually many to many, but we have a natural bridge Entity here which is you guess it; Component! One Manufacturer will be making many Component, but one Component is only been manufactured by only one Manufacturer. And the same apply for other side of entity Component relationship to the Type. One Component is only Type, but one Type can have many Component associated to it.\nLastly, you don't need to create different class of Type for data storaga or monitor or CPU or any other Component. Sharing a single Type class will do its job perfectly. This way you can dinamically add your Component and Type associated with it without the nees to manually add new classes.\n"
] | [
0
] | [] | [] | [
"database",
"entity_framework",
"entity_framework_core",
"sql"
] | stackoverflow_0074636989_database_entity_framework_entity_framework_core_sql.txt |
Q:
Slash commands don't disappearing (nextcord)
I'm developing a discord bot using nextcord.
When i'm registering slash command and deleting it later, it's also staying at discord command list.
What can I do to delete non-existent slash commands or sync actual bot's command list with discord?
P.S. All of my commands are in different cogs
I was waiting about 4 hours for registering and sync slash commands by discord but to no avail.
A:
You should try kicking your bot and then inviting it back to your server. If this doesn't work, regenerate your bot's token. This should sync it back with Discord, and the command should be gone.
A:
The solution is adding all servers in default_guild_ids variable
Use methods on_ready and on_guild_join
Example code:
class Bot(nextcord.ext.commands.Bot):
async def on_ready(self):
for guild in self.guilds:
self.default_guild_ids.append(guild.id)
async def on_guild_join(self, guild: nextcord.Guild):
self.default_guild_ids.append(guild.id)
| Slash commands don't disappearing (nextcord) | I'm developing a discord bot using nextcord.
When i'm registering slash command and deleting it later, it's also staying at discord command list.
What can I do to delete non-existent slash commands or sync actual bot's command list with discord?
P.S. All of my commands are in different cogs
I was waiting about 4 hours for registering and sync slash commands by discord but to no avail.
| [
"You should try kicking your bot and then inviting it back to your server. If this doesn't work, regenerate your bot's token. This should sync it back with Discord, and the command should be gone.\n",
"The solution is adding all servers in default_guild_ids variable\nUse methods on_ready and on_guild_join\nExample code:\nclass Bot(nextcord.ext.commands.Bot):\n async def on_ready(self):\n for guild in self.guilds:\n self.default_guild_ids.append(guild.id)\n\n async def on_guild_join(self, guild: nextcord.Guild):\n self.default_guild_ids.append(guild.id)\n\n"
] | [
0,
0
] | [] | [] | [
"discord",
"nextcord",
"python"
] | stackoverflow_0074582360_discord_nextcord_python.txt |
Q:
[Question]How i can show Cid (https) from web3 storage at website?
iam newbie and now it is my 1rst steps
iam using
Set address:
{file}
but i take local adress ! How i can take Cid adress.I can find it(Cid) in console but i cant show it at website !!!
thanks for all !!!
enter image description here
import React from 'react';
import { Web3Storage } from "web3.storage";
import { useState } from "react";
import "../css/App.css";
const apiToken =
"meow";
const client = new Web3Storage({ token: apiToken });
const RegBuilding = () => {
const [file, setFile] = useState("");
const handleUpload = async () => {
console.log(document.getElementById("input").files[0]);
var fileInput = document.getElementById("input");
const rootCid = await client.put(fileInput.files, {
name: "cat pics",
maxRetries: 3
});
console.log(rootCid);
const res = await client.get(rootCid);
const files = await res.files();
console.log(files);
const url = URL.createObjectURL(files[0]);
console.log(url);
setFile(url);
};
return (
<div className="App">
<header className="App-header">
<label htmlFor="blogs_name">Meow system</label>
Set address:
{file}
<div>
<label htmlFor="file">Choose file to upload</label>
<br></br>
<input type="file" id="input" name="file" multiple />
</div>
<div>
<button onClick={handleUpload}>Submit</button>
</div></header>
</div>
);
}
export default RegBuilding;
A:
import React from 'react';
import { Web3Storage } from "web3.storage";
import { useState } from "react";
import "../css/App.css";
const apiToken =
"meow";
const client = new Web3Storage({ token: apiToken });
const RegBuilding = () => {
const [file, setFile] = useState("");
const [cid, setCid] = useState(""); // added
const handleUpload = async () => {
console.log(document.getElementById("input").files[0]);
var fileInput = document.getElementById("input");
// added
const rootCid = await client.put(fileInput.files, {
name: "cat pics",
maxRetries: 3
});
setCid(rootCid); // added
const res = await client.get(rootCid);
const files = await res.files();
console.log(files);
const url = URL.createObjectURL(files[0]);
console.log(url);
setFile(url);
};
return (
<div className="App">
<header className="App-header">
<label htmlFor="blogs_name">Meow system</label>
Set address:
{/* added */}
{cid}
<div>
<label htmlFor="file">Choose file to upload</label>
<br></br>
<input type="file" id="input" name="file" multiple />
</div>
<div>
<button onClick={handleUpload}>Submit</button>
</div></header>
</div>
);
}
export default RegBuilding;
| [Question]How i can show Cid (https) from web3 storage at website? | iam newbie and now it is my 1rst steps
iam using
Set address:
{file}
but i take local adress ! How i can take Cid adress.I can find it(Cid) in console but i cant show it at website !!!
thanks for all !!!
enter image description here
import React from 'react';
import { Web3Storage } from "web3.storage";
import { useState } from "react";
import "../css/App.css";
const apiToken =
"meow";
const client = new Web3Storage({ token: apiToken });
const RegBuilding = () => {
const [file, setFile] = useState("");
const handleUpload = async () => {
console.log(document.getElementById("input").files[0]);
var fileInput = document.getElementById("input");
const rootCid = await client.put(fileInput.files, {
name: "cat pics",
maxRetries: 3
});
console.log(rootCid);
const res = await client.get(rootCid);
const files = await res.files();
console.log(files);
const url = URL.createObjectURL(files[0]);
console.log(url);
setFile(url);
};
return (
<div className="App">
<header className="App-header">
<label htmlFor="blogs_name">Meow system</label>
Set address:
{file}
<div>
<label htmlFor="file">Choose file to upload</label>
<br></br>
<input type="file" id="input" name="file" multiple />
</div>
<div>
<button onClick={handleUpload}>Submit</button>
</div></header>
</div>
);
}
export default RegBuilding;
| [
"import React from 'react';\nimport { Web3Storage } from \"web3.storage\";\nimport { useState } from \"react\";\nimport \"../css/App.css\";\n\n\nconst apiToken =\n \"meow\";\n\nconst client = new Web3Storage({ token: apiToken });\n\nconst RegBuilding = () => {\n const [file, setFile] = useState(\"\");\n const [cid, setCid] = useState(\"\"); // added\n const handleUpload = async () => {\n console.log(document.getElementById(\"input\").files[0]);\n var fileInput = document.getElementById(\"input\");\n\n // added\n const rootCid = await client.put(fileInput.files, {\n name: \"cat pics\",\n maxRetries: 3\n });\n setCid(rootCid); // added\n\n const res = await client.get(rootCid);\n const files = await res.files();\n console.log(files);\n const url = URL.createObjectURL(files[0]);\n console.log(url);\n setFile(url);\n };\n return (\n\n <div className=\"App\">\n <header className=\"App-header\">\n <label htmlFor=\"blogs_name\">Meow system</label>\n Set address:\n {/* added */}\n {cid}\n \n \n \n <div>\n <label htmlFor=\"file\">Choose file to upload</label>\n <br></br>\n <input type=\"file\" id=\"input\" name=\"file\" multiple />\n \n </div>\n <div>\n <button onClick={handleUpload}>Submit</button>\n\n </div></header>\n </div>\n );\n }\nexport default RegBuilding;\n\n"
] | [
0
] | [] | [] | [
"react_native",
"reactjs"
] | stackoverflow_0074677087_react_native_reactjs.txt |
Q:
why 3.0.1.8 TDengine database's query performance is far better 3.0.1.4
this SQL:
select * from meters limit 1000000 >> /dev/null;
3.0.1.4 takes 14 seconds, while 3.0.1.8 takes 2.4 seconds, which is quite a big difference.
May I know which part of the code we optimized?
A:
3.0 TDengine database Use fflush to brush the disk after each record is written to the redirected file,It is not available in 2.6, which is new in 3.0, so the redirection output is slow.
we canceled this then to increase performance
| why 3.0.1.8 TDengine database's query performance is far better 3.0.1.4 | this SQL:
select * from meters limit 1000000 >> /dev/null;
3.0.1.4 takes 14 seconds, while 3.0.1.8 takes 2.4 seconds, which is quite a big difference.
May I know which part of the code we optimized?
| [
"3.0 TDengine database Use fflush to brush the disk after each record is written to the redirected file,It is not available in 2.6, which is new in 3.0, so the redirection output is slow.\nwe canceled this then to increase performance\n"
] | [
0
] | [] | [] | [
"tdengine"
] | stackoverflow_0074673592_tdengine.txt |
Q:
Show individual bar count label in grouped bar plot
I am trying to plot Male and Female in different Age Groups. I am trying to show the individual Male and Female Count in their respective bars/colours but the graphs shows the total count value in the AgeGroup. How I am going to show/label the individual count of male and female in their respective bars/colours by AgeGroup. Example Data is presented. Thanks
Age
sex
AgeGroup
22
F
18-25 Years
36
F
36-45 Years
20
M
18-25 Years
Code I used:
library(tidyverse)
ggplot(demo_df, mapping = aes(x = AgeGroup)) +
geom_bar(aes(fill = sex), position="dodge")+
geom_text(stat = "count", aes(label = scales::comma(after_stat(count))),
nudge_y = 10000, fontface = 2) +
theme_minimal() +
theme(axis.text.x = element_text(angle = 90, hjust = 0),
axis.text.y.left = element_blank(),
axis.title.y.left = element_blank())
A:
You need to specify that the labels should be grouped by sex.
You also need to apply position_dodge() to your labels.
After adding the position adjustment, nudge_y will no longer work. You can use vjust instead.
library(ggplot2)
ggplot(demo_df, mapping = aes(x = AgeGroup)) +
geom_bar(aes(fill = sex), position="dodge")+
geom_text(
stat = "count",
aes(label = scales::comma(after_stat(count)), group = sex),
position = position_dodge(width = 0.9),
vjust = -1,
fontface = 2
) +
theme_minimal() +
theme(axis.text.x = element_text(angle = 90, hjust = 0),
axis.text.y.left = element_blank(),
axis.title.y.left = element_blank())
A:
You need to add sex as a grouping variable in the text layer:
library(tidyverse)
ggplot(demo_df, mapping = aes(x = AgeGroup)) +
geom_bar(aes(fill = sex), position="dodge")+
geom_text(stat = "count",
aes(label = scales::comma(after_stat(count)), group = sex),
position = position_dodge(width = 0.9), fontface = 2,
vjust = -0.5) +
theme_minimal() +
theme(axis.text.x = element_text(angle = 90, hjust = 0),
axis.text.y.left = element_blank(),
axis.title.y.left = element_blank())
Reproducible data taken from answer to OP's previous question
demo_df <- data.frame(sex = rep(c('F', 'M'), c(514729, 470971)),
AgeGroup = rep(rep(c("18-25 years", "26-35 years",
"36-45 years", "46-55 years",
"55-65 years", "66-75 years",
"76-85 years", "86+ years"), 2),
times = c(40608, 80464, 85973, 72863, 72034,
62862, 54588, 45337, 37341, 77383,
83620, 67367, 67190, 64193, 49171,
24706)))
A:
One more version using geom_col and calculating stats before plotting:
Data from @Allan Cameron (many thanks!):
library(tidyverse)
library(RColorBrewer)
demo_df %>%
as_tibble() %>%
count(sex, AgeGroup) %>%
ggplot(aes(x=AgeGroup, y=n, fill = sex))+
geom_col(position = position_dodge())+
geom_text(aes(label = n, group = sex),
position = position_dodge(width = .9),
vjust = -1, size = 3)+
scale_fill_brewer(palette = 1, direction = - 1) +
theme_bw() +
theme(axis.text.x = element_text(angle = 90, hjust = 0),
axis.text.y.left = element_blank(),
axis.title.y.left = element_blank())
| Show individual bar count label in grouped bar plot | I am trying to plot Male and Female in different Age Groups. I am trying to show the individual Male and Female Count in their respective bars/colours but the graphs shows the total count value in the AgeGroup. How I am going to show/label the individual count of male and female in their respective bars/colours by AgeGroup. Example Data is presented. Thanks
Age
sex
AgeGroup
22
F
18-25 Years
36
F
36-45 Years
20
M
18-25 Years
Code I used:
library(tidyverse)
ggplot(demo_df, mapping = aes(x = AgeGroup)) +
geom_bar(aes(fill = sex), position="dodge")+
geom_text(stat = "count", aes(label = scales::comma(after_stat(count))),
nudge_y = 10000, fontface = 2) +
theme_minimal() +
theme(axis.text.x = element_text(angle = 90, hjust = 0),
axis.text.y.left = element_blank(),
axis.title.y.left = element_blank())
| [
"\nYou need to specify that the labels should be grouped by sex.\nYou also need to apply position_dodge() to your labels.\nAfter adding the position adjustment, nudge_y will no longer work. You can use vjust instead.\n\nlibrary(ggplot2)\n\nggplot(demo_df, mapping = aes(x = AgeGroup)) + \n geom_bar(aes(fill = sex), position=\"dodge\")+\n geom_text(\n stat = \"count\", \n aes(label = scales::comma(after_stat(count)), group = sex),\n position = position_dodge(width = 0.9),\n vjust = -1,\n fontface = 2\n ) +\n theme_minimal() +\n theme(axis.text.x = element_text(angle = 90, hjust = 0),\n axis.text.y.left = element_blank(),\n axis.title.y.left = element_blank())\n\n\n",
"You need to add sex as a grouping variable in the text layer:\nlibrary(tidyverse)\n\nggplot(demo_df, mapping = aes(x = AgeGroup)) + \n geom_bar(aes(fill = sex), position=\"dodge\")+\n geom_text(stat = \"count\", \n aes(label = scales::comma(after_stat(count)), group = sex),\n position = position_dodge(width = 0.9), fontface = 2,\n vjust = -0.5) +\n theme_minimal() +\n theme(axis.text.x = element_text(angle = 90, hjust = 0),\n axis.text.y.left = element_blank(),\n axis.title.y.left = element_blank())\n\n\n\nReproducible data taken from answer to OP's previous question\ndemo_df <- data.frame(sex = rep(c('F', 'M'), c(514729, 470971)), \n AgeGroup = rep(rep(c(\"18-25 years\", \"26-35 years\",\n \"36-45 years\", \"46-55 years\",\n \"55-65 years\", \"66-75 years\",\n \"76-85 years\", \"86+ years\"), 2),\n times = c(40608, 80464, 85973, 72863, 72034,\n 62862, 54588, 45337, 37341, 77383,\n 83620, 67367, 67190, 64193, 49171,\n 24706)))\n\n",
"One more version using geom_col and calculating stats before plotting:\nData from @Allan Cameron (many thanks!):\nlibrary(tidyverse)\nlibrary(RColorBrewer) \n\ndemo_df %>% \n as_tibble() %>% \n count(sex, AgeGroup) %>% \n ggplot(aes(x=AgeGroup, y=n, fill = sex))+\n geom_col(position = position_dodge())+\n geom_text(aes(label = n, group = sex), \n position = position_dodge(width = .9),\n vjust = -1, size = 3)+\n scale_fill_brewer(palette = 1, direction = - 1) + \n theme_bw() +\n theme(axis.text.x = element_text(angle = 90, hjust = 0),\n axis.text.y.left = element_blank(),\n axis.title.y.left = element_blank())\n\n\n"
] | [
3,
3,
3
] | [] | [] | [
"geom_bar",
"geom_text",
"ggplot2",
"r"
] | stackoverflow_0074677136_geom_bar_geom_text_ggplot2_r.txt |
Q:
WebStorm - Argument type {providedIn: "root"} is not assignable to parameter type {providedIn: Type | "root" | null} & InjectableProvider
I'm trying to migrate my app from Angular v5 to v6 and I face the following typescript error while trying to specify providedIn in my providers
Argument type {providedIn: "root"} is not assignable to parameter type {providedIn: Type | "root" | null} & InjectableProvider
@Injectable({
providedIn: 'root',
})
export class MyService {
}
I copied and pasted the code from the Angular doc https://angular.io/guide/dependency-injection
Any idea?
UPDATE
I have created a blank project ng new ... and added a provider ng g service my-new-service, opened the project in WebStorm and everything was ok, I didn't face any error with that dummy project
UPDATE
I contacted the WebStorm support, it turns out that this is a known bug of WebStorm https://youtrack.jetbrains.com/issue/WEB-32634
UPDATE
Webstorm 2018.1.4 (not yet released) should fix the issue, see https://youtrack.jetbrains.com/issue/WEB-32634
UPDATE
Webstorm team moved the fix to 2018.1.5
UPDATE
Sunday 17th June 2018, the Webstorm fix has been released
A:
Believe me or not, I closed and opened my project in Webstorm and the error just disappeared
Thx @yurzui and @AdrianFâciu for the support
UPDATE
It turns out it was a confirmed bug in Webstorm which was later corrected in v2018.1.5 and published Sunday 17th August 2018. I have updated my editor to this version and didn't face the problem anymore
Webstorm issue tracker: https://youtrack.jetbrains.com/issue/WEB-32634
v2018.1.5 release notes: https://confluence.jetbrains.com/display/WI/WebStorm+181.5281.31+Release+Notes
A:
for me the problem was a wrong import:
import { Injectable } from '@nestjs/common';
I had to change it to:
import { Injectable } from '@angular/core';
Hope that helps someone else!
| WebStorm - Argument type {providedIn: "root"} is not assignable to parameter type {providedIn: Type | "root" | null} & InjectableProvider | I'm trying to migrate my app from Angular v5 to v6 and I face the following typescript error while trying to specify providedIn in my providers
Argument type {providedIn: "root"} is not assignable to parameter type {providedIn: Type | "root" | null} & InjectableProvider
@Injectable({
providedIn: 'root',
})
export class MyService {
}
I copied and pasted the code from the Angular doc https://angular.io/guide/dependency-injection
Any idea?
UPDATE
I have created a blank project ng new ... and added a provider ng g service my-new-service, opened the project in WebStorm and everything was ok, I didn't face any error with that dummy project
UPDATE
I contacted the WebStorm support, it turns out that this is a known bug of WebStorm https://youtrack.jetbrains.com/issue/WEB-32634
UPDATE
Webstorm 2018.1.4 (not yet released) should fix the issue, see https://youtrack.jetbrains.com/issue/WEB-32634
UPDATE
Webstorm team moved the fix to 2018.1.5
UPDATE
Sunday 17th June 2018, the Webstorm fix has been released
| [
"Believe me or not, I closed and opened my project in Webstorm and the error just disappeared\nThx @yurzui and @AdrianFâciu for the support\nUPDATE\nIt turns out it was a confirmed bug in Webstorm which was later corrected in v2018.1.5 and published Sunday 17th August 2018. I have updated my editor to this version and didn't face the problem anymore\nWebstorm issue tracker: https://youtrack.jetbrains.com/issue/WEB-32634\nv2018.1.5 release notes: https://confluence.jetbrains.com/display/WI/WebStorm+181.5281.31+Release+Notes\n",
"for me the problem was a wrong import:\nimport { Injectable } from '@nestjs/common';\n\nI had to change it to:\nimport { Injectable } from '@angular/core';\n\nHope that helps someone else!\n"
] | [
33,
0
] | [] | [] | [
"angular",
"angular6",
"typescript",
"webstorm"
] | stackoverflow_0050201189_angular_angular6_typescript_webstorm.txt |
Q:
Align assembly to end of 4K block
I have some assembly. I'd like it to be at the end of a 4K block. Currently the section is being put at 0x1000003C0, I'd like it to be located at 0x100003F80
I tried using p2align but it didn't seem to put it at the end of the 4K block
A:
You can do this if you know a previous 4k-alignment point, but the tools don't make it easy to avoid wasting a huge amount of space.
.balign 4096
pagestart: // a page-aligned reference at some earlier point.
nop
.skip 5680
nop // some arbitrary amount of code after it, perhaps more than a page.
.skip 4096 - (. - pagestart) % 4096 - blocksize // pad to blocksize before end of page
blockstart:
add x1, x1, x2
add x2, x2, x3
// 4k boundary here
blockend:
.equ blocksize, blockend - blockstart
nop // more code
clang -target arm64 -c foo.s && llvm-objdump -d foo.o
foo.o: file format elf64-littleaarch64 (I'm on GNU/Linux, not MacOS)
foo.o: file format elf64-littleaarch64
Disassembly of section .text:
0000000000000000 <pagestart>:
0: 1f 20 03 d5 nop
0000000000000004 <$d.1>: // placeholder for actual code
4: 00 00 00 00 .word 0x00000000
8: 00 00 00 00 .word 0x00000000
...
1630: 00 00 00 00 .word 0x00000000
0000000000001634 <$x.2>:
1634: 1f 20 03 d5 nop // end of actual code
0000000000001638 <$d.3>: // padding for alignment of blockend
1638: 00 00 00 00 .word 0x00000000
...
1ff0: 00 00 00 00 .word 0x00000000
1ff4: 00 00 00 00 .word 0x00000000
0000000000001ff8 <blockstart>:
1ff8: 21 00 02 8b add x1, x1, x2
1ffc: 42 00 03 8b add x2, x2, x3
0000000000002000 <blockend>: // note 4k alignment
2000: 1f 20 03 d5 nop
So this costs 0 to 4092 bytes of padding, depending on block size. And it requires a 4k-aligned point inside this .s file; these sizes need to be assemble-time constants, not just link-time, since I don't think a relocation entry can express the % modulo. Or even without it, probably not the subtraction and variable-sized skip.
This doesn't work for me with clang -target arm64-macos -c foo.s on Linux so I'm not sure it's usable with Mach-O64 object files. Even without the % 4096, I still get an assemble-time error from .skip 4096 - (. - pagestart) - blocksize - error: expected assembly-time absolute expression
| Align assembly to end of 4K block | I have some assembly. I'd like it to be at the end of a 4K block. Currently the section is being put at 0x1000003C0, I'd like it to be located at 0x100003F80
I tried using p2align but it didn't seem to put it at the end of the 4K block
| [
"You can do this if you know a previous 4k-alignment point, but the tools don't make it easy to avoid wasting a huge amount of space.\n.balign 4096\npagestart: // a page-aligned reference at some earlier point.\n nop\n .skip 5680\n nop // some arbitrary amount of code after it, perhaps more than a page.\n\n .skip 4096 - (. - pagestart) % 4096 - blocksize // pad to blocksize before end of page\nblockstart:\n add x1, x1, x2\n add x2, x2, x3\n// 4k boundary here\nblockend:\n.equ blocksize, blockend - blockstart\n nop // more code\n\nclang -target arm64 -c foo.s && llvm-objdump -d foo.o\nfoo.o: file format elf64-littleaarch64 (I'm on GNU/Linux, not MacOS)\n\nfoo.o: file format elf64-littleaarch64\n\nDisassembly of section .text:\n\n0000000000000000 <pagestart>:\n 0: 1f 20 03 d5 nop\n\n0000000000000004 <$d.1>: // placeholder for actual code\n 4: 00 00 00 00 .word 0x00000000\n 8: 00 00 00 00 .word 0x00000000\n ...\n 1630: 00 00 00 00 .word 0x00000000\n\n0000000000001634 <$x.2>:\n 1634: 1f 20 03 d5 nop // end of actual code\n\n0000000000001638 <$d.3>: // padding for alignment of blockend\n 1638: 00 00 00 00 .word 0x00000000\n ...\n 1ff0: 00 00 00 00 .word 0x00000000\n 1ff4: 00 00 00 00 .word 0x00000000\n\n0000000000001ff8 <blockstart>:\n 1ff8: 21 00 02 8b add x1, x1, x2\n 1ffc: 42 00 03 8b add x2, x2, x3\n\n0000000000002000 <blockend>: // note 4k alignment\n 2000: 1f 20 03 d5 nop\n\nSo this costs 0 to 4092 bytes of padding, depending on block size. And it requires a 4k-aligned point inside this .s file; these sizes need to be assemble-time constants, not just link-time, since I don't think a relocation entry can express the % modulo. Or even without it, probably not the subtraction and variable-sized skip.\nThis doesn't work for me with clang -target arm64-macos -c foo.s on Linux so I'm not sure it's usable with Mach-O64 object files. Even without the % 4096, I still get an assemble-time error from .skip 4096 - (. - pagestart) - blocksize - error: expected assembly-time absolute expression\n"
] | [
2
] | [] | [] | [
"arm64",
"assembly",
"gnu_arm",
"gnu_assembler",
"macos"
] | stackoverflow_0074673461_arm64_assembly_gnu_arm_gnu_assembler_macos.txt |
Q:
Inconsistent output using do/while and for loop in asynchronous JavaScript using let to declare the variables
Why do I get a different output when using a do/while loop in the code below?
function logNum() {
let counter = 0;
do {
counter += 1;
setTimeout(() => console.log(counter), counter * 1000);
} while(counter <= 10);
}
logNum();
The above code outputs number 11 ten times. Expected output was numbers 1 to 10. But when I use a for loop, it works as expected as shown below. Why?
function logNum() {
for (let counter = 1; counter <= 10; counter += 1) {
setTimeout(() => console.log(counter), counter * 1000);
}
}
logNum();
Updated working code from example 1:
function logNum() {
let counter = 0;
do {
let num;
counter += 1;
num = counter;
setTimeout(() => console.log(num), num * 1000);
} while(counter < 10);
}
logNum();
A:
The first increments the counter very quickly and then when the setTimeout function triggers, the counter has already been incremented.
Run this below and you will see.
function logNum() {
let counter = 0;
do {
counter += 1;
console.log('A in loop',counter),
setTimeout(() => console.log('A in timeout',counter), counter * 1000);
} while (counter <= 10);
}
function logNum2() {
for (let counter = 1; counter <= 10; counter += 1) {
setTimeout(() => console.log('B',counter), counter * 1000);
}
}
logNum()
logNum2()
Update. I've just re-read the question - This answer is here:
What is the scope of a 'while' and 'for' loop?
| Inconsistent output using do/while and for loop in asynchronous JavaScript using let to declare the variables | Why do I get a different output when using a do/while loop in the code below?
function logNum() {
let counter = 0;
do {
counter += 1;
setTimeout(() => console.log(counter), counter * 1000);
} while(counter <= 10);
}
logNum();
The above code outputs number 11 ten times. Expected output was numbers 1 to 10. But when I use a for loop, it works as expected as shown below. Why?
function logNum() {
for (let counter = 1; counter <= 10; counter += 1) {
setTimeout(() => console.log(counter), counter * 1000);
}
}
logNum();
Updated working code from example 1:
function logNum() {
let counter = 0;
do {
let num;
counter += 1;
num = counter;
setTimeout(() => console.log(num), num * 1000);
} while(counter < 10);
}
logNum();
| [
"The first increments the counter very quickly and then when the setTimeout function triggers, the counter has already been incremented.\nRun this below and you will see.\n\n\nfunction logNum() {\n let counter = 0;\n\n do {\n counter += 1;\n console.log('A in loop',counter),\n setTimeout(() => console.log('A in timeout',counter), counter * 1000);\n } while (counter <= 10);\n}\n\nfunction logNum2() {\n for (let counter = 1; counter <= 10; counter += 1) {\n setTimeout(() => console.log('B',counter), counter * 1000);\n }\n}\n\nlogNum()\nlogNum2()\n\n\n\nUpdate. I've just re-read the question - This answer is here:\nWhat is the scope of a 'while' and 'for' loop?\n"
] | [
1
] | [] | [] | [
"asynchronous",
"asynchronous_javascript",
"javascript",
"settimeout"
] | stackoverflow_0074677484_asynchronous_asynchronous_javascript_javascript_settimeout.txt |
Q:
How to customize Subscription contributor role for blocking Storage in Azure
I have a requirement to customize the contributor role at Azure Subscription level, such that, people added to that customized contributor role can NOT view or read the data from the storage account (under that subscription).
This is how i'm doing this:
Step1
Step2
Step3 ( Actions shows * )
This MSFT link does NOT show me the JSON details that can be removed or added so that the read access to the storage account can be blocked.
Hence, I'm trying below ways to customize this (two assignable scopes to cover subscription as well as block viewing the storage data):
Note, The idea is to People need a contributor role to manage the subscription. However, they MUST NOT view the data from the storage under this particular subscription.
I think this is not the right approach. Are there any other ways to achieve this? Thanks.
A:
If you want to create a custom role, then you should have a look at the resource provider operations. From there, you can see all the available actions per resource provider.
You would probably be interested in the DataActions such as Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read and others depending on what you want to filter out.
A:
If you want to block particularly Azure Storage under Subscription Scope Level.
Kindly Exclude Azure Storage under Add Permission Section in order to block Azure Storage only while creating RBAC Role
| How to customize Subscription contributor role for blocking Storage in Azure | I have a requirement to customize the contributor role at Azure Subscription level, such that, people added to that customized contributor role can NOT view or read the data from the storage account (under that subscription).
This is how i'm doing this:
Step1
Step2
Step3 ( Actions shows * )
This MSFT link does NOT show me the JSON details that can be removed or added so that the read access to the storage account can be blocked.
Hence, I'm trying below ways to customize this (two assignable scopes to cover subscription as well as block viewing the storage data):
Note, The idea is to People need a contributor role to manage the subscription. However, they MUST NOT view the data from the storage under this particular subscription.
I think this is not the right approach. Are there any other ways to achieve this? Thanks.
| [
"If you want to create a custom role, then you should have a look at the resource provider operations. From there, you can see all the available actions per resource provider.\nYou would probably be interested in the DataActions such as Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read and others depending on what you want to filter out.\n",
"If you want to block particularly Azure Storage under Subscription Scope Level.\nKindly Exclude Azure Storage under Add Permission Section in order to block Azure Storage only while creating RBAC Role\n"
] | [
0,
0
] | [] | [] | [
"azure",
"azure_active_directory",
"azure_policy",
"azure_rbac",
"azure_storage"
] | stackoverflow_0074651891_azure_azure_active_directory_azure_policy_azure_rbac_azure_storage.txt |
Q:
Commit git changes but keep file highlighting in IntelliJ
I like to save my progress while working on large commits. But when I commit, my project naturally loses all of its highlighting of changes (lines and files) in IntelliJ. I am not very used to git so this may be an easy or hard question, but I want to commit my changes, but keep the highlighting of changes since my last big commit, so I think I would need to choose which commit to start highlighting from somehow.
Is there a way to do this, and can I be provided specific steps to do it?
I want to do this with as little damage to my git history as possible. When I am doing this I am doing it as a single developer. I am not very used to git, so any potential problems with any solutions would be good to know as well.
A:
While working on large commit is not the recommended best practice, you can:
save your work in progress through commits
keep your current diffs against your last commits
For that:
create a "wip" (for "work in progress") branch from your current dev branch (after your last small commit)
reset soft dev to your previous large commit
See IntelliJ "Reset a branch to a specific commit".
After the last soft reset, all your files should reflect the diff against said previous large commit
Whenever you want to commit again:
reset soft dev to your wip
add and commit
reset (hard) wip to your dev (to point to that last small commit)
reset soft dev to your previous large commit (to see again all your diffs compared to said previous large commit)
| Commit git changes but keep file highlighting in IntelliJ | I like to save my progress while working on large commits. But when I commit, my project naturally loses all of its highlighting of changes (lines and files) in IntelliJ. I am not very used to git so this may be an easy or hard question, but I want to commit my changes, but keep the highlighting of changes since my last big commit, so I think I would need to choose which commit to start highlighting from somehow.
Is there a way to do this, and can I be provided specific steps to do it?
I want to do this with as little damage to my git history as possible. When I am doing this I am doing it as a single developer. I am not very used to git, so any potential problems with any solutions would be good to know as well.
| [
"While working on large commit is not the recommended best practice, you can:\n\nsave your work in progress through commits\nkeep your current diffs against your last commits\n\nFor that:\n\ncreate a \"wip\" (for \"work in progress\") branch from your current dev branch (after your last small commit)\nreset soft dev to your previous large commit\n\nSee IntelliJ \"Reset a branch to a specific commit\".\nAfter the last soft reset, all your files should reflect the diff against said previous large commit\nWhenever you want to commit again:\n\nreset soft dev to your wip\nadd and commit\nreset (hard) wip to your dev (to point to that last small commit)\nreset soft dev to your previous large commit (to see again all your diffs compared to said previous large commit)\n\n"
] | [
0
] | [] | [] | [
"git",
"intellij_idea",
"pycharm",
"webstorm"
] | stackoverflow_0074673926_git_intellij_idea_pycharm_webstorm.txt |
Q:
Understanding how cookie is set on the browser
I'm using express-session to initialize a session and save the cookie. But the process of how the cookie is saved browser side is abstracted away and something of a black box to me, it just happens automatically. Can anyone point to a resource that explains how the client takes the cookie from the response and saves it in local storage? My front facing stack is composed of react, nextjs and urql client.
A:
When you use express-session to initialize a session and save the cookie on the server, the client automatically receives the cookie in the response from the server and saves it in the local storage. This happens because the browser automatically includes the cookie in the request headers for any subsequent requests to the same domain, and the server uses the cookie to identify the user's session.
The process of how the cookie is saved in the local storage and included in the request headers is part of the underlying mechanics of the HTTP protocol and is handled automatically by the browser. It is not something that you need to worry about or configure when using express-session.
If you want to learn more about how cookies work in general, you can check out the following resources:
The official documentation for cookies on the Mozilla Developer
Network: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
A tutorial on cookies from the W3Schools website:
https://www.w3schools.com/js/js_cookies.asp
| Understanding how cookie is set on the browser | I'm using express-session to initialize a session and save the cookie. But the process of how the cookie is saved browser side is abstracted away and something of a black box to me, it just happens automatically. Can anyone point to a resource that explains how the client takes the cookie from the response and saves it in local storage? My front facing stack is composed of react, nextjs and urql client.
| [
"When you use express-session to initialize a session and save the cookie on the server, the client automatically receives the cookie in the response from the server and saves it in the local storage. This happens because the browser automatically includes the cookie in the request headers for any subsequent requests to the same domain, and the server uses the cookie to identify the user's session.\nThe process of how the cookie is saved in the local storage and included in the request headers is part of the underlying mechanics of the HTTP protocol and is handled automatically by the browser. It is not something that you need to worry about or configure when using express-session.\nIf you want to learn more about how cookies work in general, you can check out the following resources:\n\nThe official documentation for cookies on the Mozilla Developer\nNetwork: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies\nA tutorial on cookies from the W3Schools website:\nhttps://www.w3schools.com/js/js_cookies.asp\n\n"
] | [
1
] | [] | [] | [
"cookies",
"express",
"express_session",
"node.js",
"reactjs"
] | stackoverflow_0074677521_cookies_express_express_session_node.js_reactjs.txt |
Q:
Office 2013 fails to install under WINE
Office 2013 fails to install using WINE. Using the online installer it loads up till 63% (app start load, not installation load) then says the Error - 30045-4. Please help
Office 2013 fails to install using WINE. Using the online installer it loads up till 63% (app start load, not installation load) then says the Error - 30045-4. What can I do to fix this
A:
Check if you are using the latest version of WINE. You can update WINE by running the following command in a terminal: wineboot --update
Make sure that you have the required dependencies installed for WINE. You can check the dependencies and install them if necessary by running the following command: winetricks
Try running the Microsoft Office installation in a clean WINE prefix. This can help to isolate any conflicts with other installed software. To create a clean WINE prefix, run the following commands:
WINEPREFIX=~/.wine-office2013 wineboot
WINEARCH=win32 WINEPREFIX=~/.wine-office2013 wine winecfg
Try using the offline installer for Microsoft Office 2013 instead of the online installer. The offline installer does not require an internet connection and may be less susceptible to installation issues. You can download the offline installer from the Microsoft website.
If the error persists, you can try reinstalling WINE or using a different version of WINE. You can also try using a different method for installing Microsoft Office 2013 on Linux, such as using a virtual machine or a compatibility layer like CrossOver.
| Office 2013 fails to install under WINE | Office 2013 fails to install using WINE. Using the online installer it loads up till 63% (app start load, not installation load) then says the Error - 30045-4. Please help
Office 2013 fails to install using WINE. Using the online installer it loads up till 63% (app start load, not installation load) then says the Error - 30045-4. What can I do to fix this
| [
"\nCheck if you are using the latest version of WINE. You can update WINE by running the following command in a terminal: wineboot --update\nMake sure that you have the required dependencies installed for WINE. You can check the dependencies and install them if necessary by running the following command: winetricks\nTry running the Microsoft Office installation in a clean WINE prefix. This can help to isolate any conflicts with other installed software. To create a clean WINE prefix, run the following commands:\n\nWINEPREFIX=~/.wine-office2013 wineboot\nWINEARCH=win32 WINEPREFIX=~/.wine-office2013 wine winecfg\n\n\nTry using the offline installer for Microsoft Office 2013 instead of the online installer. The offline installer does not require an internet connection and may be less susceptible to installation issues. You can download the offline installer from the Microsoft website.\nIf the error persists, you can try reinstalling WINE or using a different version of WINE. You can also try using a different method for installing Microsoft Office 2013 on Linux, such as using a virtual machine or a compatibility layer like CrossOver.\n\n"
] | [
1
] | [] | [] | [
"ms_office",
"wine"
] | stackoverflow_0074677491_ms_office_wine.txt |
Q:
Pyspark MapReduce - how to get number occurrences in a list of tuple
I have a list like:
A 2022-08-13
B 2022-08-14
B 2022-08-13
A 2022-05-04
B 2022-05-04
C 2022-08-14
...
and I applied the following map functions to map each row with the # of occurrences:
map(lambda x: ((x.split(',')[0], x.split(',')[1]), 1))
To get this:
[
(('A', '2022-08-13'), 1),
(('B', '2022-08-14'), 1),
(('B', '2022-08-13'), 1),
(('A', '2022-05-04'), 1),
(('B', '2022-05-04'), 1),
(('C', '2022-08-14'), 1),
...
]
My end goal is to find the number of occurrences where two persons (denoted by the letter) have the same dates, to output something like this for the example above:
[
('A', 'B', 2),
('B', 'C', 1),
...
]
This is my code so far, but the reduceByKey is not working as expected:
shifts_mapped = worker_shifts.map(lambda x: (x.split(',')[1], 1))
shifts_mapped = worker_shifts.map(lambda x: ((x.split(',')[0], x.split(',')[1]), 1))
count = shifts_mapped.reduceByKey(lambda x, y: x[0][1] + y[0][1])
A:
Group by multiple times, first by "person", "date" and then by "date", "count" and collect persons with same date and count.
Then generate pair combinations, explode, and separate pair.
I extended your sample dataset to include persons "D" & "E" same as "A" & "B" to generate more combinations.
df = spark.createDataFrame(data=[["A","2022-08-13"],["E","2022-08-13"],["D","2022-08-13"],["B","2022-08-14"],["B","2022-08-13"],["D","2022-05-04"],["E","2022-05-04"],["A","2022-05-04"],["B","2022-05-04"],["C","2022-08-14"]], schema=["person", "date"])
df = df.groupBy("person", "date").count()
df = df.groupBy("date", "count") \
.agg(F.collect_list("person").alias("persons"))
@F.udf(returnType="array<struct<col1:string, col2:string>>")
def combinations(arr):
import itertools
return list(itertools.combinations(sorted(arr), 2))
df = df.withColumn("persons", combinations("persons"))
df = df.withColumn("persons", F.explode("persons"))
df = df.withColumn("person_1", F.col("persons").getField("col1")) \
.withColumn("person_2", F.col("persons").getField("col2"))
df = df.groupBy("person_1", "person_2").count()
Output:
+--------+--------+-----+
|person_1|person_2|count|
+--------+--------+-----+
|B |C |1 |
|D |E |2 |
|A |E |2 |
|A |D |2 |
|B |D |2 |
|A |B |2 |
|B |E |2 |
+--------+--------+-----+
| Pyspark MapReduce - how to get number occurrences in a list of tuple | I have a list like:
A 2022-08-13
B 2022-08-14
B 2022-08-13
A 2022-05-04
B 2022-05-04
C 2022-08-14
...
and I applied the following map functions to map each row with the # of occurrences:
map(lambda x: ((x.split(',')[0], x.split(',')[1]), 1))
To get this:
[
(('A', '2022-08-13'), 1),
(('B', '2022-08-14'), 1),
(('B', '2022-08-13'), 1),
(('A', '2022-05-04'), 1),
(('B', '2022-05-04'), 1),
(('C', '2022-08-14'), 1),
...
]
My end goal is to find the number of occurrences where two persons (denoted by the letter) have the same dates, to output something like this for the example above:
[
('A', 'B', 2),
('B', 'C', 1),
...
]
This is my code so far, but the reduceByKey is not working as expected:
shifts_mapped = worker_shifts.map(lambda x: (x.split(',')[1], 1))
shifts_mapped = worker_shifts.map(lambda x: ((x.split(',')[0], x.split(',')[1]), 1))
count = shifts_mapped.reduceByKey(lambda x, y: x[0][1] + y[0][1])
| [
"Group by multiple times, first by \"person\", \"date\" and then by \"date\", \"count\" and collect persons with same date and count.\nThen generate pair combinations, explode, and separate pair.\nI extended your sample dataset to include persons \"D\" & \"E\" same as \"A\" & \"B\" to generate more combinations.\ndf = spark.createDataFrame(data=[[\"A\",\"2022-08-13\"],[\"E\",\"2022-08-13\"],[\"D\",\"2022-08-13\"],[\"B\",\"2022-08-14\"],[\"B\",\"2022-08-13\"],[\"D\",\"2022-05-04\"],[\"E\",\"2022-05-04\"],[\"A\",\"2022-05-04\"],[\"B\",\"2022-05-04\"],[\"C\",\"2022-08-14\"]], schema=[\"person\", \"date\"])\n\ndf = df.groupBy(\"person\", \"date\").count()\n\ndf = df.groupBy(\"date\", \"count\") \\\n .agg(F.collect_list(\"person\").alias(\"persons\"))\n\[email protected](returnType=\"array<struct<col1:string, col2:string>>\")\ndef combinations(arr): \n import itertools\n return list(itertools.combinations(sorted(arr), 2))\n\ndf = df.withColumn(\"persons\", combinations(\"persons\"))\n\ndf = df.withColumn(\"persons\", F.explode(\"persons\"))\n\ndf = df.withColumn(\"person_1\", F.col(\"persons\").getField(\"col1\")) \\\n .withColumn(\"person_2\", F.col(\"persons\").getField(\"col2\"))\n\ndf = df.groupBy(\"person_1\", \"person_2\").count()\n\nOutput:\n+--------+--------+-----+\n|person_1|person_2|count|\n+--------+--------+-----+\n|B |C |1 |\n|D |E |2 |\n|A |E |2 |\n|A |D |2 |\n|B |D |2 |\n|A |B |2 |\n|B |E |2 |\n+--------+--------+-----+\n\n"
] | [
0
] | [] | [] | [
"apache_spark",
"pyspark",
"python"
] | stackoverflow_0074663401_apache_spark_pyspark_python.txt |
Q:
Jest test not passing for debounce function
I have this function
import _ from 'underscore';
const configMap = {};
export function someFunctionName(someValue, dispatch, reduxAction) {
if (!configMap[someValue]) {
configMap[someValue] = _.debounce(
(someValue) => dispatch(reduxAction(someValue)),
1000,
);
}
return configMap[someValue];
}
with jest tests:
const dispatchMock = jest.fn();
const reduxAction = jest.fn().mockReturnValue({});
jest.useFakeTimers();
describe('someFunctionName', () => {
it('should dispatch reduxAction', async () => {
someFunctionName('value', dispatchMock, reduxAction);
jest.runAllTimers();
expect(reduxAction).toHaveBeenCalled();
});
});
Test keeps failing and i'm not sure why. I initially thought it could be the debounce method needs a mock, but that doesn't seem to fix it.
A:
Lodash's debounce function is asynchronous which means the return statement of someFunctionName is going to execute before debounce comes back with a value. Additionally, the function inside debounce is not going to run until the provided wait time of 1000ms has elapsed.
You'll need to add async logic to wait for the result of debounce within someFunctionName before returning. This SO post may provide further help on how to achieve this.
| Jest test not passing for debounce function | I have this function
import _ from 'underscore';
const configMap = {};
export function someFunctionName(someValue, dispatch, reduxAction) {
if (!configMap[someValue]) {
configMap[someValue] = _.debounce(
(someValue) => dispatch(reduxAction(someValue)),
1000,
);
}
return configMap[someValue];
}
with jest tests:
const dispatchMock = jest.fn();
const reduxAction = jest.fn().mockReturnValue({});
jest.useFakeTimers();
describe('someFunctionName', () => {
it('should dispatch reduxAction', async () => {
someFunctionName('value', dispatchMock, reduxAction);
jest.runAllTimers();
expect(reduxAction).toHaveBeenCalled();
});
});
Test keeps failing and i'm not sure why. I initially thought it could be the debounce method needs a mock, but that doesn't seem to fix it.
| [
"Lodash's debounce function is asynchronous which means the return statement of someFunctionName is going to execute before debounce comes back with a value. Additionally, the function inside debounce is not going to run until the provided wait time of 1000ms has elapsed.\nYou'll need to add async logic to wait for the result of debounce within someFunctionName before returning. This SO post may provide further help on how to achieve this.\n"
] | [
0
] | [] | [] | [
"debouncing",
"javascript",
"jestjs",
"unit_testing"
] | stackoverflow_0074675958_debouncing_javascript_jestjs_unit_testing.txt |
Q:
Multi head Attention calculation
I create a model with a multi head attention layer,
import torch
import torch.nn as nn
query = torch.randn(2, 4)
key = torch.randn(2, 4)
value = torch.randn(2, 4)
model = nn.MultiheadAttention(4, 1, bias=False)
model(query, key, value)
I attempt at matching the attention output obtained,
softmax_output = torch.softmax((([email protected]_proj_weight[:4])@(([email protected]_proj_weight[4:8]).t()))/2, dim=1)
intermediate_output = softmax_output@([email protected]_proj_weight[8:12])
final_output = [email protected]_proj.weight
but the final_output does not match the attention output
A:
was able to match the output,
q_w = [email protected]_proj_weight[:4].t()
k_w = [email protected]_proj_weight[4:8].t()
v_w = [email protected]_proj_weight[8:12].t()
softmax_output = torch.softmax((q_w@k_w.t())/2, dim=1)
attention = softmax_output@v_w
final_output = [email protected]_proj.weight.t()
was missing the transpose earlier
| Multi head Attention calculation | I create a model with a multi head attention layer,
import torch
import torch.nn as nn
query = torch.randn(2, 4)
key = torch.randn(2, 4)
value = torch.randn(2, 4)
model = nn.MultiheadAttention(4, 1, bias=False)
model(query, key, value)
I attempt at matching the attention output obtained,
softmax_output = torch.softmax((([email protected]_proj_weight[:4])@(([email protected]_proj_weight[4:8]).t()))/2, dim=1)
intermediate_output = softmax_output@([email protected]_proj_weight[8:12])
final_output = [email protected]_proj.weight
but the final_output does not match the attention output
| [
"was able to match the output,\nq_w = [email protected]_proj_weight[:4].t()\nk_w = [email protected]_proj_weight[4:8].t()\nv_w = [email protected]_proj_weight[8:12].t()\n\nsoftmax_output = torch.softmax((q_w@k_w.t())/2, dim=1)\n\nattention = softmax_output@v_w\n\nfinal_output = [email protected]_proj.weight.t()\n\nwas missing the transpose earlier\n"
] | [
0
] | [] | [] | [
"multihead_attention",
"pytorch"
] | stackoverflow_0074677218_multihead_attention_pytorch.txt |
Q:
Ebay Scraping, filter out international results, select parents that do not have specific descendants
EDIT:
I have solved this thanks to @Driftr95
Here is the working code:
import xlwings as xw
from bs4 import BeautifulSoup
import requests
import statistics
@xw.func
def get_prices(url,args =[]):
url = requests.get(url).content
soup = BeautifulSoup(url,'lxml')
products = []
rsecSel = 'li:not(.srp-river-answer--REWRITE_START ~ li)'
iDetSel = f'div[id="srp-river-results"] {rsecSel} div.s-item__details'
results = soup.select(f'{iDetSel}:not(:has(span.s-item__location))')
for item in results:
price = item.find('span', class_='s-item__price').text.replace('$', '').replace(',', '')
if 'to' not in price:
price = float(price)
products.append(price)
mean = round(statistics.mean(products), 2)
median = round(statistics.median(products), 2)
return mean, median
I now have a working function in excel that will automatically look up sold prices on ebay that I can iterate over a large amount of products instantly!
I have some code that I put together to scrape ebay sold prices using BeautifulSoup and so far it is working pretty good. The only issue I currently have is that it also pulls prices for 2 categories that ebay adds to the search results page (International Sellers, and results matching fewer words)
I am struggling to filter these out. Its like I need to identify if the listing (the parent) contains a specific descendant and then filter out that parent. I hope that is clear, here is a sample:
https://www.ebay.com/sch/57988/i.html?_from=R40&_nkw=Fjallraven%20nuuk%20parka&LH_Complete=1&LH_Sold=1&_udlo=50&_udhi=600&LH_PrefLoc=1
The picture is an example of an item that I would like to filter out. It has a Span Class for location. This class only exists if the item is from an international seller.
import xlwings as xw
import bs4 as bs
import requests
import statistics
@xw.func
def get_prices(url,args =[]):
url_base = requests.get(url).text
soup = bs.BeautifulSoup(url_base,'lxml')
products = []
results = soup.find('div', {'class': 'srp-river-results clearfix'}).find_all('div', {'class': ['s-item__details clearfix'] })
for item in results:
price = item.find('span', class_='s-item__price').text.replace('$', '').replace(',', '')
if 'to' not in price:
price = float(price)
products.append(price)
#def calculate_averages(products):
mean = round(statistics.mean(products), 2)
median = round(statistics.median(products), 2)
mode = round(statistics.mode(products), 2)
return mean, median, mode
I have tried several different methods but cannot seem to filter out the parents based on a class in one of the children.
A:
It has a Span Class for location. This class only exists if the item is from an international seller.
Assuming the class you mean is s-item__location you can use .select with the :has and :not pseudo-classes as below
iDetSel = 'div[id="srp-river-results"] div.s-item__details'
# results = soup.select(iDetSel) # --> your current resultset
results = soup.select(f'{iDetSel}:not(:has(span.s-item__location))')
or, if you want to only use find...:
results = soup.find_all(
lambda r: r.name == 'div' and
r.get('class') == ['s-item__details', 'clearfix'] and
r.find_parent('div', {'class': 'srp-river-results clearfix'}) and
not r.find('span', {'class': 's-item__location'})
)
(I find the .select-with-CSS-selectors method much more convenient.)
As an example:
url = 'https://www.ebay.com/sch/57988/i.html?_from=R40&_nkw=Fjallraven%20nuuk%20parka&LH_Complete=1&LH_Sold=1&_udlo=50&_udhi=600&LH_PrefLoc=1'
soup = BeautifulSoup(requests.get(url).content)
iDetSel = 'div[id="srp-river-results"] div.s-item__details'
selectors = [
('With Location', f'{iDetSel}:has(span.s-item__location)') ,
('Without Location', f'{iDetSel}:not(:has(span.s-item__location))')
]
for t, sel in selectors:
print(f'\n\n{t}')
for r in soup.select(sel):
print(' ', ' '.join(w for w in r.get_text(' ').split() if w)) # minimize whitespace
prints
With Location
$151.40 Best offer accepted +$16.72 shipping from Lithuania Free returns Sponsored
Without Location
$349.95 Buy It Now Free shipping Sponsored
$299.40 Was: Previous Price $499.00 40% off or Best Offer +$29.00 shipping Sponsored
$425.00 Best offer accepted +$13.45 shipping Sponsored
$329.99 Buy It Now +$19.99 shipping Sponsored
$349.30 Was: Previous Price $499.00 30% off or Best Offer +$29.00 shipping Sponsored
$296.65 Was: Previous Price $349.00 15% off Buy It Now +$20.00 shipping Sponsored
$339.99 Buy It Now +$17.87 shipping Sponsored
$361.00 Buy It Now +$10.51 shipping Sponsored
$202.00 16 bids +$25.05 shipping Sponsored
$236.00 Buy It Now +$5.99 shipping Extra 15% off Sponsored
$300.00 or Best Offer +$12.75 shipping Sponsored
$330.00 or Best Offer +$11.00 shipping Sponsored
$330.00 Best offer accepted +$11.00 shipping Sponsored
$289.00 Best offer accepted +$16.75 shipping Sponsored
Added EDIT: To only get the first section, you can do
rsecSel = 'li:not(.srp-river-answer--REWRITE_START ~ li)'
iDetSel = f'div[id="srp-river-results"] {rsecSel} div.s-item__details'
results = soup.select(f'{iDetSel}:not(:has(span.s-item__location))')
(Although, since the international sellers seem to be in a separate section, the :not(:has(span.s-item__location)) part might not be necessary...)
| Ebay Scraping, filter out international results, select parents that do not have specific descendants | EDIT:
I have solved this thanks to @Driftr95
Here is the working code:
import xlwings as xw
from bs4 import BeautifulSoup
import requests
import statistics
@xw.func
def get_prices(url,args =[]):
url = requests.get(url).content
soup = BeautifulSoup(url,'lxml')
products = []
rsecSel = 'li:not(.srp-river-answer--REWRITE_START ~ li)'
iDetSel = f'div[id="srp-river-results"] {rsecSel} div.s-item__details'
results = soup.select(f'{iDetSel}:not(:has(span.s-item__location))')
for item in results:
price = item.find('span', class_='s-item__price').text.replace('$', '').replace(',', '')
if 'to' not in price:
price = float(price)
products.append(price)
mean = round(statistics.mean(products), 2)
median = round(statistics.median(products), 2)
return mean, median
I now have a working function in excel that will automatically look up sold prices on ebay that I can iterate over a large amount of products instantly!
I have some code that I put together to scrape ebay sold prices using BeautifulSoup and so far it is working pretty good. The only issue I currently have is that it also pulls prices for 2 categories that ebay adds to the search results page (International Sellers, and results matching fewer words)
I am struggling to filter these out. Its like I need to identify if the listing (the parent) contains a specific descendant and then filter out that parent. I hope that is clear, here is a sample:
https://www.ebay.com/sch/57988/i.html?_from=R40&_nkw=Fjallraven%20nuuk%20parka&LH_Complete=1&LH_Sold=1&_udlo=50&_udhi=600&LH_PrefLoc=1
The picture is an example of an item that I would like to filter out. It has a Span Class for location. This class only exists if the item is from an international seller.
import xlwings as xw
import bs4 as bs
import requests
import statistics
@xw.func
def get_prices(url,args =[]):
url_base = requests.get(url).text
soup = bs.BeautifulSoup(url_base,'lxml')
products = []
results = soup.find('div', {'class': 'srp-river-results clearfix'}).find_all('div', {'class': ['s-item__details clearfix'] })
for item in results:
price = item.find('span', class_='s-item__price').text.replace('$', '').replace(',', '')
if 'to' not in price:
price = float(price)
products.append(price)
#def calculate_averages(products):
mean = round(statistics.mean(products), 2)
median = round(statistics.median(products), 2)
mode = round(statistics.mode(products), 2)
return mean, median, mode
I have tried several different methods but cannot seem to filter out the parents based on a class in one of the children.
| [
"\nIt has a Span Class for location. This class only exists if the item is from an international seller.\n\nAssuming the class you mean is s-item__location you can use .select with the :has and :not pseudo-classes as below\n iDetSel = 'div[id=\"srp-river-results\"] div.s-item__details'\n # results = soup.select(iDetSel) # --> your current resultset\n results = soup.select(f'{iDetSel}:not(:has(span.s-item__location))')\n\nor, if you want to only use find...:\n results = soup.find_all(\n lambda r: r.name == 'div' and \n r.get('class') == ['s-item__details', 'clearfix'] and\n r.find_parent('div', {'class': 'srp-river-results clearfix'}) and\n not r.find('span', {'class': 's-item__location'})\n )\n\n(I find the .select-with-CSS-selectors method much more convenient.)\n\nAs an example:\nurl = 'https://www.ebay.com/sch/57988/i.html?_from=R40&_nkw=Fjallraven%20nuuk%20parka&LH_Complete=1&LH_Sold=1&_udlo=50&_udhi=600&LH_PrefLoc=1'\nsoup = BeautifulSoup(requests.get(url).content)\n\niDetSel = 'div[id=\"srp-river-results\"] div.s-item__details' \nselectors = [\n ('With Location', f'{iDetSel}:has(span.s-item__location)') , \n ('Without Location', f'{iDetSel}:not(:has(span.s-item__location))') \n] \nfor t, sel in selectors:\n print(f'\\n\\n{t}')\n for r in soup.select(sel):\n print(' ', ' '.join(w for w in r.get_text(' ').split() if w)) # minimize whitespace\n\nprints\n\n\nWith Location\n $151.40 Best offer accepted +$16.72 shipping from Lithuania Free returns Sponsored\n\n\nWithout Location\n $349.95 Buy It Now Free shipping Sponsored\n $299.40 Was: Previous Price $499.00 40% off or Best Offer +$29.00 shipping Sponsored\n $425.00 Best offer accepted +$13.45 shipping Sponsored\n $329.99 Buy It Now +$19.99 shipping Sponsored\n $349.30 Was: Previous Price $499.00 30% off or Best Offer +$29.00 shipping Sponsored\n $296.65 Was: Previous Price $349.00 15% off Buy It Now +$20.00 shipping Sponsored\n $339.99 Buy It Now +$17.87 shipping Sponsored\n $361.00 Buy It Now +$10.51 shipping Sponsored\n $202.00 16 bids +$25.05 shipping Sponsored\n $236.00 Buy It Now +$5.99 shipping Extra 15% off Sponsored\n $300.00 or Best Offer +$12.75 shipping Sponsored\n $330.00 or Best Offer +$11.00 shipping Sponsored\n $330.00 Best offer accepted +$11.00 shipping Sponsored\n $289.00 Best offer accepted +$16.75 shipping Sponsored\n\n\n\nAdded EDIT: To only get the first section, you can do\n rsecSel = 'li:not(.srp-river-answer--REWRITE_START ~ li)'\n iDetSel = f'div[id=\"srp-river-results\"] {rsecSel} div.s-item__details'\n results = soup.select(f'{iDetSel}:not(:has(span.s-item__location))')\n\n(Although, since the international sellers seem to be in a separate section, the :not(:has(span.s-item__location)) part might not be necessary...)\n"
] | [
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074673061_beautifulsoup_python.txt |
Q:
Golang libvirt guest-agent not available
I've tried to communicate with the guest agent on a qemu instance through the libvirt golang API. However, it always reject my connections with
2022-12-02T00:10:43.799+0100 DPANIC test/main.go:335 Failed to connect to guest {"error": "virError(Code=86, Domain=10, Message='Guest agent is not responding: QEMU guest agent is not connected')"}
Even if the qemu instance is fully booted and the guest agent is available through the commandline
sudo virsh qemu-agent-command test-vm '{"execute":"guest-info"}'
Is this a bug in the implementation or do I have to register the agent somewhere in the go code? I wasn't able to find references in the documentation.
<channel type='unix'>
<source mode='bind' path='/var/lib/libvirt/qemu/channel/target/domain-6-test-vm/org.qemu.guest_agent.0'/>
<target type='virtio' name='org.qemu.guest_agent.0' state='connected'/>
<alias name='channel0'/>
<address type='virtio-serial' controller='0' bus='0' port='1'/>
</channel>
Thanks!
A:
Not sure what was the cause in the end. I had a loop and was accessing, or to be more specific try to access, the agent. I changed it to use a timeout of 500ms and not it works.
type qemuStatusResponse struct {
Return struct {
Exitcode int `json:"exitcode,omitempty"`
OutData string `json:"out-data,omitempty"`
Exited bool `json:"exited,omitempty"`
ErrData string `json:"err-data,omitempty"`
} `json:"return,omitempty"`
}
func (l *LibvirtInstance) waitForCompletion(ctx context.Context, pid int, domain *libvirt.Domain) (response *qemuStatusResponse, err error) {
response = &qemuStatusResponse{}
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ticker.C:
result, err := domain.QemuAgentCommand(
fmt.Sprintf(`
{
"execute": "guest-exec-status",
"arguments": {
"pid": %d
}
}`, pid),
libvirt.DOMAIN_QEMU_AGENT_COMMAND_BLOCK, 0)
if err != nil {
return nil, err
}
if err := json.Unmarshal([]byte(result), response); err != nil {
return nil, err
}
if response.Return.Exited {
return response, nil
}
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
Furhtermore I had some stability issues (i.e., when executing multiple concurrent requests to the connection it was sometimes broken). I found some article in the web suggesting adding the user to the kvm group. This worked for me.
| Golang libvirt guest-agent not available | I've tried to communicate with the guest agent on a qemu instance through the libvirt golang API. However, it always reject my connections with
2022-12-02T00:10:43.799+0100 DPANIC test/main.go:335 Failed to connect to guest {"error": "virError(Code=86, Domain=10, Message='Guest agent is not responding: QEMU guest agent is not connected')"}
Even if the qemu instance is fully booted and the guest agent is available through the commandline
sudo virsh qemu-agent-command test-vm '{"execute":"guest-info"}'
Is this a bug in the implementation or do I have to register the agent somewhere in the go code? I wasn't able to find references in the documentation.
<channel type='unix'>
<source mode='bind' path='/var/lib/libvirt/qemu/channel/target/domain-6-test-vm/org.qemu.guest_agent.0'/>
<target type='virtio' name='org.qemu.guest_agent.0' state='connected'/>
<alias name='channel0'/>
<address type='virtio-serial' controller='0' bus='0' port='1'/>
</channel>
Thanks!
| [
"Not sure what was the cause in the end. I had a loop and was accessing, or to be more specific try to access, the agent. I changed it to use a timeout of 500ms and not it works.\ntype qemuStatusResponse struct {\n Return struct {\n Exitcode int `json:\"exitcode,omitempty\"`\n OutData string `json:\"out-data,omitempty\"`\n Exited bool `json:\"exited,omitempty\"`\n ErrData string `json:\"err-data,omitempty\"`\n } `json:\"return,omitempty\"`\n}\n\nfunc (l *LibvirtInstance) waitForCompletion(ctx context.Context, pid int, domain *libvirt.Domain) (response *qemuStatusResponse, err error) {\n response = &qemuStatusResponse{}\n\n ticker := time.NewTicker(500 * time.Millisecond)\n defer ticker.Stop()\n for {\n select {\n case <-ticker.C:\n result, err := domain.QemuAgentCommand(\n fmt.Sprintf(`\n {\n \"execute\": \"guest-exec-status\",\n \"arguments\": {\n \"pid\": %d\n }\n }`, pid),\n libvirt.DOMAIN_QEMU_AGENT_COMMAND_BLOCK, 0)\n if err != nil {\n return nil, err\n }\n if err := json.Unmarshal([]byte(result), response); err != nil {\n return nil, err\n }\n if response.Return.Exited {\n return response, nil\n }\n case <-ctx.Done():\n return nil, ctx.Err()\n }\n }\n}\n\nFurhtermore I had some stability issues (i.e., when executing multiple concurrent requests to the connection it was sometimes broken). I found some article in the web suggesting adding the user to the kvm group. This worked for me.\n"
] | [
0
] | [] | [] | [
"go",
"libvirt",
"qemu",
"virsh"
] | stackoverflow_0074649202_go_libvirt_qemu_virsh.txt |
Q:
how to create dynamic database table using csv file in django or DRF
I am going to create a database table using csv file without model in django. Steps are:
after sending csv file by post request, one database table will be created according to csv headers (name, university, score, total_score etc). And it will be populated using csv file data. Database table name should be derived from csv file name.
I searched but couldn't find good solution.
Any help is appreciated.
Below is my code to read csv file
class UploadProductApiView(generics.CreateAPIView):
serializer_class = FileUploadSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
file = serializer.validated_data['file']
decoded_file = file.read().decode()
# upload_products_csv.delay(decoded_file, request.user.pk)
io_string = io.StringIO(decoded_file)
reader = csv.reader(io_string)
for row in reader:
print(row)
A:
You could always create a dynamic Django model: https://code.djangoproject.com/wiki/DynamicModels
With this approach you could create models on the fly and by running this snippet
from django.core.management import call_command
call_command('makemigrations')
call_command('migrate')
you could migrate the model to the database and use it for accessing and storing the csv data. After that you should create the model code with inspectdb:
python manage.py inspectdb TableName > output.py
Set the path to the where you want your model file to be generated. I'm not certain if this command would overwrite or append to the current file, so you can try to append to current file, if it doesn't work make a temp file and write the output to it and append it to your desired models.py file: https://www.geeksforgeeks.org/python-append-content-of-one-text-file-to-another/
After the whole process you will have migrations generated, executed and the model in models.py for use on server restart.
| how to create dynamic database table using csv file in django or DRF | I am going to create a database table using csv file without model in django. Steps are:
after sending csv file by post request, one database table will be created according to csv headers (name, university, score, total_score etc). And it will be populated using csv file data. Database table name should be derived from csv file name.
I searched but couldn't find good solution.
Any help is appreciated.
Below is my code to read csv file
class UploadProductApiView(generics.CreateAPIView):
serializer_class = FileUploadSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
file = serializer.validated_data['file']
decoded_file = file.read().decode()
# upload_products_csv.delay(decoded_file, request.user.pk)
io_string = io.StringIO(decoded_file)
reader = csv.reader(io_string)
for row in reader:
print(row)
| [
"You could always create a dynamic Django model: https://code.djangoproject.com/wiki/DynamicModels\nWith this approach you could create models on the fly and by running this snippet\nfrom django.core.management import call_command\ncall_command('makemigrations')\ncall_command('migrate')\n\nyou could migrate the model to the database and use it for accessing and storing the csv data. After that you should create the model code with inspectdb:\npython manage.py inspectdb TableName > output.py\n\nSet the path to the where you want your model file to be generated. I'm not certain if this command would overwrite or append to the current file, so you can try to append to current file, if it doesn't work make a temp file and write the output to it and append it to your desired models.py file: https://www.geeksforgeeks.org/python-append-content-of-one-text-file-to-another/\nAfter the whole process you will have migrations generated, executed and the model in models.py for use on server restart.\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"dynamic_programming",
"python"
] | stackoverflow_0074666791_django_django_models_django_rest_framework_dynamic_programming_python.txt |
Q:
How to sort a list of strings in terms of a duplicate re-ordered copy
Take these two list of strings for example.
names = ['Jack', 'Steve', 'Marc', 'Xavier', 'Bob']
names_copy = ['Steve', 'Marc', 'Xavier', 'Bob', 'Jack']
Essentially I'm trying to find a way to sort names_copy in the same way that names is sorted.
So, a sorted version of names_copy would result in ['Jack', 'Steve', 'Marc', 'Xavier', 'Bob']
NOTE: in my program, names_copy is being created with a map, so I cannot use .sort(), sorted() works however.
I understand the sorted() function takes in a key parameter indicating the sort order, but I'm not too sure how to use it here.
A:
The easiest way would be to do:
names_copy_sorted = sorted(names_copy, key=names.index)
This assumes that every item in names_copy is actually an item in names. But this solution isn't very efficient. It would be more efficient to create a dictionary that assigns a priority to the items from names and then uses those priorities as key. For example:
priorities = dict((n, i) for i, n in enumerate(names))
names_copy_sorted = sorted(names_copy, key=priorities.get)
If there are items in names_copy that aren't in names then you could adjust that with something like:
priorities = dict((n, i) for i, n in enumerate(names))
default = len(priorities)
def key(name): return priorities.get(name, default)
names_copy_sorted = sorted(names_copy, key=key)
This way the items in names_copy that are not in names are pushed to the back.
Be aware that duplicates in names are dealt with differently: names.index uses the first occurrence as priority, while the priorities.get version uses the last.
| How to sort a list of strings in terms of a duplicate re-ordered copy | Take these two list of strings for example.
names = ['Jack', 'Steve', 'Marc', 'Xavier', 'Bob']
names_copy = ['Steve', 'Marc', 'Xavier', 'Bob', 'Jack']
Essentially I'm trying to find a way to sort names_copy in the same way that names is sorted.
So, a sorted version of names_copy would result in ['Jack', 'Steve', 'Marc', 'Xavier', 'Bob']
NOTE: in my program, names_copy is being created with a map, so I cannot use .sort(), sorted() works however.
I understand the sorted() function takes in a key parameter indicating the sort order, but I'm not too sure how to use it here.
| [
"The easiest way would be to do:\nnames_copy_sorted = sorted(names_copy, key=names.index)\n\nThis assumes that every item in names_copy is actually an item in names. But this solution isn't very efficient. It would be more efficient to create a dictionary that assigns a priority to the items from names and then uses those priorities as key. For example:\npriorities = dict((n, i) for i, n in enumerate(names))\nnames_copy_sorted = sorted(names_copy, key=priorities.get)\n\nIf there are items in names_copy that aren't in names then you could adjust that with something like:\npriorities = dict((n, i) for i, n in enumerate(names))\ndefault = len(priorities)\ndef key(name): return priorities.get(name, default)\n\nnames_copy_sorted = sorted(names_copy, key=key)\n\nThis way the items in names_copy that are not in names are pushed to the back.\nBe aware that duplicates in names are dealt with differently: names.index uses the first occurrence as priority, while the priorities.get version uses the last.\n"
] | [
0
] | [
"\nFirst we have a List that contains duplicates:\nCreate a dictionary, using the List items as keys. This will automatically remove any duplicates because dictionaries cannot have duplicate keys.\nThen, convert the dictionary back into a list:\nNow we have a List without any duplicates, and it has the same order as the original List.\n\nI hope this helps.\n"
] | [
-2
] | [
"python",
"python_3.x",
"sorting"
] | stackoverflow_0074673707_python_python_3.x_sorting.txt |
Q:
Remove duplicates from groupBy
I would like to find out how many Users have Swipes per day without duplicates of user_id within group.
So if a User has swiped multiple times on a day, I want the User only show once per group (per day). I am not really interested in the actual Swipes but rather in the swipe count per day.
I tried:
Swipe::all()->groupBy(function($item){ return $item->created_at->format('d-M-y'); })->unique('user_id')
A:
To remove duplicates from the groupBy, you can use the distinct() method in combination with the groupBy() method. This will group the Swipes by day, and then only include distinct user_id values in each group:
Swipe::all()->groupBy(function($item){ return $item->created_at->format('d-M-y'); })->distinct('user_id')
Alternatively, you can use the distinct() method with a callback function to specify which columns to consider when determining uniqueness:
Swipe::all()->distinct(function ($item) {
return $item->created_at->format('d-M-y') . '-' . $item->user_id;
})
This will group the Swipes by day and user_id, and only include distinct combinations of these values in the result. You can then use the count() method to get the number of unique Swipes per day.
Swipe::all()->distinct(function ($item) {
return $item->created_at->format('d-M-y') . '-' . $item->user_id;
})->count();
A:
To remove duplicate data, you can use unique().
I create an example for you.
I have dummy data like
.
So you want the result is data grouped by created_at and on every date return how many users swipe it but without duplicate user?
The code should be like:
$collect = Swipe::all()->groupBy(function($data){
return $item->created_at->format('d-M-y');
})->transform(function($dataGrouped,$date){
return [
$date => $dataGrouped->unique('user_id')
];
});
The result will be like:
| Remove duplicates from groupBy | I would like to find out how many Users have Swipes per day without duplicates of user_id within group.
So if a User has swiped multiple times on a day, I want the User only show once per group (per day). I am not really interested in the actual Swipes but rather in the swipe count per day.
I tried:
Swipe::all()->groupBy(function($item){ return $item->created_at->format('d-M-y'); })->unique('user_id')
| [
"To remove duplicates from the groupBy, you can use the distinct() method in combination with the groupBy() method. This will group the Swipes by day, and then only include distinct user_id values in each group:\nSwipe::all()->groupBy(function($item){ return $item->created_at->format('d-M-y'); })->distinct('user_id')\n\nAlternatively, you can use the distinct() method with a callback function to specify which columns to consider when determining uniqueness:\nSwipe::all()->distinct(function ($item) {\nreturn $item->created_at->format('d-M-y') . '-' . $item->user_id;\n})\n\nThis will group the Swipes by day and user_id, and only include distinct combinations of these values in the result. You can then use the count() method to get the number of unique Swipes per day.\nSwipe::all()->distinct(function ($item) {\nreturn $item->created_at->format('d-M-y') . '-' . $item->user_id;\n})->count();\n\n",
"To remove duplicate data, you can use unique().\nI create an example for you.\nI have dummy data like\n.\nSo you want the result is data grouped by created_at and on every date return how many users swipe it but without duplicate user?\nThe code should be like:\n $collect = Swipe::all()->groupBy(function($data){\n return $item->created_at->format('d-M-y');\n })->transform(function($dataGrouped,$date){\n return [\n $date => $dataGrouped->unique('user_id')\n ];\n });\n\nThe result will be like:\n\n"
] | [
0,
0
] | [] | [] | [
"laravel"
] | stackoverflow_0074677103_laravel.txt |
Q:
Flink task manager managed memory used is showing zero
I am trying to tune memory configuration for my flink job deployed using FlinkOperator. Following are the memory settings I am using. I am configuring only Total memory as mentioned in this doc.
https://nightlies.apache.org/flink/flink-docs-master/docs/deployment/memory/mem_setup_tm/
taskmanager.memory.process.size: "8000m"
taskmanager.memory.task.off-heap.size: "500m"
taskmanager.memory.jvm-metaspace.size: "250m"
When the job starts processing, the metrics show that flink_taskmanager_Status_Flink_Memory_Managed_Used is always ZERO.
where flink_taskmanager_Status_Flink_Memory_Managed_Total is set to 5G.
Is this configuration fine ? (edited)
A:
It seems to me that the memory configuration for your Flink job is not correct. The memory settings you are using only define the total memory available to the Flink task manager, but do not specify how this memory should be used.
You need to specify the amount of memory that should be used for different purposes, such as the JVM heap, off-heap memory, and managed memory. You can do this by setting the following configuration options:
taskmanager.memory.process.size: This option defines the total memory available to the Flink task manager process. It should be set to a value that is larger than the sum of the other memory settings.
taskmanager.memory.jvm-heap.size: This option defines the amount of memory that should be allocated to the JVM heap. This memory is used by the Flink runtime and should be large enough to accommodate the needs of your Flink job.
taskmanager.memory.task.off-heap.size: This option defines the amount of off-heap memory that should be allocated for each task in the Flink job. This memory is used for data structures and intermediate results that cannot be stored on the JVM heap.
taskmanager.memory.jvm-metaspace.size: This option defines the amount of memory that should be allocated to the JVM metaspace. This memory is used for class metadata and should be set to a value that is appropriate for your Flink job.
In addition to these memory settings, you also need to set the taskmanager.memory.managed.size option to define the amount of managed memory that should be allocated for each task in the Flink job
| Flink task manager managed memory used is showing zero | I am trying to tune memory configuration for my flink job deployed using FlinkOperator. Following are the memory settings I am using. I am configuring only Total memory as mentioned in this doc.
https://nightlies.apache.org/flink/flink-docs-master/docs/deployment/memory/mem_setup_tm/
taskmanager.memory.process.size: "8000m"
taskmanager.memory.task.off-heap.size: "500m"
taskmanager.memory.jvm-metaspace.size: "250m"
When the job starts processing, the metrics show that flink_taskmanager_Status_Flink_Memory_Managed_Used is always ZERO.
where flink_taskmanager_Status_Flink_Memory_Managed_Total is set to 5G.
Is this configuration fine ? (edited)
| [
"It seems to me that the memory configuration for your Flink job is not correct. The memory settings you are using only define the total memory available to the Flink task manager, but do not specify how this memory should be used.\nYou need to specify the amount of memory that should be used for different purposes, such as the JVM heap, off-heap memory, and managed memory. You can do this by setting the following configuration options:\n\ntaskmanager.memory.process.size: This option defines the total memory available to the Flink task manager process. It should be set to a value that is larger than the sum of the other memory settings.\ntaskmanager.memory.jvm-heap.size: This option defines the amount of memory that should be allocated to the JVM heap. This memory is used by the Flink runtime and should be large enough to accommodate the needs of your Flink job.\ntaskmanager.memory.task.off-heap.size: This option defines the amount of off-heap memory that should be allocated for each task in the Flink job. This memory is used for data structures and intermediate results that cannot be stored on the JVM heap.\ntaskmanager.memory.jvm-metaspace.size: This option defines the amount of memory that should be allocated to the JVM metaspace. This memory is used for class metadata and should be set to a value that is appropriate for your Flink job.\n\nIn addition to these memory settings, you also need to set the taskmanager.memory.managed.size option to define the amount of managed memory that should be allocated for each task in the Flink job\n"
] | [
2
] | [] | [] | [
"apache_flink",
"flink_streaming"
] | stackoverflow_0074677189_apache_flink_flink_streaming.txt |
Q:
How to get larger doubles in Javascript
I am trying to caculate pi to a large amount of decimal places using the Gauss–Legendre algorithm as seen below
However, it only gives back around 15 digits of pi. Apparently this is because Mathematical operations in Javascript are performed using 64-bit floating point values and 16 digits of precision is right around the limit of what they can represent accurately.
This is my code
let a = 1,
b = 1 / Math.sqrt(2),
t = 1 / 4,
p = 1;
let i = 0;
while (a - b < 3) {
i++;
let an = (a + b) / 2;
b = Math.sqrt(a * b);
t = t - p * (a - an) ** 2;
p = 2 * p;
a = an;
if (i == 100) break;
let pi = (a + b) ** 2 / (4 * t);
console.log(pi);
}
I was wondering if there was any work around to get javascript to return more digits of pi.
Thanks in Advance
A:
Here's an interpretation using Decimal.js, with a desired precision of 150 digits of PI... (Note that "Full page" mode of "Run code snippet" provides a better review of the results.)
<script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/10.4.2/decimal.min.js"></script>
<script>
desiredPiDigits = 150;
Decimal.precision = desiredPiDigits + 5;
let desiredPiPrecision = new Decimal( 1 ).div( 10 ** desiredPiDigits );
let maxIterations = 50;
let a = new Decimal( 1 ),
b = new Decimal( 1 ).div( Decimal.sqrt( 2 ) ),
t = new Decimal( 0.25 ),
p = new Decimal( 1 );
let i = maxIterations;
while ( desiredPiPrecision.lt( a.sub( b ).abs() ) ) {
let an = a.add( b ).div( 2 );
b = a.mul( b ).sqrt();
t = t.sub( p.mul( a.sub( an ).pow( 2 ) ) );
p = p.mul( 2 );
a = an;
let pi = a.add( b ).pow( 2 ).div( t.mul( 4 ) );
console.log( pi.toString().slice( 0, desiredPiDigits + 1 ) );
if (--i === 0) break;
}
</script>
| How to get larger doubles in Javascript | I am trying to caculate pi to a large amount of decimal places using the Gauss–Legendre algorithm as seen below
However, it only gives back around 15 digits of pi. Apparently this is because Mathematical operations in Javascript are performed using 64-bit floating point values and 16 digits of precision is right around the limit of what they can represent accurately.
This is my code
let a = 1,
b = 1 / Math.sqrt(2),
t = 1 / 4,
p = 1;
let i = 0;
while (a - b < 3) {
i++;
let an = (a + b) / 2;
b = Math.sqrt(a * b);
t = t - p * (a - an) ** 2;
p = 2 * p;
a = an;
if (i == 100) break;
let pi = (a + b) ** 2 / (4 * t);
console.log(pi);
}
I was wondering if there was any work around to get javascript to return more digits of pi.
Thanks in Advance
| [
"Here's an interpretation using Decimal.js, with a desired precision of 150 digits of PI... (Note that \"Full page\" mode of \"Run code snippet\" provides a better review of the results.)\n\n\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/decimal.js/10.4.2/decimal.min.js\"></script>\n\n<script>\n\ndesiredPiDigits = 150;\nDecimal.precision = desiredPiDigits + 5;\n\nlet desiredPiPrecision = new Decimal( 1 ).div( 10 ** desiredPiDigits );\nlet maxIterations = 50;\n\nlet a = new Decimal( 1 ),\n b = new Decimal( 1 ).div( Decimal.sqrt( 2 ) ),\n t = new Decimal( 0.25 ),\n p = new Decimal( 1 );\n\nlet i = maxIterations;\nwhile ( desiredPiPrecision.lt( a.sub( b ).abs() ) ) {\n\n let an = a.add( b ).div( 2 );\n b = a.mul( b ).sqrt();\n t = t.sub( p.mul( a.sub( an ).pow( 2 ) ) );\n p = p.mul( 2 );\n\n a = an;\n\n let pi = a.add( b ).pow( 2 ).div( t.mul( 4 ) );\n console.log( pi.toString().slice( 0, desiredPiDigits + 1 ) );\n \n if (--i === 0) break;\n}\n\n</script>\n\n\n\n"
] | [
1
] | [] | [] | [
"algorithm",
"javascript",
"pi"
] | stackoverflow_0074675345_algorithm_javascript_pi.txt |
Q:
In Android Studio, can we store a history point?
it's like when you write code A, you markup this state, then you go on editing code A into code B (making lots of steps) and when you want to come back to state A, it's still available?
A:
Right click the file which you want to revert and choose Local History and check the history of changes made to the file and revert back to whatever you needed.
Refer the image attached below
A:
“Version Control System” (VCS)
subversion with Android studio
github, bitbucket (git)
github example
excellent github guide
bitbucket example
svn (subversion)
mercurial (hg)
local
A:
While the best method is using a revision control system, it is also possible to roll back changes using the built in Local History feature of Android Studio.
To revert to an older version of a file from within Android Studio just select Local History from the context menu for any text file in your project. This displays the history of edits for the given file and provides a differences view to compare versions and revert to an older version.
A:
If you can't find local history on Android Studio try this:
press on VCS menu once (you will not see it)
press on VCS again you should see it at the top option.
At least this is how it's working now in mac (Android Studio ~2.2)
A:
in Android studio chipmunk
go to:
git-> vcs operations-> show history.
You will find mentioned by BrentM built-in Local History feature of Android Studio
| In Android Studio, can we store a history point? | it's like when you write code A, you markup this state, then you go on editing code A into code B (making lots of steps) and when you want to come back to state A, it's still available?
| [
"Right click the file which you want to revert and choose Local History and check the history of changes made to the file and revert back to whatever you needed.\nRefer the image attached below\n\n",
"“Version Control System” (VCS)\nsubversion with Android studio\n\ngithub, bitbucket (git) \ngithub example \nexcellent github guide\nbitbucket example\nsvn (subversion) \nmercurial (hg) \nlocal \n\n",
"While the best method is using a revision control system, it is also possible to roll back changes using the built in Local History feature of Android Studio.\nTo revert to an older version of a file from within Android Studio just select Local History from the context menu for any text file in your project. This displays the history of edits for the given file and provides a differences view to compare versions and revert to an older version.\n",
"If you can't find local history on Android Studio try this:\n\npress on VCS menu once (you will not see it)\npress on VCS again you should see it at the top option. \n\nAt least this is how it's working now in mac (Android Studio ~2.2)\n",
"in Android studio chipmunk\ngo to:\ngit-> vcs operations-> show history.\nYou will find mentioned by BrentM built-in Local History feature of Android Studio\n"
] | [
4,
2,
1,
0,
0
] | [] | [] | [
"android",
"android_studio",
"history"
] | stackoverflow_0031757313_android_android_studio_history.txt |
Q:
Chrome not loading (or redirecting) Vimeo direct video URLs
Context:
So I built a website for a company, and it uses Vimeo to host all it's videos. We use the "direct download" URL's Vimeo Pro provides to play a MP4 video using the native <video> element.
You can see the site here.
For example, a lot of images on this site show a video on hover, on almost all pages. Those videos are what I am describing. It is not the video's shown with player controls, those are proper Vimeo iFrame embeds.
The problem:
After browsing around the site for a little (navigating to about 4-5 different pages should trigger it), those MP4 videos stop loading, but only in Chrome. I've tested it across a lot of computers in my company, both in office and remote. I am using Chrome for Mac, Version 107.0.5304.121.
What does "stop loading" mean? I mean, that if you copy the video src URL from the site source code and open it in a new browser, it never loads... But if you use that same URL in an Incognito tab, it will load and play. You can also see it happening in the Network tab of DevTools.
From best I can tell, the Vimeo URL actually get redirected to a akamaized.net URL, and that redirect stops working, perhaps by some sort of rate limit or cookie tracking?
Here is a video recording showing the issue:
https://www.dropbox.com/s/fnp0oaoaeb9s54i/New%20Recording%20-%2011_29_2022%2C%2010_32_58%20AM.webm?dl=0
The code that is used to display those videos is like this:
<video
src="https://player.vimeo.com/progressive_redirect/playback/759618180/rendition/1080p/file.mp4?loc=external&signature=73c3773c3830e6ef73af25b0c88e33c411a79a365497ef56519b5f18a963b523"
loop="loop"
autoplay="autoplay"
playsinline="true"
disablepictureinpicture="true"
preload="none"
muted=""
>
</video>
And then using an IntersectionObserver when the video is in-view I load() the video, and on hover I play() the video.
Vimeo support says they are "unable to replicate the issue" which given the multiple people in my company (and the client) that can see this, I think Vimeo support is wrong.
Attempted solutions:
I tried setting crossorigin="anonymous" on each video, and that had no effect.
I implemented the Intersection Observer and preload="none" code to be more efficient with what videos get loaded. This helped with bandwidth usage, but didn't solve the Vimeo video's not loading/redirecting.
A:
Here is what happening:
video.play() starts loading video content asynchronously.
video.pause() interrupts video loading because it is not ready yet.
video.play() rejects asynchronously loudly.
here is a proper way to implement paly/pause using promise
<video id="video" preload="none" src="https://example.com/file.mp4"></video>
<script>
// Show loading animation.
var playPromise = video.play();
if (playPromise !== undefined) {
playPromise.then(_ => {
// Automatic playback started!
// Show playing UI.
// We can now safely pause video...
video.pause();
})
.catch(error => {
// Auto-play was prevented
// Show paused UI.
});
}
</script>
Also, be aware of this Chromium Bug
| Chrome not loading (or redirecting) Vimeo direct video URLs | Context:
So I built a website for a company, and it uses Vimeo to host all it's videos. We use the "direct download" URL's Vimeo Pro provides to play a MP4 video using the native <video> element.
You can see the site here.
For example, a lot of images on this site show a video on hover, on almost all pages. Those videos are what I am describing. It is not the video's shown with player controls, those are proper Vimeo iFrame embeds.
The problem:
After browsing around the site for a little (navigating to about 4-5 different pages should trigger it), those MP4 videos stop loading, but only in Chrome. I've tested it across a lot of computers in my company, both in office and remote. I am using Chrome for Mac, Version 107.0.5304.121.
What does "stop loading" mean? I mean, that if you copy the video src URL from the site source code and open it in a new browser, it never loads... But if you use that same URL in an Incognito tab, it will load and play. You can also see it happening in the Network tab of DevTools.
From best I can tell, the Vimeo URL actually get redirected to a akamaized.net URL, and that redirect stops working, perhaps by some sort of rate limit or cookie tracking?
Here is a video recording showing the issue:
https://www.dropbox.com/s/fnp0oaoaeb9s54i/New%20Recording%20-%2011_29_2022%2C%2010_32_58%20AM.webm?dl=0
The code that is used to display those videos is like this:
<video
src="https://player.vimeo.com/progressive_redirect/playback/759618180/rendition/1080p/file.mp4?loc=external&signature=73c3773c3830e6ef73af25b0c88e33c411a79a365497ef56519b5f18a963b523"
loop="loop"
autoplay="autoplay"
playsinline="true"
disablepictureinpicture="true"
preload="none"
muted=""
>
</video>
And then using an IntersectionObserver when the video is in-view I load() the video, and on hover I play() the video.
Vimeo support says they are "unable to replicate the issue" which given the multiple people in my company (and the client) that can see this, I think Vimeo support is wrong.
Attempted solutions:
I tried setting crossorigin="anonymous" on each video, and that had no effect.
I implemented the Intersection Observer and preload="none" code to be more efficient with what videos get loaded. This helped with bandwidth usage, but didn't solve the Vimeo video's not loading/redirecting.
| [
"Here is what happening:\n\nvideo.play() starts loading video content asynchronously.\nvideo.pause() interrupts video loading because it is not ready yet.\nvideo.play() rejects asynchronously loudly.\n\nhere is a proper way to implement paly/pause using promise\n<video id=\"video\" preload=\"none\" src=\"https://example.com/file.mp4\"></video>\n \n<script>\n // Show loading animation.\n var playPromise = video.play();\n \n if (playPromise !== undefined) {\n playPromise.then(_ => {\n // Automatic playback started!\n // Show playing UI.\n // We can now safely pause video...\n video.pause();\n })\n .catch(error => {\n // Auto-play was prevented\n // Show paused UI.\n });\n }\n</script>\n\nAlso, be aware of this Chromium Bug\n"
] | [
0
] | [] | [] | [
"akamai",
"google_chrome",
"html5_video",
"javascript",
"vimeo"
] | stackoverflow_0074635511_akamai_google_chrome_html5_video_javascript_vimeo.txt |
Q:
Custom trusted types in Angular project
I have a spot in my Angular application where I do not want the Angular sanitizer to sanitize my content. My goal is to create a custom trusted type policy in my angular project. But I could not figure out what is the best practice to create one, store them and use them in code later.
I know it works by using (window as any)
And doing I was doing it in a separate trusted-types-service:
export class TrustedTypesService {
readonly fooPolicy: any;
constructor() {
this.fooPolicy = (window as any).trustedTypes.createPolicy('foo', (bar) => {
// ideally some sanitizing by e.g. DOM Purify
return bar;
});
}
}
But is this the right and best way to do it?
I'd appreciate any help. Thank you :)
A:
Yes, creating a custom trusted type policy and storing it in a service is the best way to do it in an Angular application. This approach allows you to create a single source of truth for all of your trusted type policies. This service can then be injected into any components that need to use the trusted types.
You can also use the same service to create and store multiple trusted type policies. This will allow you to have different policies for different types of data. For example, you could have one policy for sanitizing HTML, one for sanitizing URLs, and one for sanitizing user input.
It's also important to note that you should always use DOM Purify or a similar library to actually sanitize the data. This will ensure that the data is properly sanitized before being returned.
Overall, the best practice for creating and using custom trusted type policies in an Angular application is to create a service to store the policies and inject that service into any components that need to use the trusted types. This will allow you to have a single source of truth for all of your trusted type policies and ensure that your data is properly sanitized.
A:
Trusted Types is a security feature introduced in Angular 9.0 that aims to prevent cross-site scripting (XSS) attacks. It does this by providing a strict API for creating, modifying, and sanitizing strings that are safe to use in different contexts.
Creating custom trusted types policies is a way to extend the default behavior of the Angular sanitizer to support specific needs in your application. The way you have implemented your custom policy in the TrustedTypesService looks correct, although it's worth noting that the trustedTypes property on the window object is only available if the TrustedTypesModule has been imported in your Angular app.
Here is an example of how you could use your custom fooPolicy in your Angular code:
import { TrustedTypesService } from './trusted-types-service';
@Component({
// ...
})
export class MyComponent {
constructor(private trustedTypesService: TrustedTypesService) {}
foo() {
const input = 'Some potentially unsafe string';
const safe = this.trustedTypesService.fooPolicy.createHTML(input);
// You can now safely use the "safe" string in your Angular templates
// without worrying about XSS attacks.
}
}
It's worth noting that the createPolicy method takes a second argument that specifies the type of the output of the policy. This can be either HTML, Script, ScriptURL, ResourceURL, or URL. In the example above, we have used the HTML type, which indicates that the policy creates trusted HTML strings.
Overall, the approach you have taken to creating a custom trusted type policy in your Angular app looks correct. However, it's important to understand the limitations of this approach and to use it wisely. In particular, you should be aware that a custom policy does not automatically guarantee the security of your application - it's up to you to ensure that the policy correctly sanitizes the input strings and makes them safe to use in your Angular templates.
| Custom trusted types in Angular project | I have a spot in my Angular application where I do not want the Angular sanitizer to sanitize my content. My goal is to create a custom trusted type policy in my angular project. But I could not figure out what is the best practice to create one, store them and use them in code later.
I know it works by using (window as any)
And doing I was doing it in a separate trusted-types-service:
export class TrustedTypesService {
readonly fooPolicy: any;
constructor() {
this.fooPolicy = (window as any).trustedTypes.createPolicy('foo', (bar) => {
// ideally some sanitizing by e.g. DOM Purify
return bar;
});
}
}
But is this the right and best way to do it?
I'd appreciate any help. Thank you :)
| [
"Yes, creating a custom trusted type policy and storing it in a service is the best way to do it in an Angular application. This approach allows you to create a single source of truth for all of your trusted type policies. This service can then be injected into any components that need to use the trusted types.\nYou can also use the same service to create and store multiple trusted type policies. This will allow you to have different policies for different types of data. For example, you could have one policy for sanitizing HTML, one for sanitizing URLs, and one for sanitizing user input.\nIt's also important to note that you should always use DOM Purify or a similar library to actually sanitize the data. This will ensure that the data is properly sanitized before being returned.\nOverall, the best practice for creating and using custom trusted type policies in an Angular application is to create a service to store the policies and inject that service into any components that need to use the trusted types. This will allow you to have a single source of truth for all of your trusted type policies and ensure that your data is properly sanitized.\n",
"Trusted Types is a security feature introduced in Angular 9.0 that aims to prevent cross-site scripting (XSS) attacks. It does this by providing a strict API for creating, modifying, and sanitizing strings that are safe to use in different contexts.\nCreating custom trusted types policies is a way to extend the default behavior of the Angular sanitizer to support specific needs in your application. The way you have implemented your custom policy in the TrustedTypesService looks correct, although it's worth noting that the trustedTypes property on the window object is only available if the TrustedTypesModule has been imported in your Angular app.\nHere is an example of how you could use your custom fooPolicy in your Angular code:\nimport { TrustedTypesService } from './trusted-types-service';\n\n@Component({\n // ...\n})\nexport class MyComponent {\n constructor(private trustedTypesService: TrustedTypesService) {}\n\n foo() {\n const input = 'Some potentially unsafe string';\n const safe = this.trustedTypesService.fooPolicy.createHTML(input);\n // You can now safely use the \"safe\" string in your Angular templates\n // without worrying about XSS attacks.\n }\n}\n\n\nIt's worth noting that the createPolicy method takes a second argument that specifies the type of the output of the policy. This can be either HTML, Script, ScriptURL, ResourceURL, or URL. In the example above, we have used the HTML type, which indicates that the policy creates trusted HTML strings.\nOverall, the approach you have taken to creating a custom trusted type policy in your Angular app looks correct. However, it's important to understand the limitations of this approach and to use it wisely. In particular, you should be aware that a custom policy does not automatically guarantee the security of your application - it's up to you to ensure that the policy correctly sanitizes the input strings and makes them safe to use in your Angular templates.\n"
] | [
1,
1
] | [] | [] | [
"angular",
"content_security_policy",
"trusted_types",
"websecurity"
] | stackoverflow_0074677473_angular_content_security_policy_trusted_types_websecurity.txt |
Q:
Spark scala UDF complains NoClassDefFoundError
I am trying to write a simple spark UDF like this. When I test it in databricks notebook on a spark version 10.4.x-scala2.12. The same code works just fine. When I run this in a packaged jar and submit to databricks on same spark version it results in an exception like this,
Exception: at spark.sql(sql_stat).show(false)
Job aborted due to stage failure.
Caused by: NoClassDefFoundError: Could not initialize class com.test.TestClass$
:
:
at com.test.TestClass$.$anonfun$main$5(TestClass.scala:13)
Code:
object Test{
def main(args: Array[String]): Unit = {
val udf_lambda =(id: Int) => {
if (id%2==0)
"group A"
else
"group B"
}
spark.udf.register("udf_lambda", udf_lambda)
val sql_stat = "select udf_lambda(id) as idv2 from hive_table"
spark.sql(sql_stat).show(false)
}
}
Any ideas on why this might be or how to troubleshoot it? I have the jar working just fine when i change the query to one without UDF. Simple query like select id as idv2 from hive_table just displays data form table. It
A:
Method udf_lambda needs to be in a place where it can be serialized. The easiest way to do so is by placing it directly in an object.
object Test{
val udf_lambda =(id: Int) => {
if (id%2==0)
"group A"
else
"group B"
}
def main(args: Array[String]): Unit = {
spark.udf.register("udf_lambda", udf_lambda)
val sql_stat = "select udf_lambda(id) as idv2 from hive_table"
spark.sql(sql_stat).show(false)
}
}
| Spark scala UDF complains NoClassDefFoundError | I am trying to write a simple spark UDF like this. When I test it in databricks notebook on a spark version 10.4.x-scala2.12. The same code works just fine. When I run this in a packaged jar and submit to databricks on same spark version it results in an exception like this,
Exception: at spark.sql(sql_stat).show(false)
Job aborted due to stage failure.
Caused by: NoClassDefFoundError: Could not initialize class com.test.TestClass$
:
:
at com.test.TestClass$.$anonfun$main$5(TestClass.scala:13)
Code:
object Test{
def main(args: Array[String]): Unit = {
val udf_lambda =(id: Int) => {
if (id%2==0)
"group A"
else
"group B"
}
spark.udf.register("udf_lambda", udf_lambda)
val sql_stat = "select udf_lambda(id) as idv2 from hive_table"
spark.sql(sql_stat).show(false)
}
}
Any ideas on why this might be or how to troubleshoot it? I have the jar working just fine when i change the query to one without UDF. Simple query like select id as idv2 from hive_table just displays data form table. It
| [
"Method udf_lambda needs to be in a place where it can be serialized. The easiest way to do so is by placing it directly in an object.\nobject Test{\n val udf_lambda =(id: Int) => {\n if (id%2==0)\n \"group A\"\n else\n \"group B\"\n }\n\n def main(args: Array[String]): Unit = { \n spark.udf.register(\"udf_lambda\", udf_lambda)\n val sql_stat = \"select udf_lambda(id) as idv2 from hive_table\"\n spark.sql(sql_stat).show(false)\n }\n }\n\n"
] | [
0
] | [] | [] | [
"apache_spark",
"databricks",
"databricks_sql",
"scala",
"user_defined_functions"
] | stackoverflow_0074664194_apache_spark_databricks_databricks_sql_scala_user_defined_functions.txt |
Q:
Why doesn't read conditions?
I did use debug and the price range doesn't read from the condition.
if (cost <= 500.00)
Also i tried 'where' instead of 'select' By the way i can use another methods.
Thanks for any help
`
public T CostRange(int cost)
{
var price = GetByCost(cost);
if (price != null)
{
if (cost <= 500.00)
{
_context.Set<T>().Select(x => x.Cost <= 500).ToList();
}
if (cost > 500 || cost <= 2000)
{
_context.Set<T>().Select(x => x.Cost > 500 && x.Cost <= 2000).ToList();
}
if (cost > 2000 || cost <= 5000)
{
_context.Set<T>().Select(x => x.Cost > 2000 && x.Cost <= 5000).ToList();
}
if (cost > 5000 || cost <= 10000)
{
_context.Set<T>().Select(x => x.Cost > 5000 && x.Cost <= 10000).ToList();
}
if (cost > 10000)
{
_context.Set<T>().Select(x => x.Cost > 10000).ToList();
}
}
return price;
}
`
I want to get products in price range.By the way I can reach the cost value with
'_context.Set().Find(cost); or GetByCost(cost);
A:
public T CostRange(int cost)
{
var price = GetByCost(cost);
if (price != null)
{
if (cost <= 500.00)
{
_context.Set<T>().Select(x => x.Cost <= 500).ToList();
}
else if (cost > 500 && cost <= 2000)
{
_context.Set<T>().Select(x => x.Cost > 500 && x.Cost <= 2000).ToList();
}
else if (cost > 2000 && cost <= 5000)
{
_context.Set<T>().Select(x => x.Cost > 2000 && x.Cost <= 5000).ToList();
}
else if (cost > 5000 && cost <= 10000)
{
_context.Set<T>().Select(x => x.Cost > 5000 && x.Cost <= 10000).ToList();
}
else if (cost > 10000)
{
_context.Set<T>().Select(x => x.Cost > 10000).ToList();
}
}
return price;
}
| Why doesn't read conditions? | I did use debug and the price range doesn't read from the condition.
if (cost <= 500.00)
Also i tried 'where' instead of 'select' By the way i can use another methods.
Thanks for any help
`
public T CostRange(int cost)
{
var price = GetByCost(cost);
if (price != null)
{
if (cost <= 500.00)
{
_context.Set<T>().Select(x => x.Cost <= 500).ToList();
}
if (cost > 500 || cost <= 2000)
{
_context.Set<T>().Select(x => x.Cost > 500 && x.Cost <= 2000).ToList();
}
if (cost > 2000 || cost <= 5000)
{
_context.Set<T>().Select(x => x.Cost > 2000 && x.Cost <= 5000).ToList();
}
if (cost > 5000 || cost <= 10000)
{
_context.Set<T>().Select(x => x.Cost > 5000 && x.Cost <= 10000).ToList();
}
if (cost > 10000)
{
_context.Set<T>().Select(x => x.Cost > 10000).ToList();
}
}
return price;
}
`
I want to get products in price range.By the way I can reach the cost value with
'_context.Set().Find(cost); or GetByCost(cost);
| [
" public T CostRange(int cost)\n {\n var price = GetByCost(cost);\n if (price != null)\n {\n\n if (cost <= 500.00)\n {\n _context.Set<T>().Select(x => x.Cost <= 500).ToList();\n\n }\n \n else if (cost > 500 && cost <= 2000)\n {\n _context.Set<T>().Select(x => x.Cost > 500 && x.Cost <= 2000).ToList();\n\n }\n else if (cost > 2000 && cost <= 5000)\n {\n _context.Set<T>().Select(x => x.Cost > 2000 && x.Cost <= 5000).ToList();\n\n }\n else if (cost > 5000 && cost <= 10000)\n { \n _context.Set<T>().Select(x => x.Cost > 5000 && x.Cost <= 10000).ToList();\n\n }\n else if (cost > 10000)\n {\n _context.Set<T>().Select(x => x.Cost > 10000).ToList();\n }\n }\n \n return price;\n }\n\n"
] | [
0
] | [] | [] | [
"asp.net",
"asp.net_web_api",
"c#"
] | stackoverflow_0074667209_asp.net_asp.net_web_api_c#.txt |
Q:
How to iterate a queue multiple times until all elements are removed in Java?
I have created a queue containing custom objects called Card. I want to iterate through the queue to show every card to the user. If the user wants the card to appear again, the card must be shown again once all the other cards have been shown (so the card must go to the end of the queue). This must repeat endlessly until the user decides that the card must not be shown again.
How can I do that properly ?
I have tried to add the card at the end of the queue when the user wants the card to appear again using :
learningQueue.add(this.card);
But then when I use :
cardIterator.next();
I get a java.util.ConcurrentModificationException.
A:
If you use Iterator, the object card should not be modified. Otherwise, it will throw ConcurrentModificationException. And you can read source code to figure out that problem.
I don't suggest you using Iterator. Since you have used queue, why not use Queue.peek(),Queue.poll() and Queue.add().
public void test() {
Queue<User> userDeque = new ArrayDeque<>();
userDeque.add(new User(1L, "nancy"));
userDeque.add(new User(2L, "mike"));
userDeque.add(new User(3L, "hopkins"));
while (userDeque.peek() != null) {
User poll = userDeque.poll();
System.out.println(poll);
// condition
if (poll.getId() < 2) {
userDeque.add(poll);
}
}
}
@Data
@AllArgsConstructor
public class User {
private Long id;
private String name;
}
| How to iterate a queue multiple times until all elements are removed in Java? | I have created a queue containing custom objects called Card. I want to iterate through the queue to show every card to the user. If the user wants the card to appear again, the card must be shown again once all the other cards have been shown (so the card must go to the end of the queue). This must repeat endlessly until the user decides that the card must not be shown again.
How can I do that properly ?
I have tried to add the card at the end of the queue when the user wants the card to appear again using :
learningQueue.add(this.card);
But then when I use :
cardIterator.next();
I get a java.util.ConcurrentModificationException.
| [
"If you use Iterator, the object card should not be modified. Otherwise, it will throw ConcurrentModificationException. And you can read source code to figure out that problem.\nI don't suggest you using Iterator. Since you have used queue, why not use Queue.peek(),Queue.poll() and Queue.add().\npublic void test() {\n Queue<User> userDeque = new ArrayDeque<>();\n userDeque.add(new User(1L, \"nancy\"));\n userDeque.add(new User(2L, \"mike\"));\n userDeque.add(new User(3L, \"hopkins\"));\n\n while (userDeque.peek() != null) {\n User poll = userDeque.poll();\n System.out.println(poll);\n // condition\n if (poll.getId() < 2) {\n userDeque.add(poll);\n }\n }\n}\n\n@Data\n@AllArgsConstructor\npublic class User {\n private Long id;\n private String name;\n}\n\n"
] | [
0
] | [] | [] | [
"iterator",
"java",
"loops",
"queue"
] | stackoverflow_0074672303_iterator_java_loops_queue.txt |
Q:
Adruino ide doesn't want to install third-party libs
Im newbie in Arduino and just wanna start from scratch... I'm trying to print on lcd display words hello world via i2c adapter. But for some reason when i already have installed library, and try to #include instance from this lib, ide tolds that there's no such file or directory. I tried different ways to install this lib, from library manager to manual installation, or download another library. I dont know why but this ide doesn't want to use any third-party libs except built-in.
btw: I use windows 11 if it is important
A:
If the Arduino IDE is not able to find the library you are trying to include, it is likely because the library is not installed in the correct location. The Arduino IDE looks for libraries in specific directories on your computer, and if the library you are trying to include is not installed in one of these directories, the IDE will not be able to find it.
You need to make sure that the library you are trying to include is installed in the correct location. The Arduino IDE looks for libraries in the following directories:
The libraries directory in your Arduino sketchbook directory
The libraries directory inside the Arduino installation directory
The libraries directory inside the Arduino core directory for your selected board
To install a library in the correct location, you can use the Arduino Library Manager (available from the Sketch > Include Library menu in the Arduino IDE). This will automatically install the library in the correct location and make it available for use in your sketches.
You can also manually install a library by copying its files to one of the directories listed above. To do this, you need to download the library as a ZIP file, unzip it, and then copy the resulting directory to one of the directories listed above. Make sure to copy the entire library directory, not just individual files from the library.
Once you have installed the library in the correct location, you should be able to include it in your sketch using the #include directive, as in:
#include <my_library.h>
You can verify that the library is installed and available to the Arduino IDE by checking the Sketch > Include Library menu in the IDE. The library you installed should be listed in this menu, and you should be able to select it to include it in your sketch
EDIT
It sounds like the library is not being installed properly. Here are some things you can try to troubleshoot the issue:
Try manually installing the library by downloading it from the library's website and extracting it to the libraries folder in your Arduino sketchbook directory. This directory is usually located at Documents/Arduino/libraries.
Make sure you are using the latest version of the library and that it is compatible with your version of Arduino.
If you are using the Arduino Library Manager to install the library, make sure you are connected to the internet and that the library is available on the Library Manager.
If none of these solutions work, try reinstalling the Arduino IDE and restarting your computer before trying again.
| Adruino ide doesn't want to install third-party libs | Im newbie in Arduino and just wanna start from scratch... I'm trying to print on lcd display words hello world via i2c adapter. But for some reason when i already have installed library, and try to #include instance from this lib, ide tolds that there's no such file or directory. I tried different ways to install this lib, from library manager to manual installation, or download another library. I dont know why but this ide doesn't want to use any third-party libs except built-in.
btw: I use windows 11 if it is important
| [
"If the Arduino IDE is not able to find the library you are trying to include, it is likely because the library is not installed in the correct location. The Arduino IDE looks for libraries in specific directories on your computer, and if the library you are trying to include is not installed in one of these directories, the IDE will not be able to find it.\nYou need to make sure that the library you are trying to include is installed in the correct location. The Arduino IDE looks for libraries in the following directories:\n\nThe libraries directory in your Arduino sketchbook directory\nThe libraries directory inside the Arduino installation directory\nThe libraries directory inside the Arduino core directory for your selected board\n\nTo install a library in the correct location, you can use the Arduino Library Manager (available from the Sketch > Include Library menu in the Arduino IDE). This will automatically install the library in the correct location and make it available for use in your sketches.\nYou can also manually install a library by copying its files to one of the directories listed above. To do this, you need to download the library as a ZIP file, unzip it, and then copy the resulting directory to one of the directories listed above. Make sure to copy the entire library directory, not just individual files from the library.\nOnce you have installed the library in the correct location, you should be able to include it in your sketch using the #include directive, as in:\n#include <my_library.h>\n\nYou can verify that the library is installed and available to the Arduino IDE by checking the Sketch > Include Library menu in the IDE. The library you installed should be listed in this menu, and you should be able to select it to include it in your sketch\nEDIT\nIt sounds like the library is not being installed properly. Here are some things you can try to troubleshoot the issue:\n\nTry manually installing the library by downloading it from the library's website and extracting it to the libraries folder in your Arduino sketchbook directory. This directory is usually located at Documents/Arduino/libraries.\nMake sure you are using the latest version of the library and that it is compatible with your version of Arduino.\nIf you are using the Arduino Library Manager to install the library, make sure you are connected to the internet and that the library is available on the Library Manager.\nIf none of these solutions work, try reinstalling the Arduino IDE and restarting your computer before trying again.\n\n"
] | [
1
] | [] | [] | [
"arduino_ide"
] | stackoverflow_0074677469_arduino_ide.txt |
Q:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'backend')
I am experiencing the following error in my code: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'backend'). This error is occurring when I am trying to access the ‘backend’ property of an object, but it is returning as undefined. I have checked my code multiple times and cannot figure out why this is happening.
Here is the error:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'backend')
at Engine.moveData (engine.ts:426:1)
at DataStorage.get (backend.ts:55:1)
at MathBackendCPU.incRef (backend_cpu.ts:106:1)
at Object.reshape [as kernelFunc] (Reshape.ts:40:1)
at kernelFunc (engine.ts:646:1)
at engine.ts:712:1
at Engine.scopedRun (engine.ts:480:1)
at Engine.runKernelFunc (engine.ts:708:1)
at Engine.runKernel (engine.ts:553:1)
at reshape_ (reshape.ts:60:1)
Dependencies:
"@tensorflow/tfjs": "^4.1.0",
"@tensorflow/tfjs-converter": "^4.1.0",
"@tensorflow/tfjs-core": "^4.1.0",
"@tensorflow/tfjs-node": "^1.7.4",
If anyone has experienced this error or has any suggestions on how to fix it, please let me know.
A:
@tensorflow/tfjs-node is a bundle package of tjfs-core, tfjs-converter and others.
@tensorflow/tfjs is also a bundle package, but for browsers.
so you have dependency on TWO different bundles - of which there could be only one. and then you have MAJOR version incompatibility: v4 vs v1.
and on top of that you have individual packages like tfjs-core and tfjs-converter. really, this has no chance of working.
| Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'backend') | I am experiencing the following error in my code: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'backend'). This error is occurring when I am trying to access the ‘backend’ property of an object, but it is returning as undefined. I have checked my code multiple times and cannot figure out why this is happening.
Here is the error:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'backend')
at Engine.moveData (engine.ts:426:1)
at DataStorage.get (backend.ts:55:1)
at MathBackendCPU.incRef (backend_cpu.ts:106:1)
at Object.reshape [as kernelFunc] (Reshape.ts:40:1)
at kernelFunc (engine.ts:646:1)
at engine.ts:712:1
at Engine.scopedRun (engine.ts:480:1)
at Engine.runKernelFunc (engine.ts:708:1)
at Engine.runKernel (engine.ts:553:1)
at reshape_ (reshape.ts:60:1)
Dependencies:
"@tensorflow/tfjs": "^4.1.0",
"@tensorflow/tfjs-converter": "^4.1.0",
"@tensorflow/tfjs-core": "^4.1.0",
"@tensorflow/tfjs-node": "^1.7.4",
If anyone has experienced this error or has any suggestions on how to fix it, please let me know.
| [
"@tensorflow/tfjs-node is a bundle package of tjfs-core, tfjs-converter and others.\n@tensorflow/tfjs is also a bundle package, but for browsers.\nso you have dependency on TWO different bundles - of which there could be only one. and then you have MAJOR version incompatibility: v4 vs v1.\nand on top of that you have individual packages like tfjs-core and tfjs-converter. really, this has no chance of working.\n"
] | [
0
] | [] | [] | [
"javascript",
"tensorflow",
"tensorflow.js",
"typescript"
] | stackoverflow_0074674313_javascript_tensorflow_tensorflow.js_typescript.txt |
Q:
"The Fetch API is an experimental feature. This feature could change at any time" while installing a Nuxt3 app
I try to creat new nuxt app using fallowing command
npx nuxi init my-app
successfully creating new app with Nuxt 3.0 stable inside but i get this annoying response
Nuxi 3.0.0-rc.10 15:04:22
ERROR (node:35527) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
What confuses me is the version of Nuxi 3.0.0-rc.10 and the Error I belive it comes from node.
node - 18.12.1
npm - 8.19.2
git - 2.38.1
A:
First off, you should be running Nuxt 3.0.0 (stable version), not the RC.
Also, this is a warning hence something that you can omit. Especially because it is tied to Node v18 itself and not Vue/Nuxt. Some details on how to suppress the warning are available here: https://github.com/netlify/cli/issues/4608#issuecomment-1223696635
As for the warning, it is a common thing to have experimental features marked until they are fully stable. Here is the official source for that one.
| "The Fetch API is an experimental feature. This feature could change at any time" while installing a Nuxt3 app | I try to creat new nuxt app using fallowing command
npx nuxi init my-app
successfully creating new app with Nuxt 3.0 stable inside but i get this annoying response
Nuxi 3.0.0-rc.10 15:04:22
ERROR (node:35527) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
What confuses me is the version of Nuxi 3.0.0-rc.10 and the Error I belive it comes from node.
node - 18.12.1
npm - 8.19.2
git - 2.38.1
| [
"First off, you should be running Nuxt 3.0.0 (stable version), not the RC.\nAlso, this is a warning hence something that you can omit. Especially because it is tied to Node v18 itself and not Vue/Nuxt. Some details on how to suppress the warning are available here: https://github.com/netlify/cli/issues/4608#issuecomment-1223696635\nAs for the warning, it is a common thing to have experimental features marked until they are fully stable. Here is the official source for that one.\n"
] | [
1
] | [] | [] | [
"javascript",
"node.js",
"nuxt.js",
"nuxtjs3"
] | stackoverflow_0074677483_javascript_node.js_nuxt.js_nuxtjs3.txt |
Q:
displaying error products.map is not a function
this is my component file and when I run this code displaying error products.map is not a function.
A:
this means products is not an array , try console logging the products and see what it's returning .
else you can make it map through only if the products exist like this
products?.map
A:
The .map function is only available on array.
It looks like products isn't in the format you are expecting it to be (it is {} but you are expecting [])
| displaying error products.map is not a function | this is my component file and when I run this code displaying error products.map is not a function.
| [
"this means products is not an array , try console logging the products and see what it's returning .\nelse you can make it map through only if the products exist like this\nproducts?.map\n\n",
"The .map function is only available on array.\nIt looks like products isn't in the format you are expecting it to be (it is {} but you are expecting [])\n"
] | [
1,
0
] | [] | [] | [
"dictionary",
"reactjs",
"redux"
] | stackoverflow_0074677506_dictionary_reactjs_redux.txt |
Q:
How to deploy npm project to gh-pages
I'm trying to deploy a website to gh-pages using npm. I'm using blain HTML and CSS and asynchronous javascript. I haven't used any SPA framework (react or angular).
I'm currently using lite server for development purposes and gh-pages package.
I'm trying to deploy the src folder using the following command
npm run deploy
it fails because the build script is not specified.
my question is what should I write in the build script?
when I try to run npm run deploy it displays the following error
'src' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `src`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Amr\AppData\Roaming\npm-cache\_logs\2020-05-30T11_30_29_824Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] predeploy: `npm run build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] predeploy script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Amr\AppData\Roaming\npm-cache\_logs\2020-05-30T11_30_29_869Z-debug.log
in similar projects using react, the build script has the following react-scripts build
this is my package.json file
{
"name": "AmrAhmed",
"version": "1.0.0",
"description": "",
"main": "truffle.js",
"directories": {
"test": "test"
},
"scripts": {
"dev": "lite-server",
"test": "echo \"Error: no test specified\" && exit 1",
"build": "src",
"predeploy": "npm run build",
"deploy": "gh-pages -d src"
},
"author": "",
"license": "ISC",
"devDependencies": {
"gh-pages": "^3.0.0",
"lite-server": "^2.5.4"
}
}
election folder content
src folder content
A:
I found out that you don't need the build script or the pre-deploy script. they are unnecessary to be used, since my website is static, I can navigate directly to the build folder and it will work fine.
I have modified the config.json file to be as in the following
{
"name": "AmrAhmed",
"version": "1.0.0",
"description": "",
"main": "truffle.js",
"directories": {
"test": "test"
},
"scripts": {
"dev": "lite-server",
"test": "echo \"Error: no test specified\" && exit 1",
"deploy": "gh-pages -d src"
},
"author": "",
"license": "ISC",
"devDependencies": {
"gh-pages": "^3.0.0",
"lite-server": "^2.5.4"
}
}
run the command
npm run build
and it will be deployed to Github pages.
A:
you should also add "homepage":"https://yourGithub.github.io/your-repo" above "name" in the package.json
| How to deploy npm project to gh-pages | I'm trying to deploy a website to gh-pages using npm. I'm using blain HTML and CSS and asynchronous javascript. I haven't used any SPA framework (react or angular).
I'm currently using lite server for development purposes and gh-pages package.
I'm trying to deploy the src folder using the following command
npm run deploy
it fails because the build script is not specified.
my question is what should I write in the build script?
when I try to run npm run deploy it displays the following error
'src' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `src`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Amr\AppData\Roaming\npm-cache\_logs\2020-05-30T11_30_29_824Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] predeploy: `npm run build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] predeploy script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Amr\AppData\Roaming\npm-cache\_logs\2020-05-30T11_30_29_869Z-debug.log
in similar projects using react, the build script has the following react-scripts build
this is my package.json file
{
"name": "AmrAhmed",
"version": "1.0.0",
"description": "",
"main": "truffle.js",
"directories": {
"test": "test"
},
"scripts": {
"dev": "lite-server",
"test": "echo \"Error: no test specified\" && exit 1",
"build": "src",
"predeploy": "npm run build",
"deploy": "gh-pages -d src"
},
"author": "",
"license": "ISC",
"devDependencies": {
"gh-pages": "^3.0.0",
"lite-server": "^2.5.4"
}
}
election folder content
src folder content
| [
"I found out that you don't need the build script or the pre-deploy script. they are unnecessary to be used, since my website is static, I can navigate directly to the build folder and it will work fine.\nI have modified the config.json file to be as in the following\n{\n \"name\": \"AmrAhmed\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"truffle.js\",\n \"directories\": {\n \"test\": \"test\"\n },\n \"scripts\": {\n \"dev\": \"lite-server\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"deploy\": \"gh-pages -d src\"\n },\n \"author\": \"\",\n \"license\": \"ISC\",\n \"devDependencies\": {\n \"gh-pages\": \"^3.0.0\",\n \"lite-server\": \"^2.5.4\"\n }\n}\n\nrun the command \nnpm run build\nand it will be deployed to Github pages.\n",
"you should also add \"homepage\":\"https://yourGithub.github.io/your-repo\" above \"name\" in the package.json\n"
] | [
1,
0
] | [] | [] | [
"github",
"github_pages",
"npm",
"package.json"
] | stackoverflow_0062101924_github_github_pages_npm_package.json.txt |
Q:
Why I need to enter empty char to be able to continue with my console app in c++?
I am totally new to c++ and I am working on small console project for school. I created something like Thermostat. When you run that app, It will ask for user input.
i - informations
t - temperature settings
q - quit
+ - add to temperature by 1
- - remove from temperature by 1
Everything is working for me, I can press 'i', I can press +/- and everything is ok. But when I press 't', enter some temperature and confirm, I will receive corrent response. But now, whatever I will press, it will get into 'default' part of switch. Why is this happening to me? Then I press just 'enter', then again 't' and it is working again.
As you can see, after I put '18', I pressed enter. There is response that Temperature will be set to 18 and relay is on. If I want to close app, I should press 'q' or I can continue in setting new temperature. Whatever I press it will show: "Zly vstup. Stlacte tlacidlo 'i' pre viac informacii" and that is from 'default' part of switch.
I can press anything, all the time this will be shown until I press 'enter', then I can enter 't' again and it is working.
Why is this happening?
Here is code:
#include <iostream>
#include <string>
using namespace std;
int input;
int temp = 20;
int oldTemp = 20;
string relay = "vypnute";
int main() {
printf("Regulator teploty Turbo 3000 \nAktualna teplota: %d stupnov celzia, rele je %s. \nStlacte tladiclo 'i' pre informacie: ", temp, relay.c_str());
while(input != 'q'){
input = getchar();
getchar();
switch(input){
case 'i': case 'i ':
if(temp != 20){
relay = "zapnute";
}
printf("Aktualne je nastavena teplota na %d stupnov celzia, rele je %s. \n", temp, relay.c_str());
printf(" i Info \n\ t Zadanie teploty od 10 do 35 stupnov \n\ + Zvysenie teploty o 1 stupen \n\ - Znizenie teploty o 1 stupen \n\ q Koniec programu \n");
break;
case 't': case 't ':
printf("Zadajte pozadovanu teplotu: ");
cin >> input;
if(input > 35 || input < 10){
printf("Zadajte teplotu v rozmedzi od 10 do 35 stupnov. \nStlacte 't' pre zadanie novej teploty. ");
break;
}
if(input == temp){
relay = "vypnute";
}
else{
relay = "zapnute";
}
printf("Teplota bude nastavena z povodnych %d na pozadovanych %d stupnov, rele je %s.",temp, input, relay.c_str());
temp = input;
printf("\nAk chcete ukoncit regulator, stlacte 'q', inak pokracujte v nastavovani teploty. ");
break;
case '+': case '+ ':
if(temp+1 > 35){
printf("Teplota nemoze byt vyssia ako 35 stupnov. ");
break;
}
relay = "zapnute";
printf("Teplota bola zvysena z povodnych %d na pozadovanych %d stupnov, rele je %s. ",temp, temp+1, relay.c_str());
temp++;
printf("\nAk chcete ukoncit regulator, stlacte 'q', inak pokracujte v nastavovani teploty. ");
break;
case '-': case '- ':
if(temp-1 < 10){
printf("Teplota nemoze byt mensia ako 10 stupnov. ");
break;
}
relay = "zapnute";
printf("Teplota bola znizena z povodnych %d na pozadovanych %d stupnov, rele je %s. ",temp, temp-1, relay.c_str());
temp--;
printf("\nAk chcete ukoncit regulator, stlacte 'q', inak pokracujte v nastavovani teploty. ");
break;
case 'q': case 'q ':
break;
default:
printf("Zly vstup. Stlacte tlacidlo 'i' pre viac informacii. ");
break;
}
}
if(temp == oldTemp){
relay = "vypnute";
}
else{
relay = "zapnute";
}
printf("Dakujeme za pouzivanie Regulatora Turbo 3000. \nTeplota je po novom nastavena na %d stupnov celzia a rele je %s. ", temp, relay.c_str());
printf("Stlacte 'enter' pre ukoncenie aplikacie.");
getchar();
return 0;
}
A:
Thanks to @πάντα ῥεῖ, I was able to fix my problem.
Here is new, working code:
#include <iostream>
using namespace std;
int temp = 20;
int oldTemp = 20;
int min_temp = 10;
int max_temp = 35;
int temp_input;
char input;
string relay = "vypnute";
int main(int argc, const char * argv[]) {
cout << "Regulator teploty Turbo 3000. \nAktualna teplota je nastavena na " << temp << " stupnov celzia, rele je " << relay << ".\nStlacte tlacidlo 'i' pre viac informacii.\nZadajte poziadavku: ";
while(input != 'q'){
cin >> input;
cin.ignore();
switch(input){
case 'i':
if(temp != oldTemp){
relay = "zapnute";
}
cout << "Aktualne je nastavena teplota na " << temp << " stupnov celzia, rele je " << relay << ".\n'i' -> Info \n't' -> Zadanie teploty \n'+' -> Zvysenie teploty o 1 stupen celzia \n'-' -> Znizenie teploty o jeden stupen celzia \n'q' -> Ukoncenie programu 'Regulator teploty Turbo 3000'\nZadajte poziadavku: ";
break;
case 't':
cout << "Zadajte pozadovanu teplotu v rozmedzi od " << min_temp << " stupnov celzia do " << max_temp << " stupnov celzia.\nTeplota: ";
cin >> temp_input;
cin.ignore();
if(temp_input > max_temp || temp_input < min_temp){
cout << "Zadali ste teplotu mimo povolenych hodnot. Zadajte hodnotu v rozmedzi od " << min_temp << " stupnov celzia do " << max_temp << " stupnov celzia.\n Teplota: ";
}
temp_input != temp ? relay = "zapnute" : relay = "vypnute";
cout << "Teplota bude regulovana z povodnych " << temp << " stupnov celzia na pozadovanych " << temp_input << " stupnov celzia, rele je " << relay << ".\nZadajte poziadavku: ";
temp = temp_input;
break;
case '+':
if(temp + 1 > max_temp){
cout << "Teplota nemoze byt vyssia ako " << max_temp << " stupnov celzia.\nZadajte poziadavku: ";
break;
}
relay = "zapnute";
cout << "Teplota bude regulovana z povodnych " << temp << " stupnov celzia na pozadovanych " << temp + 1 << " stupnov celzia, rele je " << relay << ".\nZadajte poziadavku: ";
temp++;
break;
case '-':
if(temp - 1 < min_temp){
cout << "Teplota nemoze byt nizsia ako " << min_temp << " stupnov celzia.\nZadajte poziadavku: ";
break;
}
relay = "zapnute";
cout << "Teplota bude regulovana z povodnych " << temp << " stupnov celzia na pozadovanych " << temp - 1 << " stupnov celzia, rele je " << relay << ".\nZadajte poziadavku: ";
temp--;
break;
default:
cout << "Neznama poziadavka. Zadajte 'i' pre viac informacii.\nZadajte poziadavku: ";
}
}
oldTemp == temp ? relay = "vypnute" : relay = "zapnute";
cout << "Dakujeme za pouzivanie programu Regulator Turbo 3000.\nTeplota je nastavena na " << temp << " stupnov celzia, rele je " << relay << ".\nStlacte 'enter' pre ukoncenie aplikacie.\n";
cin.get();
return 0;
}
| Why I need to enter empty char to be able to continue with my console app in c++? | I am totally new to c++ and I am working on small console project for school. I created something like Thermostat. When you run that app, It will ask for user input.
i - informations
t - temperature settings
q - quit
+ - add to temperature by 1
- - remove from temperature by 1
Everything is working for me, I can press 'i', I can press +/- and everything is ok. But when I press 't', enter some temperature and confirm, I will receive corrent response. But now, whatever I will press, it will get into 'default' part of switch. Why is this happening to me? Then I press just 'enter', then again 't' and it is working again.
As you can see, after I put '18', I pressed enter. There is response that Temperature will be set to 18 and relay is on. If I want to close app, I should press 'q' or I can continue in setting new temperature. Whatever I press it will show: "Zly vstup. Stlacte tlacidlo 'i' pre viac informacii" and that is from 'default' part of switch.
I can press anything, all the time this will be shown until I press 'enter', then I can enter 't' again and it is working.
Why is this happening?
Here is code:
#include <iostream>
#include <string>
using namespace std;
int input;
int temp = 20;
int oldTemp = 20;
string relay = "vypnute";
int main() {
printf("Regulator teploty Turbo 3000 \nAktualna teplota: %d stupnov celzia, rele je %s. \nStlacte tladiclo 'i' pre informacie: ", temp, relay.c_str());
while(input != 'q'){
input = getchar();
getchar();
switch(input){
case 'i': case 'i ':
if(temp != 20){
relay = "zapnute";
}
printf("Aktualne je nastavena teplota na %d stupnov celzia, rele je %s. \n", temp, relay.c_str());
printf(" i Info \n\ t Zadanie teploty od 10 do 35 stupnov \n\ + Zvysenie teploty o 1 stupen \n\ - Znizenie teploty o 1 stupen \n\ q Koniec programu \n");
break;
case 't': case 't ':
printf("Zadajte pozadovanu teplotu: ");
cin >> input;
if(input > 35 || input < 10){
printf("Zadajte teplotu v rozmedzi od 10 do 35 stupnov. \nStlacte 't' pre zadanie novej teploty. ");
break;
}
if(input == temp){
relay = "vypnute";
}
else{
relay = "zapnute";
}
printf("Teplota bude nastavena z povodnych %d na pozadovanych %d stupnov, rele je %s.",temp, input, relay.c_str());
temp = input;
printf("\nAk chcete ukoncit regulator, stlacte 'q', inak pokracujte v nastavovani teploty. ");
break;
case '+': case '+ ':
if(temp+1 > 35){
printf("Teplota nemoze byt vyssia ako 35 stupnov. ");
break;
}
relay = "zapnute";
printf("Teplota bola zvysena z povodnych %d na pozadovanych %d stupnov, rele je %s. ",temp, temp+1, relay.c_str());
temp++;
printf("\nAk chcete ukoncit regulator, stlacte 'q', inak pokracujte v nastavovani teploty. ");
break;
case '-': case '- ':
if(temp-1 < 10){
printf("Teplota nemoze byt mensia ako 10 stupnov. ");
break;
}
relay = "zapnute";
printf("Teplota bola znizena z povodnych %d na pozadovanych %d stupnov, rele je %s. ",temp, temp-1, relay.c_str());
temp--;
printf("\nAk chcete ukoncit regulator, stlacte 'q', inak pokracujte v nastavovani teploty. ");
break;
case 'q': case 'q ':
break;
default:
printf("Zly vstup. Stlacte tlacidlo 'i' pre viac informacii. ");
break;
}
}
if(temp == oldTemp){
relay = "vypnute";
}
else{
relay = "zapnute";
}
printf("Dakujeme za pouzivanie Regulatora Turbo 3000. \nTeplota je po novom nastavena na %d stupnov celzia a rele je %s. ", temp, relay.c_str());
printf("Stlacte 'enter' pre ukoncenie aplikacie.");
getchar();
return 0;
}
| [
"Thanks to @πάντα ῥεῖ, I was able to fix my problem.\nHere is new, working code:\n#include <iostream>\n\nusing namespace std;\n\nint temp = 20;\nint oldTemp = 20;\nint min_temp = 10;\nint max_temp = 35;\nint temp_input;\nchar input;\nstring relay = \"vypnute\";\n\nint main(int argc, const char * argv[]) {\n cout << \"Regulator teploty Turbo 3000. \\nAktualna teplota je nastavena na \" << temp << \" stupnov celzia, rele je \" << relay << \".\\nStlacte tlacidlo 'i' pre viac informacii.\\nZadajte poziadavku: \";\n while(input != 'q'){\n cin >> input;\n cin.ignore();\n switch(input){\n case 'i':\n if(temp != oldTemp){\n relay = \"zapnute\";\n }\n cout << \"Aktualne je nastavena teplota na \" << temp << \" stupnov celzia, rele je \" << relay << \".\\n'i' -> Info \\n't' -> Zadanie teploty \\n'+' -> Zvysenie teploty o 1 stupen celzia \\n'-' -> Znizenie teploty o jeden stupen celzia \\n'q' -> Ukoncenie programu 'Regulator teploty Turbo 3000'\\nZadajte poziadavku: \";\n break;\n case 't':\n cout << \"Zadajte pozadovanu teplotu v rozmedzi od \" << min_temp << \" stupnov celzia do \" << max_temp << \" stupnov celzia.\\nTeplota: \";\n cin >> temp_input;\n cin.ignore();\n if(temp_input > max_temp || temp_input < min_temp){\n cout << \"Zadali ste teplotu mimo povolenych hodnot. Zadajte hodnotu v rozmedzi od \" << min_temp << \" stupnov celzia do \" << max_temp << \" stupnov celzia.\\n Teplota: \";\n }\n temp_input != temp ? relay = \"zapnute\" : relay = \"vypnute\";\n cout << \"Teplota bude regulovana z povodnych \" << temp << \" stupnov celzia na pozadovanych \" << temp_input << \" stupnov celzia, rele je \" << relay << \".\\nZadajte poziadavku: \";\n temp = temp_input;\n break;\n case '+':\n if(temp + 1 > max_temp){\n cout << \"Teplota nemoze byt vyssia ako \" << max_temp << \" stupnov celzia.\\nZadajte poziadavku: \";\n break;\n }\n relay = \"zapnute\";\n cout << \"Teplota bude regulovana z povodnych \" << temp << \" stupnov celzia na pozadovanych \" << temp + 1 << \" stupnov celzia, rele je \" << relay << \".\\nZadajte poziadavku: \";\n temp++;\n break;\n case '-':\n if(temp - 1 < min_temp){\n cout << \"Teplota nemoze byt nizsia ako \" << min_temp << \" stupnov celzia.\\nZadajte poziadavku: \";\n break;\n }\n relay = \"zapnute\";\n cout << \"Teplota bude regulovana z povodnych \" << temp << \" stupnov celzia na pozadovanych \" << temp - 1 << \" stupnov celzia, rele je \" << relay << \".\\nZadajte poziadavku: \";\n temp--;\n break;\n default:\n cout << \"Neznama poziadavka. Zadajte 'i' pre viac informacii.\\nZadajte poziadavku: \";\n }\n }\n oldTemp == temp ? relay = \"vypnute\" : relay = \"zapnute\";\n cout << \"Dakujeme za pouzivanie programu Regulator Turbo 3000.\\nTeplota je nastavena na \" << temp << \" stupnov celzia, rele je \" << relay << \".\\nStlacte 'enter' pre ukoncenie aplikacie.\\n\";\n cin.get();\n return 0;\n}\n\n\n\n"
] | [
0
] | [] | [] | [
"c++",
"console_application"
] | stackoverflow_0074675794_c++_console_application.txt |
Q:
Saving bash variable *after* a command have run
I have the following git pre-commit hook:
echo '\n Running "yarn lint"...'
cd web
lintCheck=$(yarn lint)
if [[ "$lintCheck" == *" No ESLint warnings or errors"* ]]; then
echo "✅ Linting looks good!";
else
echo "❌ Linting error ❌";
exit 1
fi
I want to display the output from yarn lint with normal behavior. I want to see messages as they come using the standard formatting of messages in real time.
The closest solution I have that doesn't run the same command twice looks like this:
echo '\n Running "yarn lint"...'
cd web
lintCheck=$(yarn lint)
echo $lintCheck # <-- LOOK HERE
if [[ "$lintCheck" == *" No ESLint warnings or errors"* ]]; then
echo "✅ Linting looks good!";
else
echo "❌ Linting error ❌";
exit 1
fi
However, it outputs the text without regular font color and on one single line, all at the same time.
I've got a tip to use tee, but as I understand it it's used for file saving, and not for variables.
Thanks in advance!
A:
echo $lintCheck
However, it outputs the text without regular font color and on one single line, all at the same time.
The missing line breaks come from the unquoted variable expansion, which does all kind of stuff like word splitting and so on. Use echo "$lintCheck" to keep the linebreaks.
The missing colors probably come from yarn itself. Programs can detect if they run interactively or in a pipe/script and adjust their output accordingly.
I cannot try this myself, but from https://classic.yarnpkg.com/lang/en/docs/cli/ ...
Force ANSI color output
Yarn utilizes the chalk terminal colors library and will respect an environment variable setting FORCE_COLOR=true, e.g. to make script tasks output color when the terminal is not a tty (e.g., in CI environments.)
it seems you can use ...
lintCheck=$(FORCE_COLOR=true yarn lint)
echo "$lintCheck"
But that will give you the output only after yarn lint completed. To print the output as soon it is produced, try writing to a file descriptor
{ lintCheck=$(FORCE_COLOR=true yarn lint | tee /dev/fd/3); } 3>&1
However, the whole reason you try to capture the output in a variable looks a bit like an XY problem. Are you sure you need the output, and cannot just use the exit status of yarn lint?
| Saving bash variable *after* a command have run | I have the following git pre-commit hook:
echo '\n Running "yarn lint"...'
cd web
lintCheck=$(yarn lint)
if [[ "$lintCheck" == *" No ESLint warnings or errors"* ]]; then
echo "✅ Linting looks good!";
else
echo "❌ Linting error ❌";
exit 1
fi
I want to display the output from yarn lint with normal behavior. I want to see messages as they come using the standard formatting of messages in real time.
The closest solution I have that doesn't run the same command twice looks like this:
echo '\n Running "yarn lint"...'
cd web
lintCheck=$(yarn lint)
echo $lintCheck # <-- LOOK HERE
if [[ "$lintCheck" == *" No ESLint warnings or errors"* ]]; then
echo "✅ Linting looks good!";
else
echo "❌ Linting error ❌";
exit 1
fi
However, it outputs the text without regular font color and on one single line, all at the same time.
I've got a tip to use tee, but as I understand it it's used for file saving, and not for variables.
Thanks in advance!
| [
"\necho $lintCheck\nHowever, it outputs the text without regular font color and on one single line, all at the same time.\n\nThe missing line breaks come from the unquoted variable expansion, which does all kind of stuff like word splitting and so on. Use echo \"$lintCheck\" to keep the linebreaks.\nThe missing colors probably come from yarn itself. Programs can detect if they run interactively or in a pipe/script and adjust their output accordingly.\nI cannot try this myself, but from https://classic.yarnpkg.com/lang/en/docs/cli/ ...\n\nForce ANSI color output\nYarn utilizes the chalk terminal colors library and will respect an environment variable setting FORCE_COLOR=true, e.g. to make script tasks output color when the terminal is not a tty (e.g., in CI environments.)\n\nit seems you can use ...\nlintCheck=$(FORCE_COLOR=true yarn lint)\necho \"$lintCheck\"\n\nBut that will give you the output only after yarn lint completed. To print the output as soon it is produced, try writing to a file descriptor\n{ lintCheck=$(FORCE_COLOR=true yarn lint | tee /dev/fd/3); } 3>&1\n\nHowever, the whole reason you try to capture the output in a variable looks a bit like an XY problem. Are you sure you need the output, and cannot just use the exit status of yarn lint?\n"
] | [
2
] | [] | [] | [
"bash",
"git",
"pre_commit_hook"
] | stackoverflow_0074677442_bash_git_pre_commit_hook.txt |
Q:
stable Baselines 3 model.predict with stepwise varying actions
I would like to train a gym model based on a custom environment.
The training loop looks like this:
obs = env.reset()
for i in range(1000):
action, _states = model.predict(obs, deterministic=True)
print(f"action: {action}")
obs, reward, done, info = env.step(action)
env.render()
if done:
obs = env.reset()
There are basic examples like this, e.g. here:
https://stable-baselines.readthedocs.io/en/master/guide/examples.html
Somewhere else (within the environment class)
I defined an action_space:
self.action_space = spaces.Discrete(5)
With this basic definition of the action_space the actions returned by model.predict
for each step seem to be just numbers from 0 to 4.
Now - for making the question a little more practical - I assume, my
environment describes a maze. My overall available actions in this case could be
realActions = [_UP, _DOWN, _LEFT, _RIGHT]
Now in a maze the available actions for each step are constantly changing.
For example at the upper wall of the maze the actions would only be:
realActions = [_DOWN, _LEFT, _RIGHT]
So I would try to take this into consideration:
env.render()
realActions = env.getCurrentAvailableActions()
#set gym action_space with reduced no. of options:
self.action_space = spaces.Discrete(len(realActions))
And in env.step I would execute realActions[action] in the maze to do the correct move.
Unfortunately the reassignment of self.action_space seems not to be recognized by my model.
There is another important point: the workaround to assign realActions instead of defining action_space itsself with this values could never
train correctly, because the model never would know, which
effect the action it generates would have to the maze, because
it does not see the assignment from its own action to realActions.
So my question is: does stable baselines / gym provide a practicable way to limit the action_spaces to dynamically (per step) available actions?
Thank you!
A:
Yes, it is possible to use dynamically changing action spaces in stable-baselines / gym. The key is to use the self.observation_space attribute within your environment class to specify the available actions at each step.
Here is an example of how you could do this:
class MazeEnv(gym.Env):
def __init__(self):
self.observation_space = spaces.Box(
low=0, high=255, shape=(4, 4, 3), dtype=np.uint8)
self.current_actions = [_UP, _DOWN, _LEFT, _RIGHT]
self.action_space = spaces.Discrete(len(self.current_actions))
def get_current_actions(self):
# Compute and return the available actions at the current state
return self.current_actions
def step(self, action):
# Use self.get_current_actions() to determine which action to take
real_action = self.current_actions[action]
...
In the above example, the MazeEnv class has a current_actions attribute which is used to store the available actions at each step. The get_current_actions method is used to compute and return the available actions at the current state, and the step method uses this information to determine which action to take.
To use this environment with a stable-baselines model, you would need to update the training loop as follows:
obs = env.reset()
for i in range(1000):
# Get the current available actions
current_actions = env.get_current_actions()
# Set the action space to the current available actions
env.action_space = spaces.Discrete(len(current_actions))
# Use the current action space to make a prediction
action, _states = model.predict(obs, deterministic=True)
print(f"action: {action}")
# Use the current available actions to determine which action to take
real_action = current_actions[action]
obs, reward, done, info = env.step(real_action)
env.render()
if done:
obs = env.reset()
In this updated training loop, the current_actions variable is used to store the available actions at each step, and the env.action_space attribute is updated to use these actions. This allows the model to make predictions based on the correct action space, and the real_action variable is used to determine which action to take in the environment.
| stable Baselines 3 model.predict with stepwise varying actions | I would like to train a gym model based on a custom environment.
The training loop looks like this:
obs = env.reset()
for i in range(1000):
action, _states = model.predict(obs, deterministic=True)
print(f"action: {action}")
obs, reward, done, info = env.step(action)
env.render()
if done:
obs = env.reset()
There are basic examples like this, e.g. here:
https://stable-baselines.readthedocs.io/en/master/guide/examples.html
Somewhere else (within the environment class)
I defined an action_space:
self.action_space = spaces.Discrete(5)
With this basic definition of the action_space the actions returned by model.predict
for each step seem to be just numbers from 0 to 4.
Now - for making the question a little more practical - I assume, my
environment describes a maze. My overall available actions in this case could be
realActions = [_UP, _DOWN, _LEFT, _RIGHT]
Now in a maze the available actions for each step are constantly changing.
For example at the upper wall of the maze the actions would only be:
realActions = [_DOWN, _LEFT, _RIGHT]
So I would try to take this into consideration:
env.render()
realActions = env.getCurrentAvailableActions()
#set gym action_space with reduced no. of options:
self.action_space = spaces.Discrete(len(realActions))
And in env.step I would execute realActions[action] in the maze to do the correct move.
Unfortunately the reassignment of self.action_space seems not to be recognized by my model.
There is another important point: the workaround to assign realActions instead of defining action_space itsself with this values could never
train correctly, because the model never would know, which
effect the action it generates would have to the maze, because
it does not see the assignment from its own action to realActions.
So my question is: does stable baselines / gym provide a practicable way to limit the action_spaces to dynamically (per step) available actions?
Thank you!
| [
"Yes, it is possible to use dynamically changing action spaces in stable-baselines / gym. The key is to use the self.observation_space attribute within your environment class to specify the available actions at each step.\nHere is an example of how you could do this:\nclass MazeEnv(gym.Env):\n def __init__(self):\n self.observation_space = spaces.Box(\n low=0, high=255, shape=(4, 4, 3), dtype=np.uint8)\n self.current_actions = [_UP, _DOWN, _LEFT, _RIGHT]\n self.action_space = spaces.Discrete(len(self.current_actions))\n\n def get_current_actions(self):\n # Compute and return the available actions at the current state\n return self.current_actions\n\n def step(self, action):\n # Use self.get_current_actions() to determine which action to take\n real_action = self.current_actions[action]\n ...\n\nIn the above example, the MazeEnv class has a current_actions attribute which is used to store the available actions at each step. The get_current_actions method is used to compute and return the available actions at the current state, and the step method uses this information to determine which action to take.\nTo use this environment with a stable-baselines model, you would need to update the training loop as follows:\nobs = env.reset()\nfor i in range(1000):\n # Get the current available actions\n current_actions = env.get_current_actions()\n\n # Set the action space to the current available actions\n env.action_space = spaces.Discrete(len(current_actions))\n\n # Use the current action space to make a prediction\n action, _states = model.predict(obs, deterministic=True)\n print(f\"action: {action}\")\n\n # Use the current available actions to determine which action to take\n real_action = current_actions[action]\n obs, reward, done, info = env.step(real_action)\n\n env.render()\n if done:\n obs = env.reset()\n\nIn this updated training loop, the current_actions variable is used to store the available actions at each step, and the env.action_space attribute is updated to use these actions. This allows the model to make predictions based on the correct action space, and the real_action variable is used to determine which action to take in the environment.\n"
] | [
1
] | [] | [] | [
"python",
"reinforcement_learning",
"stable_baselines"
] | stackoverflow_0074656974_python_reinforcement_learning_stable_baselines.txt |
Q:
Vue JS : Pinia direct changes to state and $patch() which one is more performant or is better to use
I'm using Pinia with Vuejs 3 and I just want to know if using $patch() doesn't affect the performance of the app.
Which one is the best practice?
For example.
import { defineStore } from 'pinia'
export const useStore = defineStore('storeId', {
state: () => ({ count: 0 }),
actions: {
directIncrement() {
this.count++
},
patchIncrement() {
this.$patch({
count: store.count + 1,
},
},
})
So which one is the best?
I want to know which one to chose to have the best performance and which one respects the best practices
A:
If you have only one value to change, you may use like this.count++.
But if you have multiple changes, you can use like
this.$patch({
count: store.count + 1,
name: 'aa'
})
| Vue JS : Pinia direct changes to state and $patch() which one is more performant or is better to use | I'm using Pinia with Vuejs 3 and I just want to know if using $patch() doesn't affect the performance of the app.
Which one is the best practice?
For example.
import { defineStore } from 'pinia'
export const useStore = defineStore('storeId', {
state: () => ({ count: 0 }),
actions: {
directIncrement() {
this.count++
},
patchIncrement() {
this.$patch({
count: store.count + 1,
},
},
})
So which one is the best?
I want to know which one to chose to have the best performance and which one respects the best practices
| [
"If you have only one value to change, you may use like this.count++.\nBut if you have multiple changes, you can use like\nthis.$patch({\n count: store.count + 1,\n name: 'aa'\n})\n\n"
] | [
0
] | [] | [] | [
"pinia",
"vue.js"
] | stackoverflow_0074674512_pinia_vue.js.txt |
Q:
What is the right way of providing custom metadata to file uploaded to GCP Storage bucket? Using node.js sdk
I have been struggling to provide custom metadata to uploaded file. Here is the code:
const uploadResponse = await GCS.bucket(bucketName).upload(filePath, {
destination: filedir + filename,
metadata: {
custom1: 'customValue1',
custom2: 'customValue2'
},
});
The file upload is working alright but the custom metadata attributes seem to be ignored. Any hints appreciated.
A:
o provide custom metadata to a file uploaded to a Google Cloud Storage (GCS) bucket, you can use the metadata option when calling the upload method. This option takes an object where the keys are the metadata keys and the values are the metadata values.
Here is an example of how you can provide custom metadata when uploading a file to a GCS bucket using the Node.js SDK:
const {Storage} = require('@google-cloud/storage');
const GCS = new Storage();
const bucketName = 'my-bucket';
const filePath = '/path/to/file.txt';
const filedir = 'folder/';
const filename = 'file.txt';
const uploadResponse = await GCS.bucket(bucketName).upload(filePath, {
destination: filedir + filename,
metadata: {
custom1: 'customValue1',
custom2: 'customValue2'
},
});
In this example, the upload method is called with the metadata option set to an object with two keys: custom1 and custom2. These keys will be added as metadata to the uploaded file.
Note that the metadata keys must be lowercase and cannot contain underscores, dashes, or other special characters. Also, the metadata values must be strings and cannot be larger than 1,024 bytes.
| What is the right way of providing custom metadata to file uploaded to GCP Storage bucket? Using node.js sdk | I have been struggling to provide custom metadata to uploaded file. Here is the code:
const uploadResponse = await GCS.bucket(bucketName).upload(filePath, {
destination: filedir + filename,
metadata: {
custom1: 'customValue1',
custom2: 'customValue2'
},
});
The file upload is working alright but the custom metadata attributes seem to be ignored. Any hints appreciated.
| [
"o provide custom metadata to a file uploaded to a Google Cloud Storage (GCS) bucket, you can use the metadata option when calling the upload method. This option takes an object where the keys are the metadata keys and the values are the metadata values.\nHere is an example of how you can provide custom metadata when uploading a file to a GCS bucket using the Node.js SDK:\nconst {Storage} = require('@google-cloud/storage');\n\nconst GCS = new Storage();\n\nconst bucketName = 'my-bucket';\nconst filePath = '/path/to/file.txt';\nconst filedir = 'folder/';\nconst filename = 'file.txt';\n\nconst uploadResponse = await GCS.bucket(bucketName).upload(filePath, {\n destination: filedir + filename,\n metadata: {\n custom1: 'customValue1',\n custom2: 'customValue2'\n },\n});\n\nIn this example, the upload method is called with the metadata option set to an object with two keys: custom1 and custom2. These keys will be added as metadata to the uploaded file.\nNote that the metadata keys must be lowercase and cannot contain underscores, dashes, or other special characters. Also, the metadata values must be strings and cannot be larger than 1,024 bytes.\n"
] | [
0
] | [] | [] | [
"google_cloud_platform",
"google_cloud_storage",
"node.js"
] | stackoverflow_0074677541_google_cloud_platform_google_cloud_storage_node.js.txt |
Q:
How to solve Error : cannot find module "ejs"?
I started a new (and first) express.js project using ejs but facing to this following error while accessing to the page :
Error: Cannot find module 'ejs '
Require stack:
- C:\wamp64\www\myproject\node_modules\express\lib\view.js
- C:\wamp64\www\myproject\node_modules\express\lib\application.js
- C:\wamp64\www\myproject\node_modules\express\lib\express.js
- C:\wamp64\www\myproject\node_modules\express\index.js
- C:\wamp64\www\myproject\server.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:925:15)
at Function.Module._load (node:internal/modules/cjs/loader:769:27)
at Module.require (node:internal/modules/cjs/loader:997:19)
at require (node:internal/modules/cjs/helpers:92:18)
at new View (C:\wamp64\www\myproject\node_modules\express\lib\view.js:81:14)
at Function.render (C:\wamp64\www\myproject\node_modules\express\lib\application.js:570:12)
at ServerResponse.render (C:\wamp64\www\myproject\node_modules\express\lib\response.js:1012:7)
at C:\wamp64\www\myproject\server.js:10:13
at Layer.handle [as handle_request] (C:\wamp64\www\myproject\node_modules\express\lib\router\layer.js:95:5)
at next (C:\wamp64\www\myproject\node_modules\express\lib\router\route.js:137:13)
Here is how I proceed from the beginning :
Created a new folder called myproject
Created a new file called server.js
node init
Modified package.json to add nodemon
npm install --save nodemon
npm install --save express
npm install --save ejs
My file server.js :
var app = require('express')();
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
res.setHeader('Content-Type', 'text/plain');
res.send('Accueil');
})
.get('/album', function(req, res){
res.setHeader('Content-Type', 'text/plain');
res.render('album.ejs ', {name :'yop'});
})
.use(function(req, res, next){
res.setHeader('Content-Type', 'text/plain');
res.status(404).send('Page introuvable !');
});
app.listen(8080);
My file package.json :
{
"name": "myproject",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.5",
"express": "^4.17.1",
"nodemon": "^2.0.6"
}
}
My project's structure :
My project directory
node_modules folder
views folder
album.ejs file
package.json
server.js
A:
in your server.js
app.set('view engine', 'ejs')
app.set('views', __dirname + '/views')
A:
You add one extra space accidentally behind the ejs.
res.render('album.ejs ', {name :'yop'});
Remove that space like below.
res.render('album.ejs', {name :'yop'});
And you could just use the file name without extension name.
res.render('album', {name :'yop'});
A:
add this to your code just below app.set('view engine', 'ejs)
app.engine('ejs', require('ejs').__express);
A:
If you already had installed ejs, you must uninstall and install it again
Here are the steps:
npm uninstall ejs --save
npm install ejs --save
| How to solve Error : cannot find module "ejs"? | I started a new (and first) express.js project using ejs but facing to this following error while accessing to the page :
Error: Cannot find module 'ejs '
Require stack:
- C:\wamp64\www\myproject\node_modules\express\lib\view.js
- C:\wamp64\www\myproject\node_modules\express\lib\application.js
- C:\wamp64\www\myproject\node_modules\express\lib\express.js
- C:\wamp64\www\myproject\node_modules\express\index.js
- C:\wamp64\www\myproject\server.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:925:15)
at Function.Module._load (node:internal/modules/cjs/loader:769:27)
at Module.require (node:internal/modules/cjs/loader:997:19)
at require (node:internal/modules/cjs/helpers:92:18)
at new View (C:\wamp64\www\myproject\node_modules\express\lib\view.js:81:14)
at Function.render (C:\wamp64\www\myproject\node_modules\express\lib\application.js:570:12)
at ServerResponse.render (C:\wamp64\www\myproject\node_modules\express\lib\response.js:1012:7)
at C:\wamp64\www\myproject\server.js:10:13
at Layer.handle [as handle_request] (C:\wamp64\www\myproject\node_modules\express\lib\router\layer.js:95:5)
at next (C:\wamp64\www\myproject\node_modules\express\lib\router\route.js:137:13)
Here is how I proceed from the beginning :
Created a new folder called myproject
Created a new file called server.js
node init
Modified package.json to add nodemon
npm install --save nodemon
npm install --save express
npm install --save ejs
My file server.js :
var app = require('express')();
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
res.setHeader('Content-Type', 'text/plain');
res.send('Accueil');
})
.get('/album', function(req, res){
res.setHeader('Content-Type', 'text/plain');
res.render('album.ejs ', {name :'yop'});
})
.use(function(req, res, next){
res.setHeader('Content-Type', 'text/plain');
res.status(404).send('Page introuvable !');
});
app.listen(8080);
My file package.json :
{
"name": "myproject",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.5",
"express": "^4.17.1",
"nodemon": "^2.0.6"
}
}
My project's structure :
My project directory
node_modules folder
views folder
album.ejs file
package.json
server.js
| [
"in your server.js\napp.set('view engine', 'ejs')\napp.set('views', __dirname + '/views')\n\n",
"You add one extra space accidentally behind the ejs.\nres.render('album.ejs ', {name :'yop'});\n\nRemove that space like below.\nres.render('album.ejs', {name :'yop'});\n\nAnd you could just use the file name without extension name.\nres.render('album', {name :'yop'});\n\n",
"add this to your code just below app.set('view engine', 'ejs)\napp.engine('ejs', require('ejs').__express);\n\n",
"If you already had installed ejs, you must uninstall and install it again\nHere are the steps:\n\nnpm uninstall ejs --save\nnpm install ejs --save\n\n"
] | [
1,
1,
0,
0
] | [] | [] | [
"ejs",
"express",
"node.js"
] | stackoverflow_0065530111_ejs_express_node.js.txt |
Q:
How to solve "Error: MySQL shutdown unexpectedly"?
When I open XAMPP and click start MySQL button and it gives me an error.
I had started it just before, but now it isn't working.
12:19:12 PM [mysql] Attempting to start MySQL app...
12:19:12 PM [mysql] Status change detected: running
12:19:13 PM [mysql] Status change detected: stopped
12:19:13 PM [mysql] Error: MySQL shutdown unexpectedly.
12:19:13 PM [mysql] This may be due to a blocked port, missing dependencies,
12:19:13 PM [mysql] improper privileges, a crash, or a shutdown by another method
12:19:13 PM [mysql] Press the Logs button to view error logs and check
12:19:13 PM [mysql] the Windows Event Viewer for more clues
12:19:13 PM [mysql] If you need more help, copy and post this
12:19:13 PM [mysql] entire log window on the forums
Here is the contents of the error log:
2013-08-02 12:19:12 4536 [Note] Plugin 'FEDERATED' is disabled.
2013-08-02 12:19:12 f64 InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.
2013-08-02 12:19:12 4536 [Note] InnoDB: The InnoDB memory heap is disabled
2013-08-02 12:19:12 4536 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2013-08-02 12:19:12 4536 [Note] InnoDB: Compressed tables use zlib 1.2.3
2013-08-02 12:19:12 4536 [Note] InnoDB: Not using CPU crc32 instructions
2013-08-02 12:19:12 4536 [Note] InnoDB: Initializing buffer pool, size = 16.0M
2013-08-02 12:19:12 4536 [Note] InnoDB: Completed initialization of buffer pool
2013-08-02 12:19:12 4536 [Note] InnoDB: Highest supported file format is Barracuda.
2013-08-02 12:19:12 4536 [Note] InnoDB: The log sequence numbers 0 and 0 in ibdata files do not match the log sequence number 1616798 in the ib_logfiles!
2013-08-02 12:19:12 4536 [Note] InnoDB: Database was not shutdown normally!
2013-08-02 12:19:12 4536 [Note] InnoDB: Starting crash recovery.
2013-08-02 12:19:12 4536 [Note] InnoDB: Reading tablespace information from the .ibd files...
The most important error message is here:
2013-08-02 12:19:12 4536 [ERROR] InnoDB:
Attempted to open a previously opened tablespace.
Previous tablespace mysql/innodb_table_stats uses space ID: 1 at filepath: .\mysql\innodb_table_stats.ibd.
Cannot open tablespace xat/payments which uses space ID: 1 at filepath: .\xat\payments.ibd
The rest of the log:
InnoDB: Error: could not open single-table tablespace file .\xat\payments.ibd
InnoDB: We do not continue the crash recovery, because the table may become
InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.
InnoDB: To fix the problem and start mysqld:
InnoDB: 1) If there is a permission problem in the file and mysqld cannot
InnoDB: open the file, you should modify the permissions.
InnoDB: 2) If the table is not needed, or you can restore it from a backup,
InnoDB: then you can remove the .ibd file, and InnoDB will do a normal
InnoDB: crash recovery and ignore that table.
InnoDB: 3) If the file system or the disk is broken, and you cannot remove
InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf
InnoDB: and force InnoDB to continue crash recovery here.
What is the cause of these errors and how can I rectify them?
A:
IMPORTANT: do NOT delete ibdata1 file. You could destroy all your databases.
Instead, first try using the MySQL backup folder which is included with XAMPP. So do next steps:
Rename folder mysql/data to mysql/data_old
Make a copy of mysql/backup folder and name it as mysql/data
Copy all your database folders from mysql/data_old into mysql/data (except mysql, performance_schema, and phpmyadmin folders)
Copy mysql/data_old/ibdata1 file into mysql/data folder
Start MySQL from XAMPP control panel
And, voilà!
A:
IMPORTANT Deleting this file may render any existing MySQL data unusable. Use with caution
Hey I just did this and it worked:
exit Xampp server
go to your C:\xampp\mysql\data directory
delete the ibdata1 file
restart xampp server
It should work
A:
If the answers mentioned above are not working, you can try deleting all the files in data, except for the folder
Goto:
C:\xampp\mysql\data
After that:
Goto: C:\xampp\mysql\bin
then open with notepad my.ini
, Its look like this.
Then delete or put into comment the port 3306 and change it to 8111 then run xamp with administrator and its work well.
A:
Jun 2022
Disclaimer
Although many people said 'it worked' and very few say 'it didn't'.
It is hard to say what could be the cause and it is not working. Personally, the solution provided below worked for me and I didn't get any issues so far hence I am sharing this.
I don't suggest uninstalling, so you can basically back up the file and try this solution. If it doesn't work then place those files again.
Worked on other Versions
This issue works on other xampp versions too.
I have not tested personally, but some users have.
( If you have tested on a different version, let me know in the comment, I will add it here)
XAMPP v8.1.6 - Saeid Z
XAMPP v7.4.16 - CapelliC
XAMPP v3.3.0 - Myself
Feb 2022 (Problem)
I had the same problem today (2 feb 2022).
I fixed this using the same solution I mentioned below (See Dec 2021 (Solution))
XAMPP Issue Screenshot
XAMPP Fixed
Dec 2021 (Solution)
Since this question is active continuously,
I will try my best to solve it.
My issue
I visit this post every time this issue happens. The only thing I tried was that I uninstalled xampp and reinstalled it, which fixed the problem. That was on my old system.
I am using windows 10 brand new with no unwanted software or issues, and I got this unexpected shutdown again after a long time. I came to this question, hoping someone would tell me actually what was going on instead of fixing these issues. But unfortunately, I could not find it.
Just to clarify, my new issue is not with
port
unexpected shutdown
windows stuck
unwanted software
virus or malware.
One day I turned on xampp, and it stops working.
Method 1 (22 Dec 2021)
Stop MySQL.
Go to the C:/xampp/mysql directory and copy the data folder and keep it somewhere else (probably in another drive) as a backup.
Go to your original data folder (C:/xampp/mysql) and sort the files by 'Type.'
Select the files that have the type INFO File and delete them (screenshot below).
Start MySQL. It should work now.
Method 1 Screenshot
Important
Not necessarily the solution above will always fix the issue. Sometimes it will not. To avoid the major risk of losing the data, try these.
Turn on MySQL in the Control Panel ONLY IF NEEDED.
DO NOT set the XAMPP Control Panel to turn it on windows startup.
Back up DB whenever possible. If not try to back up every weekend.
PS: I will try to update this answer whenever the above method(s) don't work. I will try to explain it in the simplest way possible without uninstalling XAMPP.
Let me know if it works for you.
A:
Go to mysql/data/
Delete all random files (except the actual database folders)
Restart Apache and MySQL.
It should fix it.
A:
WORKING SOLUTION :- Follow the below listed steps.
Step 1. Rename the folder c:\xampp\mysql\data to c:\xampp\mysql\data_bkp (you can use any name).
Step 2. Create a new folder c:\xampp\mysql\data.
Step 3. Copy the content that resides in mysql\backup to the new mysql\data folder.
Step 4. Copy all your database folders that are in mysql\data_bkp to mysql\data (skipping the mysql, performance_schema, and phpmyadmin folders from mysql\data_bkp).
IMPORTATN NOTE :- Please do not replace the existing files while pasting(click skip these files)
Step 5. Finally copy the ibdata1 file from mysql\data_bkp and replace it inside mysql\data folder.
Step 6. Start MySQL from XAMPP control panel.
And, Its DONE . No databases lost, no ports changed, no run as administrator, no force recovery, no kill mysqld process, no restoring from previous versions, no more errors.
A:
Just follow two steps
go to xampp\mysql\backup
copy everything from backup folder
go to xampp\mysql\data
paste everything in data folder copied from backup folder
Thats all.
Also follow the video description to fix without losing any data:
https://www.youtube.com/watch?v=hB1wshpP3Jc
A:
UPDATE APRIL (2022)
Rename folder mysql/data to mysql/data_old
Make a copy of mysql/backup folder and name it as mysql/data
Copy all your database folders and mysql folder from mysql/data_old into mysql/data
Copy mysql/data_old/ibdata1 file into mysql/data folder
Start MySQL from XAMPP control panel
REFERENCE
https://www.youtube.com/watch?v=ipMedkjMupw&ab_channel=GeekyScript
A:
When you're not running XAMPP as an administrator, shutting down MySQL frequently causes corruption which means you have to repair or delete your tables. To avoid this you need to either run XAMPP as an administrator, or use the proper command prompt method for shutting down MySQL.
You can delete ibdata1 as Kratos suggests, but this can leave you with a broken database as other pieces of your database are still in the /mysql/data/ folder. In my case, this residual data stopped me successfully installing WordPress.
A cleaner way of undoing the damage is to revert your whole /mysql/data/ folder. Windows has built-in folder versioning — right click on /mysql/data/ and select Restore previous versions. You can then delete the current contents of the folder and replace it with the older version's contents.
Addendum: To ensure that you don't forget to run XAMPP as an administrator you can right click the XAMPP shortcut, go to Properties, then Advanced, and finally tick Run as administrator.
A:
I got the same kind of error in my C:\xampp\mysql\data\mysql_error.log when trying to start mysql.
2013-08-05 01:20:32 6780 [ERROR] InnoDB: Attempted to open a previously
opened tablespace. Previous tablespace mysql/slave_relay_log_info uses
space ID: 3 at filepath: .\mysql\slave_relay_log_info.ibd. Cannot open
tablespace test_database/test_table which uses space ID: 3 at filepath:
.\test_database\test_table.ibd
You'll have to read the error closely. This says that test_database is preventing mysql from starting.
You could blow away the offending database, these steps fix the problem:
Make sure mysql and xampp is shut down completely.
Go to your directory where mysql is installed, mine is: C:\xampp\mysql\data
You should see a folder with the name of a database that you created. mine was test_database.
Create a new folder somewhere else called C:\xampp\mysql\data\mysql\backuptablespace
Drag and drop (don't delete) the offending database table folder to the backup directory.
Try to start mysql again. For me it started right up in 1 second as expected.
If it doesn't work, put the file back where you started and you'll be back where you started.
If you don't want to delete the database and don't have backups:
If you don't have backups of table data and mysql won't start because something is corrupted you'll have to use the process of elimination to guess-and-check your way to exactly what you did that corrupted it. Follow these steps:
Make a clone of the entire C:\xampp\ and store it somewhere safe so you can get back to where you started.
Use a "binary search" approach to try to locate the corrupted item in the mysql database. It could be a file, or a table, or a database, or a user or anything.
Delete the entire database and see if that allows mysql to start. If it does, then put back the database and try removing some of the tables. If it doesn't, then try yanking out something else until it does start.
Try removing these files from C:\xampp\mysql\data\mysql:
db.frm
db.MRD
db.MYI
db.opt
user.frm
user.MYD
user.MYI
When you get mysql to start, try putting things back until you find the one thing that you add which prevents it from starting. One bonus for this is you learn how mysql works under the hood.
Nuclear option:
Something you did screwed up the mysql server. An uninstall and reinstall of XAMPP should undo the corruption.
A:
Add the following line below the [mysqld] section in the mysql config file (my.ini) and restart the apache web server and the mysql service afterwards.
[mysqld]
innodb_force_recovery = 4
A:
My Xampp MySQL worked just follows as below:
01.Go to mysql/data/ directory
02. delete the ibdata1 & ib_logfile*(ib_logfile0,ib_logfile1,ib_logfile101) file
03. restart xampp server
A:
Never delete this file (ibdata1) because all your data will be deleted!!!
I suggest three ways :
A:
1- Exit from XAMPP control panel.
1- Rename the folder mysql/data to mysql/data_old (you can use any name)
2- Create a new folder mysql/data
3- Copy the content that resides in mysql/backup to the new mysql/data folder
4- Copy all your database folders that are in mysql/data_old to mysql/data (skipping the mysql, performance_schema, and phpmyadmin folders from data_old)
5- Finally copy the ibdata1 file from mysql/data_old and replace it inside mysql/data folder
6- Reastart your system.
B:
1- Stop all sql services.
2- Next, start all sql services again.
C:
1- Open XAMPP control panel
2- Click on Config button, in front of mysql, click on my.ini
3- change client port and server port.
A:
Step 1 : Close Xampp controller completely
Step 2 : Open C:\xampp\mysql\backup
Step 3 : Copy all the files from backup folder
Step 4 : Open C:\xampp\mysql\data
Step 5 : Paste the all the files in data folder
Step 6 : Re-start the Xampp controller
A:
I have tried all the above answers but it didn't work for me. So finally I tried the below approach and it works 100% for me.
If you are worried about following the below steps you can take a backup of the entire XAMPP folder for the safe side.
Step 1: Rename the c:\xampp\mysql\data folder to c:\xampp\mysql\data_bkp
Step 2: Create a new folder c:\xampp\mysql\data.
Step 3: Copy the content, that is present inside c:\xampp\mysql\backup to the new c:\xampp\mysql\data folder.
Step 4: Copy all your database folders c:\xampp\mysql\data_bkp to c:\xampp\mysql\data (Note: Don't copy mysql, performance_schema, and phpmyadmin folders).
Step 5: Copy the ibdata1 file from c:\xampp\mysql\data_bkp and replace it inside the c:\xampp\mysql\data folder.
Step 6: Start MySQL from the XAMPP control panel.
A:
I also faced this issue and this is how I solved.
1. Make sure xampp is not under sub-directory. For example, it should be C:\xampp
2. You might need to run as administrator in running the application.
Hope this will work!
A:
in my case i did following steps and it worked:
In Xampp control panel click on "Services" button from the right side toolbar
Then find "MySQL" from the services List
Click on it and from the left side of the panel click on "stop"
Turn back in Xampp control panel and click on start.
A:
move xampp/mysql/backup files into xampp/mysql/data
RUN XAMPP as Administrator(make sure mysql is installed you can see a green tick if is installed)
Hope it helps!
A:
I have resolved the problem by ending the task for mysqlid on Task Manager.
A:
Here is the way you can solve this problem:
Go to C:\xampp\mysql\data
You will see a folder named as mysql/data
Rename that folder from mysql/data to something else like mysql/data_not_useful any name that you want to give.
Create a new folder named as mysql/data.
Copy all the files of the mysql/backup and paste in mysql/data.
Now go to mysql/data_not_useful and copy the file ibdata1 from there.
Then paste it in mysql/data (You have to replace the file).
Restart your xampp server.
Now run your mysql server.
A:
Here is what I did. I restarted my computer. Next I run services.msc. I stopped the MySQL service then restarted it. The restarted the Xampp server.
A:
No solution above worked for me. then I did below:
I deleted all the files inside C:\xampp\mysql\data\ directory except folders in this directory.
It worked perfectly fine but my previous databases are not working now.
So do above if you don't care it will delete all your previous databases in phpmyadmin.
A:
Simple solution
Open shell from Xampp Control Panel
mysqld --console --skip-grant-tables --skip-external-locking
Then again open an other shell and run
mysqlcheck -r --databases mysql --use-frm
Now close both shells and restart the xampp.
A:
i was facing the same issue and none of the solutions stated above helped me.
i went to the mysql configuration file (my.ini) and changed the port number under [mysqld].By default mysql runs on 3306 port.
port= 3306
i changed it to ,
port= 8111
Then run as Administrator.Finally this worked for me.
A:
This means that you already have a MySQL database running at port 3306.
In the XAMPP control panel, press the 'Config' button and after that press 'my.ini'. After this, Ctrl-F and search for '3306'. Replace any '3306' that you find with a different port number of your choice (you could choose 3307 or 3308 - I chose 2811 and it worked).
After you have replaced every location where '3306' is written, save the file and press 'Start' on the control panel again.
A:
Had the same issue.
STAEP 1
backup folder xampp/mysql/data (saved it as `xampp/mysql/_old_data`).
STAEP 2
Go to xampp/mysql/data and deleted all the files but not folders! With databases.
STAEP 3
At this stage your database will not work. You need to go to your backup folder `xampp/mysql/_old_data` and copy over "`ibdata1`" file to `xampp/mysql/data`.
After that everything work as expected including phpmyadmin and console.
STAEP 4
If this does not help. You can remove xampp/mysql/data folder and rename xampp/mysql/_old_data back to xampp/mysql/data.
(ROLLBACK) and try different things.
A:
Xampp stop Instantly after start.
copy all files and folder from C:\xampp\mysql\backup and paste into
C:\xampp\mysql\data.
A:
I solved similar MySQL error & I think this answer will help you to fix the same type of MySQL database error.
Solution:
Go to the “data” directory in the mysql database.
I installed XAMPP on D: drive on my computer & the mysql “data” directory location of my computer was “D:\xampp\mysql\data\”. You may have different location.
Take Backup of MySQL “data” Folder
First of all you should create a backup of the “data” folder using
any compression software.
Give a name like “data_backup.zip” or any type of compression you wish.
I used winrar compression software to compress & backup mysql “data” folder.
Rename the “data” folder
Rename the “data” folder to “data-oldfiles”. This is very important to rename the data directory to any new directory name.
Create a new “data” folder
Create a new folder and give the folder name as “data“
To solve the problem we need to create a new “data” directory in the mysql database.
Copy content from “backup” folder
Go to the “backup” folder and copy all files.
Paste the files from backup folder to data folder
Now start the MySQL database from XAMPP.
Your MySQL database will start properly without showing any error.
Transfer all MySQL projects Database, Data file & Log files
If you have many database which was used for various projects, then you have to transfer all database from “data-oldfiles” folder to “data” folder.
Copy all databases from the data-old files and paste to the data folder.
Now you have to copy the data file “ibdata1” & all log files “ib_logfile0, ib_logfile1 ” from data-old files folder to the data folder.
If you have many id_logiles then copied all of them.
Now Start MySQL from XAMPP.
Go to phpMyAdmin to check all databases are available & working.
Now start your any website project from localhost to check the MySQL database.
The Problem is solved !!
Now you will see the problem is solved and the error message “Error: MySQL shutdown unexpectedly.” will not show again.
If you have any question on this issue please feel free to ask any question in the comments section.
You can read the details tutorials on the link bellow:
Error: MySQL shutdown unexpectedly – Solution in 5 easy steps
You can also watch video tutorials to solve the problem:
[Solved] Error: MySQL shutdown unexpectedly
A:
go to : c: C:\xampp\mysql
Rename the folder "data" to "data_old" (you can use any name)
Create a new folder "data"
Copy the content of "backup" folder to the new "data" folder.
Copy all content of "data_old" to "data" (skip those folder "mysql", "performance_schema", and "phpmyadmin") *** without remplacing the file in the destination (skip theses files)**
restart XAMPP
and it will works
A:
I also get the same issue. Solution was kill process
Find the PID for port (3306)
netstat -a -n -o | find "3306"
You will see everything you need.
0.0.0.0:3306 0.0.0.0:0 LISTENING 8120 TCP
0.0.0.0:33060 0.0.0.0:0 LISTENING 8120 TCP
[::]:3306 [::]:0 LISTENING 8120 TCP
[::]:33060 [::]:0 LISTENING 8120
PID is 8120
Next run the following command
taskkill /PID 8120 /F
Start MySQL again. It will be fine. Happy cording.
A:
if you are using MariaDB you can try this:
Go to mysql/data/
Rename aria_log_control to aria_log_control_old
Restart "Mysql"
A:
Guys just make sure you dont have MySql Server installed. Because I have MySql server pre-installed and when I start mysql from xampp control panel some port conflicts are happening and its not working.. SO before starting the mysql from xampp control panel make sure mysql server is not installed. I use .net so I have installed mysql server in the Past. Uninstalling it solved my Problem....
A:
Copy all files from xampp/mysql/backup/ then paste into /xampp/mysql/data/
Restart mysql.
A:
0.cntr+alt+delet
1.end task mysqld
2.Restart mysql.
A:
What worked for me is (No File Delete):
First I open Logs for MySql in XAMPP panel.
At the end it says you are running another instance of mysqlid in port 3306
I opened my task manager(Ctrl+Shift+Esc) then find mysqlid and End the task.
A:
I had encountered the same issue, but all I had to do was close the XAMPP Control panel, go to the folder in which XAMPP is installed, find xampp-control.exe and run as administrator and then start the services.
A:
STOP! Please do NOT delete ibdata1 file!
Deleting this file is like playing a Russian roulette with your databases, it could work and restablish everything, but also, probably could leave unusable every database you have.
Instead, first try using the MySQL backup folder which is included with XAMPP. So do the next:
Rename the folder mysql/data to mysql/data_old (you can use any name)
Create a new folder mysql/data
Copy the content that resides in mysql/backup to the new mysql/data folder
Copy all your database folders that are in mysql/data_old to mysql/data (skipping the mysql, performance_schema, and phpmyadmin folders from data_old)
Finally copy the ibdata1 file from mysql/data_old and replace it inside mysql/data folder
Start MySQL from XAMPP control panel
A:
follow these steps:-
Go into C:\xampp\mysql
Rename data folder by data_old
Create a new folder empty data folder
Copy all files from data_old and paste them into the data folder
Copy all files from the backup folder and paste them in the data folder and replace all files
Copy ibdata1 files from data_old and paste and replace them in the data folder.
Restart Server
All the best!!
A:
Try the following solutions to fix the issue. Before performing this process, rename the data folder C:\xampp\mysql\data to the old_data.
Then create a new folder named data in the SQL folder.
Copy all the files and folders in the backup C:\xampp\mysql\backup folder into the data folder.
In the last step, copy the ibdata1 file and the test folder from the old_data folder and put it in the data folder.
Run the program now and enjoy!
A:
Go to xampp/mysql/data
Rename folder from data to data_backup
Create new folder data
Copy files from backup to data
delete ibdata1 from data folder
Copy ibdata1 from data_backup folder to data folder
Copy your all database from data_backup to data folder
Restart xampp. It will start working
A:
I had the same problem.
My xampp controll panel will start apache but not mysql.
The problem is in iblogfile.
This happens when you are running xampp/mysql and your pc restarts without properly shutting down the innodb engine.
Goto xampp/mysql and delete
ib_logfile0
and
ib_logfile1
Now restart mysql and it should work.
A:
Close Xampp
Open that folder
Select only the files not the folders in that Dir
Delete only the files, including those that are cached.
Open Xampp and start.
A:
In my case in which I synced my mysql data and htdocs to dropbox, I just needed to delete the conflicted files in mysql/data folder and subfolders. The conflicted files can be identified by its names, dropbox will tell you that. It has solved the problem for me.
A:
For me I quit Skype, which was occupying port 80, then Apache ran happily on port 80, than I ran Skype and it picked another port this time.
A:
Make sure the system time is correct. Mine was set to the year 2040 somehow, correcting the date solved the problem.
A:
i comment this statement in mysql/bin/my.ini
'innodb_additional_mem_pool_size=2M'
and it solve my problem. than you everyOne
A:
Go to task manager
And search mysqld and right click and select END TASK and refresh XAMPP
A:
For me, the problem was:
I used to hibernate my PC instead of shutting down due to the scale of the project. I was lazy enough to reopen all programs.
Before trying anything else, I recommend you to do the following simple things. Otherwise, you will be messed up your MySQL server.
Open your task manager and End the XAMPP process.
Re-run the XAMPP application as Administrator.
If not works,
Save all unsaved programs and restart the PC.
Run XAMMP as administrator.
Also, make sure to check 3306 & 5040 ports. These two ports are required to run MySQL on default settings.
Check @Ryan Williams answer to find of why it's good to run XAMPP as administrator.
A:
I literally deleted every file from c:\xampp\mysql\data\ except my.ini
and it works
A:
first of all, make a backup file of your database C:\xampp\mysql\data copy this file and past it somewhere in your pc. After this open, the data file and also open the XAMPP server try to delete the files step by step one by one after deleting each file try to run the MySQL server after deleting a single file as shown in the screenshot thus your databases won't delete. if the file deletion does not work then try to copy the same files from the backup folders and repeat this until it works... this is time taking but this worked for me I have solved this in 20 minutes.
A:
Go to C:\xampp\mysql\backup.
Copy all files.
Paste them into C:\xampp\mysql\data.
If Windows asks you to replace some files, replace them.
If your XAMPP Control Panes is active close it.
Go to C:\xampp and find xampp-control, run it.
Start Apache, start MySQL.
That's it.
Enjoy!
A:
Error: MySQL shutdown unexpectedly
This is the best answer
1)Rename the folder mysql/data to mysql/data_old (you can use any name)
2)Create a new folder mysql/data
3)Copy the content that resides in mysql/backup to the new mysql/data folder
4)Copy all your database folders that are in mysql/data_old to mysql/data (skipping the mysql, performance_schema, and phpmyadmin folders from data_old)
5)Finally copy the ibdata1 file from mysql/data_old and replace it inside mysql/data folder
6)Start MySQL from XAMPP control panel
A:
I faced the same issue. MySQL stops as soon as I turn it on.
In the logs it said:-
10:31:21 [mysql] Problem detected!
10:31:21 [mysql] Port 3306 in use by "Unable to open process"!
10:31:21 [mysql] MySQL WILL NOT start without the configured ports free!
10:31:21 [mysql] You need to uninstall/disable/reconfigure the blocking application
10:31:21 [mysql] or reconfigure MySQL and the Control Panel to listen on a different port
I stopped the running service on port 3306 wamp(in my case), and it worked fine after that.
Changing the port in config settings should also work.
YW!
A:
Simple solution
Rename below files in xampp\mysql\data folder
ib_logfile0
ib_logfile1
Or any such logfiles to
ib_logfile0.bak
ib_logfile1.bak
And now start mysql from xampp control.
A:
None of the solutions above are not working. It's working only temporarily. After a few days, we are facing the same issue again & again. I've lost all of my DBs on each and every time.
I don't know the exact solution. But, I am doing the 3 simple steps again & again.
Rename the folder c:\xampp\mysql\data to c:\xampp\mysql\data_old (you can use any name).
Create a new "data" folder c:\xampp\mysql\data
Copy all your database folders that are in mysql\data_old to mysql\data
then Start MySQL from the XAMPP control panel.
SOLVED!: I solved it using this method:
Open shell from from control panel and start mysql with this command:
mysqld –-console –-skip-grant-tables –-skip-external-locking
Open another shell from the control panel and repair the database with this command:
mysqlcheck -r --databases mysql --use-frm
Stop mysql, close shells, and restart mysql normally.
Refer: https://stackoverflow.com/a/60576807/1662058
A:
I open and empty the file multi-master.info which exists in data folder. this worked for me.
A:
Config->Apache->Open httpd.conf. search for Listen or 80,update listen port to 8081 save and restart server.
Oh and shutdown Skype if you have it.
A:
For this, you need to click on the x option under Modules Services and make MYSQL services installed. Then start the services. Here you go.
A:
If the crash message is "mysql.exe has stopped working". Just run xampp-control.exe as administrator will solve your problem instantly.
A:
If any of the things above do not work, make a back of Xampp directory and reinstall Xampp. That surely works!
A:
Rename below files from mysql/data
ib_logfile0
ib_logfile1
ibdata1
my.cnf
innodb_buffer_pool_size to 200M as per your ram
innodb_log_buffer_size to 32M
Restart your apache server
hope it helps you
A:
I solved! deactivate UAC with msconfig before to install xampp
A:
That's the more precise answer and worked for me!!!! !
A cleaner way of undoing the damage is to revert your whole /mysql/data/ folder. Windows has built-in folder versioning — right click on /mysql/data/ and select Restore previous versions. You can then delete the current contents of the folder and replace it with the older version's contents.
as mentioned above by Ryan Williams.
A:
Create a Back up your mysql folder from C:\xampp\mysql.
Then go to C:\xampp\mysql\backup Copy all the files and paste it into C:\xampp\mysql\data.
Then from your old backup folder see for ibdata1 file you can find it in C:\xampp\mysql\data. Copy this file and paste in into C:\xampp\mysql\data.
Now restart xampp and it should work.
A:
There are a number of things I've tried. This is the 2nd time this has happened to me. On my first time, I've to reinstall my xampp. And on the third day, mysql crashed again. I've tried everything I found on the internet. Like, innodb_flush_method=normal in my.ini file and deleting ibdata1, ib_logfile1, ib_logfile0 files, and others but none of these works.
So later I tried to run xampp with admin privilege and install apache and mysql as a service as it was instructed on xampp control panel itself. After starting mysql, I read error-log again and from there I came to know that one of my databases is responsible for this. That database file won't let mysql start. So I deleted everything in the data folder and then in cmd I navigated to C:/xampp/mysql/bin path and ran these commands:
mysqld --initialize
mysql_install_db
and mysql started running again.
But my databases and data are lost.
A:
If none of the solutions listed here didn't work for you just like me, then
Go to your task manager.
Go to the Services tab.
Find Service named "MySQL80".
Right-click on it and select "stop".
Go back to XAMPP control panel and start the MySQL service.
It worked for me.
A:
If none of the deletion of files work then probably your mysql service is not running.
Go to services.msc and start mysql service
A:
I also had this problem when i get this error , go xampp->mysql->data
then delete all other files without folder , do not delete folders ,
then run xampp and start mysql
A:
If you do not need data in the corrupt table, you can drop it by first discarding the tablespace:
ALTER TABLE sakila.actor DISCARD TABLESPACE;
after that you can drop the table itself:
DROP TABLE sakila.actor;
In case the first step is not working, first replace actor.ibd file with a copy from an empty table with the same structure.
Source
A:
# The MySQL server
default-character-set=utf8mb4
[mysqld]
skip-grant-tables // Palace this line here
port=3306
socket="C:/xampp/mysql/mysql.sock"
basedir="C:/xampp/mysql"
tmpdir="C:/xampp/tmp"
datadir="C:/xampp/mysql/data"
pid_file="mysql.pid"
# enable-named-pipe
key_buffer=16M
max_allowed_packet=1M
sort_buffer_size=512K
net_buffer_length=8K
read_buffer_size=256K
Open my.ini file from C:\xampp\mysql\data
skip-grant-tables place this line before port and restart and it working
A:
Remember Never delete this file (ibdata1) because all your data will be deleted
1- stop all running xampp services ( apache,mysql,..etc)
2- rename xampp folder to xampp-old
3- install fresh xampp
4- Restore Databases by copy these 3 files (ibdata1,ib_logfile0,ib_logfile1) + your database folders you created from xampp-old from this path
xampp-old\mysql\data
to
xampp\mysql\data
and accept replace files
5- Restore coded files by transfer xampp-old\htdocs to xampp\htdocs
now start xampp , it will work with all of your data
note: if you need to edit appache or mysql ini do this again
A:
You are getting this error because , your sql port 3306 is busy ( other app is using it )
stop the process of 3306 ( by closing that app end process )
but how to find that??
download the tcp viewer of microsoft
open the app and search for sql
you will see the sql is running and using 3306 port
that why the xampp's mysql is unable to run..
just end the process the myql and you are good to go
start the mysql of xampp and done
A:
Go to task manager and end your running MySQL task and restart your MySQL in XAMPP
A:
This happened when you already use the 3306 port. Just change the server port and it would be fixed.
A:
Open config file of MuSQL in Xamp and change port number to 3307
It worked for me :)
| How to solve "Error: MySQL shutdown unexpectedly"? | When I open XAMPP and click start MySQL button and it gives me an error.
I had started it just before, but now it isn't working.
12:19:12 PM [mysql] Attempting to start MySQL app...
12:19:12 PM [mysql] Status change detected: running
12:19:13 PM [mysql] Status change detected: stopped
12:19:13 PM [mysql] Error: MySQL shutdown unexpectedly.
12:19:13 PM [mysql] This may be due to a blocked port, missing dependencies,
12:19:13 PM [mysql] improper privileges, a crash, or a shutdown by another method
12:19:13 PM [mysql] Press the Logs button to view error logs and check
12:19:13 PM [mysql] the Windows Event Viewer for more clues
12:19:13 PM [mysql] If you need more help, copy and post this
12:19:13 PM [mysql] entire log window on the forums
Here is the contents of the error log:
2013-08-02 12:19:12 4536 [Note] Plugin 'FEDERATED' is disabled.
2013-08-02 12:19:12 f64 InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.
2013-08-02 12:19:12 4536 [Note] InnoDB: The InnoDB memory heap is disabled
2013-08-02 12:19:12 4536 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2013-08-02 12:19:12 4536 [Note] InnoDB: Compressed tables use zlib 1.2.3
2013-08-02 12:19:12 4536 [Note] InnoDB: Not using CPU crc32 instructions
2013-08-02 12:19:12 4536 [Note] InnoDB: Initializing buffer pool, size = 16.0M
2013-08-02 12:19:12 4536 [Note] InnoDB: Completed initialization of buffer pool
2013-08-02 12:19:12 4536 [Note] InnoDB: Highest supported file format is Barracuda.
2013-08-02 12:19:12 4536 [Note] InnoDB: The log sequence numbers 0 and 0 in ibdata files do not match the log sequence number 1616798 in the ib_logfiles!
2013-08-02 12:19:12 4536 [Note] InnoDB: Database was not shutdown normally!
2013-08-02 12:19:12 4536 [Note] InnoDB: Starting crash recovery.
2013-08-02 12:19:12 4536 [Note] InnoDB: Reading tablespace information from the .ibd files...
The most important error message is here:
2013-08-02 12:19:12 4536 [ERROR] InnoDB:
Attempted to open a previously opened tablespace.
Previous tablespace mysql/innodb_table_stats uses space ID: 1 at filepath: .\mysql\innodb_table_stats.ibd.
Cannot open tablespace xat/payments which uses space ID: 1 at filepath: .\xat\payments.ibd
The rest of the log:
InnoDB: Error: could not open single-table tablespace file .\xat\payments.ibd
InnoDB: We do not continue the crash recovery, because the table may become
InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.
InnoDB: To fix the problem and start mysqld:
InnoDB: 1) If there is a permission problem in the file and mysqld cannot
InnoDB: open the file, you should modify the permissions.
InnoDB: 2) If the table is not needed, or you can restore it from a backup,
InnoDB: then you can remove the .ibd file, and InnoDB will do a normal
InnoDB: crash recovery and ignore that table.
InnoDB: 3) If the file system or the disk is broken, and you cannot remove
InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf
InnoDB: and force InnoDB to continue crash recovery here.
What is the cause of these errors and how can I rectify them?
| [
"\nIMPORTANT: do NOT delete ibdata1 file. You could destroy all your databases.\n\nInstead, first try using the MySQL backup folder which is included with XAMPP. So do next steps:\n\nRename folder mysql/data to mysql/data_old\nMake a copy of mysql/backup folder and name it as mysql/data\nCopy all your database folders from mysql/data_old into mysql/data (except mysql, performance_schema, and phpmyadmin folders)\nCopy mysql/data_old/ibdata1 file into mysql/data folder\nStart MySQL from XAMPP control panel\n\nAnd, voilà!\n",
"\nIMPORTANT Deleting this file may render any existing MySQL data unusable. Use with caution\n\nHey I just did this and it worked:\n\nexit Xampp server\ngo to your C:\\xampp\\mysql\\data directory\ndelete the ibdata1 file\nrestart xampp server\n\nIt should work\n",
"If the answers mentioned above are not working, you can try deleting all the files in data, except for the folder\nGoto:\nC:\\xampp\\mysql\\data\n\nAfter that:\nGoto: C:\\xampp\\mysql\\bin\nthen open with notepad my.ini\n, Its look like this.\n\nThen delete or put into comment the port 3306 and change it to 8111 then run xamp with administrator and its work well.\n",
"Jun 2022\nDisclaimer\nAlthough many people said 'it worked' and very few say 'it didn't'.\nIt is hard to say what could be the cause and it is not working. Personally, the solution provided below worked for me and I didn't get any issues so far hence I am sharing this.\nI don't suggest uninstalling, so you can basically back up the file and try this solution. If it doesn't work then place those files again.\nWorked on other Versions\nThis issue works on other xampp versions too.\nI have not tested personally, but some users have.\n( If you have tested on a different version, let me know in the comment, I will add it here)\n\nXAMPP v8.1.6 - Saeid Z\nXAMPP v7.4.16 - CapelliC\nXAMPP v3.3.0 - Myself\n\nFeb 2022 (Problem)\nI had the same problem today (2 feb 2022).\nI fixed this using the same solution I mentioned below (See Dec 2021 (Solution))\nXAMPP Issue Screenshot\n\nXAMPP Fixed\n\nDec 2021 (Solution)\nSince this question is active continuously,\nI will try my best to solve it.\nMy issue\nI visit this post every time this issue happens. The only thing I tried was that I uninstalled xampp and reinstalled it, which fixed the problem. That was on my old system.\nI am using windows 10 brand new with no unwanted software or issues, and I got this unexpected shutdown again after a long time. I came to this question, hoping someone would tell me actually what was going on instead of fixing these issues. But unfortunately, I could not find it.\nJust to clarify, my new issue is not with\n\nport\nunexpected shutdown\nwindows stuck\nunwanted software\nvirus or malware.\n\nOne day I turned on xampp, and it stops working.\nMethod 1 (22 Dec 2021)\n\nStop MySQL.\nGo to the C:/xampp/mysql directory and copy the data folder and keep it somewhere else (probably in another drive) as a backup.\nGo to your original data folder (C:/xampp/mysql) and sort the files by 'Type.'\nSelect the files that have the type INFO File and delete them (screenshot below).\nStart MySQL. It should work now.\n\nMethod 1 Screenshot\n\nImportant\nNot necessarily the solution above will always fix the issue. Sometimes it will not. To avoid the major risk of losing the data, try these.\n\nTurn on MySQL in the Control Panel ONLY IF NEEDED.\nDO NOT set the XAMPP Control Panel to turn it on windows startup.\nBack up DB whenever possible. If not try to back up every weekend.\n\nPS: I will try to update this answer whenever the above method(s) don't work. I will try to explain it in the simplest way possible without uninstalling XAMPP.\nLet me know if it works for you.\n",
"\nGo to mysql/data/ \nDelete all random files (except the actual database folders) \nRestart Apache and MySQL.\n\nIt should fix it.\n",
"\nWORKING SOLUTION :- Follow the below listed steps.\n\nStep 1. Rename the folder c:\\xampp\\mysql\\data to c:\\xampp\\mysql\\data_bkp (you can use any name).\nStep 2. Create a new folder c:\\xampp\\mysql\\data.\nStep 3. Copy the content that resides in mysql\\backup to the new mysql\\data folder.\nStep 4. Copy all your database folders that are in mysql\\data_bkp to mysql\\data (skipping the mysql, performance_schema, and phpmyadmin folders from mysql\\data_bkp).\nIMPORTATN NOTE :- Please do not replace the existing files while pasting(click skip these files)\n\nStep 5. Finally copy the ibdata1 file from mysql\\data_bkp and replace it inside mysql\\data folder.\nStep 6. Start MySQL from XAMPP control panel.\nAnd, Its DONE . No databases lost, no ports changed, no run as administrator, no force recovery, no kill mysqld process, no restoring from previous versions, no more errors.\n",
"Just follow two steps\n\ngo to xampp\\mysql\\backup\ncopy everything from backup folder\n\ngo to xampp\\mysql\\data\npaste everything in data folder copied from backup folder\n\nThats all.\n\n\nAlso follow the video description to fix without losing any data:\nhttps://www.youtube.com/watch?v=hB1wshpP3Jc\n",
"UPDATE APRIL (2022)\n\nRename folder mysql/data to mysql/data_old\nMake a copy of mysql/backup folder and name it as mysql/data\nCopy all your database folders and mysql folder from mysql/data_old into mysql/data\nCopy mysql/data_old/ibdata1 file into mysql/data folder\n\nStart MySQL from XAMPP control panel\nREFERENCE\nhttps://www.youtube.com/watch?v=ipMedkjMupw&ab_channel=GeekyScript\n",
"When you're not running XAMPP as an administrator, shutting down MySQL frequently causes corruption which means you have to repair or delete your tables. To avoid this you need to either run XAMPP as an administrator, or use the proper command prompt method for shutting down MySQL.\nYou can delete ibdata1 as Kratos suggests, but this can leave you with a broken database as other pieces of your database are still in the /mysql/data/ folder. In my case, this residual data stopped me successfully installing WordPress.\nA cleaner way of undoing the damage is to revert your whole /mysql/data/ folder. Windows has built-in folder versioning — right click on /mysql/data/ and select Restore previous versions. You can then delete the current contents of the folder and replace it with the older version's contents.\nAddendum: To ensure that you don't forget to run XAMPP as an administrator you can right click the XAMPP shortcut, go to Properties, then Advanced, and finally tick Run as administrator.\n",
"I got the same kind of error in my C:\\xampp\\mysql\\data\\mysql_error.log when trying to start mysql.\n2013-08-05 01:20:32 6780 [ERROR] InnoDB: Attempted to open a previously \n opened tablespace. Previous tablespace mysql/slave_relay_log_info uses \n space ID: 3 at filepath: .\\mysql\\slave_relay_log_info.ibd. Cannot open \n tablespace test_database/test_table which uses space ID: 3 at filepath: \n .\\test_database\\test_table.ibd\n\nYou'll have to read the error closely. This says that test_database is preventing mysql from starting.\nYou could blow away the offending database, these steps fix the problem:\n\nMake sure mysql and xampp is shut down completely.\nGo to your directory where mysql is installed, mine is: C:\\xampp\\mysql\\data\nYou should see a folder with the name of a database that you created. mine was test_database.\nCreate a new folder somewhere else called C:\\xampp\\mysql\\data\\mysql\\backuptablespace\nDrag and drop (don't delete) the offending database table folder to the backup directory.\nTry to start mysql again. For me it started right up in 1 second as expected.\n\nIf it doesn't work, put the file back where you started and you'll be back where you started.\nIf you don't want to delete the database and don't have backups:\nIf you don't have backups of table data and mysql won't start because something is corrupted you'll have to use the process of elimination to guess-and-check your way to exactly what you did that corrupted it. Follow these steps:\n\nMake a clone of the entire C:\\xampp\\ and store it somewhere safe so you can get back to where you started.\nUse a \"binary search\" approach to try to locate the corrupted item in the mysql database. It could be a file, or a table, or a database, or a user or anything.\nDelete the entire database and see if that allows mysql to start. If it does, then put back the database and try removing some of the tables. If it doesn't, then try yanking out something else until it does start.\nTry removing these files from C:\\xampp\\mysql\\data\\mysql:\ndb.frm\ndb.MRD\ndb.MYI\ndb.opt\nuser.frm\nuser.MYD\nuser.MYI\nWhen you get mysql to start, try putting things back until you find the one thing that you add which prevents it from starting. One bonus for this is you learn how mysql works under the hood.\n\nNuclear option:\nSomething you did screwed up the mysql server. An uninstall and reinstall of XAMPP should undo the corruption.\n",
"Add the following line below the [mysqld] section in the mysql config file (my.ini) and restart the apache web server and the mysql service afterwards.\n[mysqld]\ninnodb_force_recovery = 4\n\n",
"My Xampp MySQL worked just follows as below:\n01.Go to mysql/data/ directory\n02. delete the ibdata1 & ib_logfile*(ib_logfile0,ib_logfile1,ib_logfile101) file\n03. restart xampp server\n\n",
"Never delete this file (ibdata1) because all your data will be deleted!!!\nI suggest three ways :\nA:\n1- Exit from XAMPP control panel.\n1- Rename the folder mysql/data to mysql/data_old (you can use any name)\n2- Create a new folder mysql/data\n3- Copy the content that resides in mysql/backup to the new mysql/data folder\n4- Copy all your database folders that are in mysql/data_old to mysql/data (skipping the mysql, performance_schema, and phpmyadmin folders from data_old)\n5- Finally copy the ibdata1 file from mysql/data_old and replace it inside mysql/data folder\n6- Reastart your system.\nB:\n1- Stop all sql services.\n2- Next, start all sql services again.\n\nC:\n1- Open XAMPP control panel\n2- Click on Config button, in front of mysql, click on my.ini\n\n3- change client port and server port.\n\n",
"Step 1 : Close Xampp controller completely\nStep 2 : Open C:\\xampp\\mysql\\backup\nStep 3 : Copy all the files from backup folder\nStep 4 : Open C:\\xampp\\mysql\\data\nStep 5 : Paste the all the files in data folder\nStep 6 : Re-start the Xampp controller\n",
"I have tried all the above answers but it didn't work for me. So finally I tried the below approach and it works 100% for me.\nIf you are worried about following the below steps you can take a backup of the entire XAMPP folder for the safe side.\nStep 1: Rename the c:\\xampp\\mysql\\data folder to c:\\xampp\\mysql\\data_bkp\nStep 2: Create a new folder c:\\xampp\\mysql\\data.\nStep 3: Copy the content, that is present inside c:\\xampp\\mysql\\backup to the new c:\\xampp\\mysql\\data folder.\nStep 4: Copy all your database folders c:\\xampp\\mysql\\data_bkp to c:\\xampp\\mysql\\data (Note: Don't copy mysql, performance_schema, and phpmyadmin folders).\nStep 5: Copy the ibdata1 file from c:\\xampp\\mysql\\data_bkp and replace it inside the c:\\xampp\\mysql\\data folder.\nStep 6: Start MySQL from the XAMPP control panel.\n",
"I also faced this issue and this is how I solved. \n1. Make sure xampp is not under sub-directory. For example, it should be C:\\xampp \n2. You might need to run as administrator in running the application.\nHope this will work!\n",
"in my case i did following steps and it worked:\n\nIn Xampp control panel click on \"Services\" button from the right side toolbar\nThen find \"MySQL\" from the services List\nClick on it and from the left side of the panel click on \"stop\"\nTurn back in Xampp control panel and click on start.\n\n",
"\nmove xampp/mysql/backup files into xampp/mysql/data\nRUN XAMPP as Administrator(make sure mysql is installed you can see a green tick if is installed)\n\n\nHope it helps!\n",
"I have resolved the problem by ending the task for mysqlid on Task Manager.\n",
"Here is the way you can solve this problem:\n\nGo to C:\\xampp\\mysql\\data\nYou will see a folder named as mysql/data\nRename that folder from mysql/data to something else like mysql/data_not_useful any name that you want to give.\nCreate a new folder named as mysql/data.\nCopy all the files of the mysql/backup and paste in mysql/data.\nNow go to mysql/data_not_useful and copy the file ibdata1 from there.\nThen paste it in mysql/data (You have to replace the file).\nRestart your xampp server.\nNow run your mysql server.\n\n",
"Here is what I did. I restarted my computer. Next I run services.msc. I stopped the MySQL service then restarted it. The restarted the Xampp server.\n",
"No solution above worked for me. then I did below:\nI deleted all the files inside C:\\xampp\\mysql\\data\\ directory except folders in this directory.\nIt worked perfectly fine but my previous databases are not working now.\nSo do above if you don't care it will delete all your previous databases in phpmyadmin.\n",
"Simple solution\nOpen shell from Xampp Control Panel\nmysqld --console --skip-grant-tables --skip-external-locking\n\nThen again open an other shell and run\nmysqlcheck -r --databases mysql --use-frm\n\nNow close both shells and restart the xampp.\n",
"i was facing the same issue and none of the solutions stated above helped me.\ni went to the mysql configuration file (my.ini) and changed the port number under [mysqld].By default mysql runs on 3306 port.\nport= 3306\n\ni changed it to ,\nport= 8111\n\nThen run as Administrator.Finally this worked for me.\n",
"This means that you already have a MySQL database running at port 3306.\nIn the XAMPP control panel, press the 'Config' button and after that press 'my.ini'. After this, Ctrl-F and search for '3306'. Replace any '3306' that you find with a different port number of your choice (you could choose 3307 or 3308 - I chose 2811 and it worked).\nAfter you have replaced every location where '3306' is written, save the file and press 'Start' on the control panel again.\n",
"Had the same issue.\nSTAEP 1\nbackup folder xampp/mysql/data (saved it as `xampp/mysql/_old_data`). \n\n\nSTAEP 2\nGo to xampp/mysql/data and deleted all the files but not folders! With databases.\n\n\nSTAEP 3\nAt this stage your database will not work. You need to go to your backup folder `xampp/mysql/_old_data` and copy over \"`ibdata1`\" file to `xampp/mysql/data`. \nAfter that everything work as expected including phpmyadmin and console.\nSTAEP 4\nIf this does not help. You can remove xampp/mysql/data folder and rename xampp/mysql/_old_data back to xampp/mysql/data.\n(ROLLBACK) and try different things.\n",
"Xampp stop Instantly after start.\n\ncopy all files and folder from C:\\xampp\\mysql\\backup and paste into\nC:\\xampp\\mysql\\data.\n\n\n",
"I solved similar MySQL error & I think this answer will help you to fix the same type of MySQL database error.\n\nSolution:\n\nGo to the “data” directory in the mysql database.\nI installed XAMPP on D: drive on my computer & the mysql “data” directory location of my computer was “D:\\xampp\\mysql\\data\\”. You may have different location.\n\nTake Backup of MySQL “data” Folder\n\nFirst of all you should create a backup of the “data” folder using\nany compression software.\n\nGive a name like “data_backup.zip” or any type of compression you wish.\n\nI used winrar compression software to compress & backup mysql “data” folder.\n\n\nRename the “data” folder\n\nRename the “data” folder to “data-oldfiles”. This is very important to rename the data directory to any new directory name.\n\nCreate a new “data” folder\n\nCreate a new folder and give the folder name as “data“\nTo solve the problem we need to create a new “data” directory in the mysql database.\n\nCopy content from “backup” folder\n\nGo to the “backup” folder and copy all files.\nPaste the files from backup folder to data folder\nNow start the MySQL database from XAMPP.\nYour MySQL database will start properly without showing any error.\n\nTransfer all MySQL projects Database, Data file & Log files\n\nIf you have many database which was used for various projects, then you have to transfer all database from “data-oldfiles” folder to “data” folder.\n\nCopy all databases from the data-old files and paste to the data folder.\n\nNow you have to copy the data file “ibdata1” & all log files “ib_logfile0, ib_logfile1 ” from data-old files folder to the data folder.\n\nIf you have many id_logiles then copied all of them.\n\nNow Start MySQL from XAMPP.\n\nGo to phpMyAdmin to check all databases are available & working.\n\nNow start your any website project from localhost to check the MySQL database.\n\n\nThe Problem is solved !!\n\n\nNow you will see the problem is solved and the error message “Error: MySQL shutdown unexpectedly.” will not show again.\nIf you have any question on this issue please feel free to ask any question in the comments section.\n\nYou can read the details tutorials on the link bellow:\nError: MySQL shutdown unexpectedly – Solution in 5 easy steps\nYou can also watch video tutorials to solve the problem:\n[Solved] Error: MySQL shutdown unexpectedly\n",
"go to : c: C:\\xampp\\mysql\nRename the folder \"data\" to \"data_old\" (you can use any name)\nCreate a new folder \"data\"\nCopy the content of \"backup\" folder to the new \"data\" folder.\nCopy all content of \"data_old\" to \"data\" (skip those folder \"mysql\", \"performance_schema\", and \"phpmyadmin\") *** without remplacing the file in the destination (skip theses files)**\nrestart XAMPP\nand it will works\n",
"I also get the same issue. Solution was kill process\nFind the PID for port (3306)\nnetstat -a -n -o | find \"3306\"\n\nYou will see everything you need.\n0.0.0.0:3306 0.0.0.0:0 LISTENING 8120 TCP \n0.0.0.0:33060 0.0.0.0:0 LISTENING 8120 TCP \n[::]:3306 [::]:0 LISTENING 8120 TCP \n[::]:33060 [::]:0 LISTENING 8120\n\nPID is 8120\nNext run the following command\ntaskkill /PID 8120 /F\n\nStart MySQL again. It will be fine. Happy cording.\n",
"if you are using MariaDB you can try this:\n\nGo to mysql/data/\nRename aria_log_control to aria_log_control_old\nRestart \"Mysql\"\n\n",
"Guys just make sure you dont have MySql Server installed. Because I have MySql server pre-installed and when I start mysql from xampp control panel some port conflicts are happening and its not working.. SO before starting the mysql from xampp control panel make sure mysql server is not installed. I use .net so I have installed mysql server in the Past. Uninstalling it solved my Problem....\n",
"\nCopy all files from xampp/mysql/backup/ then paste into /xampp/mysql/data/ \nRestart mysql.\n\n",
"0.cntr+alt+delet\n1.end task mysqld\n2.Restart mysql.\n\n\n",
"What worked for me is (No File Delete):\n\nFirst I open Logs for MySql in XAMPP panel.\nAt the end it says you are running another instance of mysqlid in port 3306\nI opened my task manager(Ctrl+Shift+Esc) then find mysqlid and End the task.\n\n",
"I had encountered the same issue, but all I had to do was close the XAMPP Control panel, go to the folder in which XAMPP is installed, find xampp-control.exe and run as administrator and then start the services.\n\n",
"STOP! Please do NOT delete ibdata1 file!\nDeleting this file is like playing a Russian roulette with your databases, it could work and restablish everything, but also, probably could leave unusable every database you have.\nInstead, first try using the MySQL backup folder which is included with XAMPP. So do the next:\nRename the folder mysql/data to mysql/data_old (you can use any name)\nCreate a new folder mysql/data\nCopy the content that resides in mysql/backup to the new mysql/data folder\nCopy all your database folders that are in mysql/data_old to mysql/data (skipping the mysql, performance_schema, and phpmyadmin folders from data_old)\nFinally copy the ibdata1 file from mysql/data_old and replace it inside mysql/data folder\nStart MySQL from XAMPP control panel\n",
"follow these steps:-\n\nGo into C:\\xampp\\mysql\n\nRename data folder by data_old\n\nCreate a new folder empty data folder\n\nCopy all files from data_old and paste them into the data folder\n\nCopy all files from the backup folder and paste them in the data folder and replace all files\n\nCopy ibdata1 files from data_old and paste and replace them in the data folder.\n\nRestart Server\n\n\nAll the best!!\n",
"Try the following solutions to fix the issue. Before performing this process, rename the data folder C:\\xampp\\mysql\\data to the old_data.\nThen create a new folder named data in the SQL folder.\nCopy all the files and folders in the backup C:\\xampp\\mysql\\backup folder into the data folder.\nIn the last step, copy the ibdata1 file and the test folder from the old_data folder and put it in the data folder.\nRun the program now and enjoy!\n",
"Go to xampp/mysql/data\n\nRename folder from data to data_backup\nCreate new folder data\nCopy files from backup to data\ndelete ibdata1 from data folder\nCopy ibdata1 from data_backup folder to data folder\nCopy your all database from data_backup to data folder\nRestart xampp. It will start working\n\n",
"I had the same problem.\nMy xampp controll panel will start apache but not mysql.\nThe problem is in iblogfile.\nThis happens when you are running xampp/mysql and your pc restarts without properly shutting down the innodb engine.\nGoto xampp/mysql and delete\n\nib_logfile0\n\nand\n\nib_logfile1\n\nNow restart mysql and it should work.\n",
"\nClose Xampp\nOpen that folder\nSelect only the files not the folders in that Dir\nDelete only the files, including those that are cached.\nOpen Xampp and start.\n\n\n",
"In my case in which I synced my mysql data and htdocs to dropbox, I just needed to delete the conflicted files in mysql/data folder and subfolders. The conflicted files can be identified by its names, dropbox will tell you that. It has solved the problem for me.\n",
"For me I quit Skype, which was occupying port 80, then Apache ran happily on port 80, than I ran Skype and it picked another port this time.\n",
"Make sure the system time is correct. Mine was set to the year 2040 somehow, correcting the date solved the problem.\n",
"i comment this statement in mysql/bin/my.ini \n'innodb_additional_mem_pool_size=2M'\n\nand it solve my problem. than you everyOne\n",
"Go to task manager\nAnd search mysqld and right click and select END TASK and refresh XAMPP \n",
"For me, the problem was:\nI used to hibernate my PC instead of shutting down due to the scale of the project. I was lazy enough to reopen all programs.\nBefore trying anything else, I recommend you to do the following simple things. Otherwise, you will be messed up your MySQL server.\n\nOpen your task manager and End the XAMPP process.\nRe-run the XAMPP application as Administrator. \n\nIf not works,\n\nSave all unsaved programs and restart the PC.\nRun XAMMP as administrator.\n\nAlso, make sure to check 3306 & 5040 ports. These two ports are required to run MySQL on default settings.\nCheck @Ryan Williams answer to find of why it's good to run XAMPP as administrator.\n",
"I literally deleted every file from c:\\xampp\\mysql\\data\\ except my.ini \nand it works\n",
"first of all, make a backup file of your database C:\\xampp\\mysql\\data copy this file and past it somewhere in your pc. After this open, the data file and also open the XAMPP server try to delete the files step by step one by one after deleting each file try to run the MySQL server after deleting a single file as shown in the screenshot thus your databases won't delete. if the file deletion does not work then try to copy the same files from the backup folders and repeat this until it works... this is time taking but this worked for me I have solved this in 20 minutes.\n\n",
"Go to C:\\xampp\\mysql\\backup.\nCopy all files.\nPaste them into C:\\xampp\\mysql\\data.\nIf Windows asks you to replace some files, replace them.\nIf your XAMPP Control Panes is active close it.\nGo to C:\\xampp and find xampp-control, run it.\nStart Apache, start MySQL.\n\nThat's it.\nEnjoy!\n",
"Error: MySQL shutdown unexpectedly\n\nThis is the best answer \n\n1)Rename the folder mysql/data to mysql/data_old (you can use any name)\n2)Create a new folder mysql/data\n3)Copy the content that resides in mysql/backup to the new mysql/data folder\n4)Copy all your database folders that are in mysql/data_old to mysql/data (skipping the mysql, performance_schema, and phpmyadmin folders from data_old)\n5)Finally copy the ibdata1 file from mysql/data_old and replace it inside mysql/data folder\n6)Start MySQL from XAMPP control panel\n\n",
"I faced the same issue. MySQL stops as soon as I turn it on.\nIn the logs it said:-\n\n10:31:21 [mysql] Problem detected!\n10:31:21 [mysql] Port 3306 in use by \"Unable to open process\"!\n10:31:21 [mysql] MySQL WILL NOT start without the configured ports free!\n10:31:21 [mysql] You need to uninstall/disable/reconfigure the blocking application\n10:31:21 [mysql] or reconfigure MySQL and the Control Panel to listen on a different port\n\nI stopped the running service on port 3306 wamp(in my case), and it worked fine after that.\nChanging the port in config settings should also work.\nYW!\n",
"Simple solution\nRename below files in xampp\\mysql\\data folder\n ib_logfile0\n ib_logfile1\n\nOr any such logfiles to\n ib_logfile0.bak\n ib_logfile1.bak\n\nAnd now start mysql from xampp control.\n",
"None of the solutions above are not working. It's working only temporarily. After a few days, we are facing the same issue again & again. I've lost all of my DBs on each and every time.\nI don't know the exact solution. But, I am doing the 3 simple steps again & again.\n\nRename the folder c:\\xampp\\mysql\\data to c:\\xampp\\mysql\\data_old (you can use any name).\nCreate a new \"data\" folder c:\\xampp\\mysql\\data\nCopy all your database folders that are in mysql\\data_old to mysql\\data\n\nthen Start MySQL from the XAMPP control panel.\nSOLVED!: I solved it using this method:\nOpen shell from from control panel and start mysql with this command:\nmysqld –-console –-skip-grant-tables –-skip-external-locking\n\nOpen another shell from the control panel and repair the database with this command:\nmysqlcheck -r --databases mysql --use-frm\n\nStop mysql, close shells, and restart mysql normally.\nRefer: https://stackoverflow.com/a/60576807/1662058\n",
"I open and empty the file multi-master.info which exists in data folder. this worked for me.\n",
"Config->Apache->Open httpd.conf. search for Listen or 80,update listen port to 8081 save and restart server.\nOh and shutdown Skype if you have it.\n",
"For this, you need to click on the x option under Modules Services and make MYSQL services installed. Then start the services. Here you go.\n",
"If the crash message is \"mysql.exe has stopped working\". Just run xampp-control.exe as administrator will solve your problem instantly.\n",
"If any of the things above do not work, make a back of Xampp directory and reinstall Xampp. That surely works!\n",
"Rename below files from mysql/data\nib_logfile0\nib_logfile1\nibdata1\nmy.cnf \ninnodb_buffer_pool_size to 200M as per your ram\ninnodb_log_buffer_size to 32M\nRestart your apache server\nhope it helps you\n",
"I solved! deactivate UAC with msconfig before to install xampp\n\n",
"That's the more precise answer and worked for me!!!! !\nA cleaner way of undoing the damage is to revert your whole /mysql/data/ folder. Windows has built-in folder versioning — right click on /mysql/data/ and select Restore previous versions. You can then delete the current contents of the folder and replace it with the older version's contents.\nas mentioned above by Ryan Williams.\n",
"\nCreate a Back up your mysql folder from C:\\xampp\\mysql.\nThen go to C:\\xampp\\mysql\\backup Copy all the files and paste it into C:\\xampp\\mysql\\data.\nThen from your old backup folder see for ibdata1 file you can find it in C:\\xampp\\mysql\\data. Copy this file and paste in into C:\\xampp\\mysql\\data.\nNow restart xampp and it should work.\n",
"There are a number of things I've tried. This is the 2nd time this has happened to me. On my first time, I've to reinstall my xampp. And on the third day, mysql crashed again. I've tried everything I found on the internet. Like, innodb_flush_method=normal in my.ini file and deleting ibdata1, ib_logfile1, ib_logfile0 files, and others but none of these works.\nSo later I tried to run xampp with admin privilege and install apache and mysql as a service as it was instructed on xampp control panel itself. After starting mysql, I read error-log again and from there I came to know that one of my databases is responsible for this. That database file won't let mysql start. So I deleted everything in the data folder and then in cmd I navigated to C:/xampp/mysql/bin path and ran these commands:\n\nmysqld --initialize\n\n\nmysql_install_db\n\nand mysql started running again.\nBut my databases and data are lost.\n",
"If none of the solutions listed here didn't work for you just like me, then\n\nGo to your task manager.\nGo to the Services tab.\nFind Service named \"MySQL80\".\nRight-click on it and select \"stop\".\nGo back to XAMPP control panel and start the MySQL service.\n\nIt worked for me.\n",
"If none of the deletion of files work then probably your mysql service is not running.\nGo to services.msc and start mysql service\n",
"I also had this problem when i get this error , go xampp->mysql->data\nthen delete all other files without folder , do not delete folders ,\nthen run xampp and start mysql\n",
"If you do not need data in the corrupt table, you can drop it by first discarding the tablespace:\nALTER TABLE sakila.actor DISCARD TABLESPACE;\n\nafter that you can drop the table itself:\nDROP TABLE sakila.actor;\n\nIn case the first step is not working, first replace actor.ibd file with a copy from an empty table with the same structure.\nSource\n",
"# The MySQL server\ndefault-character-set=utf8mb4\n[mysqld]\nskip-grant-tables // Palace this line here \nport=3306\nsocket=\"C:/xampp/mysql/mysql.sock\"\nbasedir=\"C:/xampp/mysql\"\ntmpdir=\"C:/xampp/tmp\"\ndatadir=\"C:/xampp/mysql/data\"\npid_file=\"mysql.pid\"\n# enable-named-pipe\nkey_buffer=16M\nmax_allowed_packet=1M\nsort_buffer_size=512K\nnet_buffer_length=8K\nread_buffer_size=256K\n\nOpen my.ini file from C:\\xampp\\mysql\\data\nskip-grant-tables place this line before port and restart and it working\n",
"Remember Never delete this file (ibdata1) because all your data will be deleted\n1- stop all running xampp services ( apache,mysql,..etc)\n2- rename xampp folder to xampp-old\n3- install fresh xampp\n4- Restore Databases by copy these 3 files (ibdata1,ib_logfile0,ib_logfile1) + your database folders you created from xampp-old from this path\nxampp-old\\mysql\\data\nto\nxampp\\mysql\\data\nand accept replace files\n5- Restore coded files by transfer xampp-old\\htdocs to xampp\\htdocs\nnow start xampp , it will work with all of your data\nnote: if you need to edit appache or mysql ini do this again\n",
"You are getting this error because , your sql port 3306 is busy ( other app is using it )\nstop the process of 3306 ( by closing that app end process )\nbut how to find that??\ndownload the tcp viewer of microsoft\nopen the app and search for sql\nyou will see the sql is running and using 3306 port\nthat why the xampp's mysql is unable to run..\njust end the process the myql and you are good to go\nstart the mysql of xampp and done\n",
"Go to task manager and end your running MySQL task and restart your MySQL in XAMPP\n",
"This happened when you already use the 3306 port. Just change the server port and it would be fixed.\n",
"Open config file of MuSQL in Xamp and change port number to 3307\nIt worked for me :)\n"
] | [
1606,
212,
78,
76,
52,
42,
32,
27,
23,
15,
14,
14,
12,
12,
11,
10,
7,
7,
6,
6,
5,
5,
5,
4,
4,
4,
4,
3,
3,
3,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
"Fixed it by reinstalling the Xampp.\nIf you don't want to go through all the technical stuff that the other proposes.\nBack up the htdocs folder then uninstall Xampp,\nit will ask you if you want to retain the htdocs folder, opt-out.\nCompletely uninstall,\nremove the remains.\nThe install again,\ncopy back your backed-up htdocs folder.\nyou're done.\n",
"Step 01 : If you have an Error with starting XAMPP MySQL,\nFollow These Steps To Easy Solving This Problem.\n\nStep 02 : Stop the Server and go to Config.\n\nStep 03: Open this my.ini file.\n\nStep 04: Find These 2 Port numbers in your notepad text.\n\nStep 05: Change these 2 port numbers 3306 --> 3308 or any other number.\n\nAfter Save the text file using Ctrl+S\nStep 07 : Go to your XAMPP installation Folder and open XAMPP Folder.\nStep 08 : Find phpMyAdmin folder.\n\nStep 09: Open the phpMyAdmin Folder and Find config.inc.php file.\n\nStep 10: Change Here Port number that previous you Change in Step 05. (Like 3008) and Save This Text File.\n\nStep 11: After Close all Files and Go to your XAMPP Server.\nStep 12: Start again MySQL Server.\n\nStep 13: Open Your Web Browser and Type in URL -->> localhost\nStep 14: Go to PhpMyAdmin\n\nStep 15: phpMyAdmin is Working properly Now.\n\nif you have any Error in Starting Apache Server,\nStep 01 : Stop The Server, and Open Config File.\n\n\nStep 02: Find this Listen number in your text file.\n\nStep 03: Change that 80 to 8000 or any other value. and save text file.\n\nStep 04: After saving text file, Open your XAMPP Server and Start Apache Server Again.\n\nStep 05: After Open your web browser.\nStep 06: Type localhost:8000\n\nStep 07: Now you Can Open Your phpMyAdmin.\n\nNote : After Changing Apache port number, You Must add in to that after the localhost: in your URL.\n-----------Thank You Guys-----------\n",
"Solve in 10 Seconds\n\nGo to mySql folder inside your xampp folder\nrename data folder as data-old\ncreate new folder name it as data\ncopy all the contents of the backup folder into new data folder...\n\nYou are good to go\n",
"Working fine in 04-Dec-2022.\nJust 3 steps.\n\nFor safe side, make a backup of the folder mysql/data.\nNow copy all (files and folders) of the folder mysql/backup except file ibdata1 then paste and replace the existing files of folder mysql/data.\nStart MySQL from XAMPP control panel.\n\nIt will work now.\n"
] | [
-1,
-1,
-1,
-1
] | [
"mysql",
"xampp"
] | stackoverflow_0018022809_mysql_xampp.txt |
Q:
How to upload a CSV file to a given s3 bucket in scala?
I want to upload a CSV file to a given s3 bucket, this CSV file is transfered from a dataframe by using the df.csv(path). For now, I saved the file locally, I'm wondering if there is a way to upload that file to a S3 bucket if given a s3 bucket name?
A:
Something like this should work
dataframe
.write
.option("header","true")
.csv("s3a://bucket/path/file.csv")
More examples on https://sparkbyexamples.com/spark/write-read-csv-file-from-s3-into-dataframe/
| How to upload a CSV file to a given s3 bucket in scala? | I want to upload a CSV file to a given s3 bucket, this CSV file is transfered from a dataframe by using the df.csv(path). For now, I saved the file locally, I'm wondering if there is a way to upload that file to a S3 bucket if given a s3 bucket name?
| [
"Something like this should work\ndataframe\n .write\n .option(\"header\",\"true\")\n .csv(\"s3a://bucket/path/file.csv\") \n\nMore examples on https://sparkbyexamples.com/spark/write-read-csv-file-from-s3-into-dataframe/\n"
] | [
0
] | [] | [] | [
"amazon_s3",
"csv",
"scala"
] | stackoverflow_0074663139_amazon_s3_csv_scala.txt |
Q:
How to Remove Specific Query Filter From url in nextJS Application
i'm trying to add product filtering functionality like this: filter product image and after add filter i have to clear filter as user wish like this one: clear filter image if anyone give me real world idea with some more details or short word it can help me be more proffessional.
A:
Well let's assume your filters data is like this:
[
{
catrgory: "Color",
values: [
"Silver",
"Black",
...
]
},
{
catrgory: "Material",
values: [
"Acrylic",
"Rayon",
...
]
},
...
]
You should have 2 states in your component. One for holding the filters data and another for holding the selected filters.
Fetch your filters data from the server once. (Or use a local file).
Each time the user selects a filter, you should add it to your selected filters data.
Each time the user remove a filter, you should remove it from your selected filters data.
Hope it helps (It's just a guide not the whole solution):
const MyComponent = () => {
const [filtersData, setFiltersData] = useState([]);
const [selectedFilters, setSelectedFilters] = useState([]);
useEffect(() => {
// fetch data from the server
}, []);
const handleSelectFilter = (category, value) => {
const newSelectedFilters = [...selectedFilters];
let filter = newSelectedFilters.find((selectedFilter) => selectedFilter.category === category);
if(filter) {
filter.values.push(value);
} else {
filter = {
catrgoty: category,
values: [value]
}
newSelectedFilters.push(filter);
}
setSelectedFilters(newSelectedFilters);
}
const handleDeleteFilter = (category, value) => {
let newSelectedFilters = [...selectedFilters];
const index = newSelectedFilters.findIndex((selectedFilter) => selectedFilter.category === category);
newSelectedFilters = newSelectedFilters.splice(index, 1);
setSelectedFilters(newSelectedFilters);
}
return (
<div>
{
filtersData.map((filterItem, index) => {
return (
<div key={index}>
<div>{filterItem.category}</div>
{
filterItem.values.map((value) => {
return (
<div key={value} onClick={() => handleSelectFilter(filterItem.category, value)}>{value}</div>
)
})
}
</div>
)
})
}
{
selectedFilters.map((selectedFilter, index) => {
return (
<div key={index}>
<div>{selectedFilter.category}</div>
{
selectedFilter.values.map((value) => {
return (
<div key={value} onClick={() => handleDeleteFilter(filterItem.category, value)}>{value}</div>
)
})
}
</div>
)
})
}
</div>
);
}
| How to Remove Specific Query Filter From url in nextJS Application | i'm trying to add product filtering functionality like this: filter product image and after add filter i have to clear filter as user wish like this one: clear filter image if anyone give me real world idea with some more details or short word it can help me be more proffessional.
| [
"Well let's assume your filters data is like this:\n[\n {\n catrgory: \"Color\",\n values: [\n \"Silver\",\n \"Black\",\n ...\n ]\n },\n {\n catrgory: \"Material\",\n values: [\n \"Acrylic\",\n \"Rayon\",\n ...\n ]\n },\n ...\n]\n\n\nYou should have 2 states in your component. One for holding the filters data and another for holding the selected filters.\n\nFetch your filters data from the server once. (Or use a local file).\n\nEach time the user selects a filter, you should add it to your selected filters data.\n\nEach time the user remove a filter, you should remove it from your selected filters data.\n\n\nHope it helps (It's just a guide not the whole solution):\nconst MyComponent = () => {\n const [filtersData, setFiltersData] = useState([]);\n const [selectedFilters, setSelectedFilters] = useState([]);\n\n useEffect(() => {\n // fetch data from the server\n }, []);\n\n const handleSelectFilter = (category, value) => {\n const newSelectedFilters = [...selectedFilters];\n let filter = newSelectedFilters.find((selectedFilter) => selectedFilter.category === category);\n if(filter) {\n filter.values.push(value);\n } else {\n filter = {\n catrgoty: category,\n values: [value]\n }\n newSelectedFilters.push(filter);\n }\n setSelectedFilters(newSelectedFilters);\n }\n\n const handleDeleteFilter = (category, value) => {\n let newSelectedFilters = [...selectedFilters];\n const index = newSelectedFilters.findIndex((selectedFilter) => selectedFilter.category === category);\n newSelectedFilters = newSelectedFilters.splice(index, 1);\n setSelectedFilters(newSelectedFilters);\n }\n\n return (\n <div>\n {\n filtersData.map((filterItem, index) => {\n return (\n <div key={index}>\n <div>{filterItem.category}</div>\n {\n filterItem.values.map((value) => {\n return (\n <div key={value} onClick={() => handleSelectFilter(filterItem.category, value)}>{value}</div>\n )\n })\n }\n </div>\n )\n })\n }\n {\n selectedFilters.map((selectedFilter, index) => {\n return (\n <div key={index}>\n <div>{selectedFilter.category}</div>\n {\n selectedFilter.values.map((value) => {\n return (\n <div key={value} onClick={() => handleDeleteFilter(filterItem.category, value)}>{value}</div>\n )\n })\n }\n </div>\n )\n })\n }\n </div>\n );\n}\n\n"
] | [
0
] | [] | [] | [
"next.js",
"nextjs_dynamic_routing",
"uri",
"url"
] | stackoverflow_0074658889_next.js_nextjs_dynamic_routing_uri_url.txt |
Q:
Can anyone shed some light on why this code from the alpaca-py documentation does not work?
I am trying to stream bitcoin data using the alpaca-py trading documentation but I keey getting a invalid syntax error. This is taken exactly from the alpaca-py documentation. Does anyone know what I am doing wrong?
from typing import Any
from alpaca.data.live import CryptoDataStream
wss_client = CryptoDataStream(key-id, secret-key)
# async handler
async def quote_data_handler(data: Any):
# quote data will arrive here
print(data)
wss_client.subscribe_quotes(quote_data_handler, "BTC")
wss_client.run()
A:
Take a look at the dashes in your parameters. Usually a no-no in most languages since the "-" or dash usually refers to a minus which is a binary operator or an operator that operates on two operands to produce a new value or result."
Make sure parameters are set before passing them.
Try the underscore instead as in: key_id = "".
Also useful is the following link to a comprehensive list of crypto pairs supported by Alpaca: https://alpaca.markets/support/alpaca-crypto-coin-pair-faq/#:~:text=For%20the%20initial%20launch%20of,%2C%20SOL%2C%20TRX%2C%20UNI)
Stay up to date on the above list as it's membership may be a bit volatile at the moment.
| Can anyone shed some light on why this code from the alpaca-py documentation does not work? | I am trying to stream bitcoin data using the alpaca-py trading documentation but I keey getting a invalid syntax error. This is taken exactly from the alpaca-py documentation. Does anyone know what I am doing wrong?
from typing import Any
from alpaca.data.live import CryptoDataStream
wss_client = CryptoDataStream(key-id, secret-key)
# async handler
async def quote_data_handler(data: Any):
# quote data will arrive here
print(data)
wss_client.subscribe_quotes(quote_data_handler, "BTC")
wss_client.run()
| [
"\nTake a look at the dashes in your parameters. Usually a no-no in most languages since the \"-\" or dash usually refers to a minus which is a binary operator or an operator that operates on two operands to produce a new value or result.\"\nMake sure parameters are set before passing them.\nTry the underscore instead as in: key_id = \"\".\nAlso useful is the following link to a comprehensive list of crypto pairs supported by Alpaca: https://alpaca.markets/support/alpaca-crypto-coin-pair-faq/#:~:text=For%20the%20initial%20launch%20of,%2C%20SOL%2C%20TRX%2C%20UNI)\nStay up to date on the above list as it's membership may be a bit volatile at the moment.\n\n"
] | [
0
] | [] | [] | [
"python",
"websocket"
] | stackoverflow_0074089722_python_websocket.txt |
Q:
Tiptap vue-2 extension throw error on construct
I have basic code from https://tiptap.dev/installation/vue2#3-create-a-new-component, but when component is loaded it throw error vue.esm.js?a026:628 [Vue warn]: Error in nextTick: "InvalidCharacterError: Failed to execute 'createElementNS' on 'Document': The qualified name provided ('[object HTMLDivElement]') contains the invalid name-start character '['."
command executed: npm i @tiptap/vue-2 @tiptap/starter-kit
Element code:
<template>
<editor-content :editor="editor" />
</template>
<script>
import { Editor, EditorContent } from '@tiptap/vue-3';
import StarterKit from '@tiptap/starter-kit';
export default {
components: {
EditorContent,
},
data() {
return {
editor: null,
};
},
mounted() {
this.editor = new Editor({
content: `'<p>I’m running Tiptap with Vue.js. </p>'`,
extensions: [StarterKit],
});
},
beforeDestroy() {
this.editor.destroy();
},
};
</script>
A:
you imported '@tiptap/vue-3'; while installed npm i @tiptap/vue-2 @tiptap/starter-kit
Both are not compatible, you need to install the right version your using, there u need to install tiptap/vue3
| Tiptap vue-2 extension throw error on construct | I have basic code from https://tiptap.dev/installation/vue2#3-create-a-new-component, but when component is loaded it throw error vue.esm.js?a026:628 [Vue warn]: Error in nextTick: "InvalidCharacterError: Failed to execute 'createElementNS' on 'Document': The qualified name provided ('[object HTMLDivElement]') contains the invalid name-start character '['."
command executed: npm i @tiptap/vue-2 @tiptap/starter-kit
Element code:
<template>
<editor-content :editor="editor" />
</template>
<script>
import { Editor, EditorContent } from '@tiptap/vue-3';
import StarterKit from '@tiptap/starter-kit';
export default {
components: {
EditorContent,
},
data() {
return {
editor: null,
};
},
mounted() {
this.editor = new Editor({
content: `'<p>I’m running Tiptap with Vue.js. </p>'`,
extensions: [StarterKit],
});
},
beforeDestroy() {
this.editor.destroy();
},
};
</script>
| [
"you imported '@tiptap/vue-3'; while installed npm i @tiptap/vue-2 @tiptap/starter-kit\nBoth are not compatible, you need to install the right version your using, there u need to install tiptap/vue3\n"
] | [
0
] | [] | [] | [
"tiptap",
"vue.js"
] | stackoverflow_0072858511_tiptap_vue.js.txt |
Q:
CustomShape using ModelRenderable and custom Texture or Color
I am trying to load custom shape glb model without any texture built into it in Sceneform using Filament as backend engine.
I could load the custom shape using ModelRenderable, but when i try to apply Color to ModelRenderable app crashes on setMaterial.
Any help would be greatly appreciated.
ModelRenderable.builder()
.setSource(context, meshId)
.setIsFilamentGltf(true)
.setAsyncLoadEnabled(true)
.build()
.thenAccept(renderable -> {
MaterialFactory.makeOpaqueWithColor(context, color).thenAccept(tMaterial -> {
renderable.setMaterial(tMaterial);
modelRenderable = renderable;
});
The setMaterial method doesnt allows applying color on the renderable.
A:
It looks like you're trying to apply a color to the material of a ModelRenderable, but the setMaterial method does not allow you to change the material of a ModelRenderable after it has been built. Instead, you can set the material when you're building the ModelRenderable using the setMaterial method of the ModelRenderable.Builder class.
Here's an example of how you could do this:
MaterialFactory.makeOpaqueWithColor(context, color)
.thenAccept(material -> ModelRenderable.builder()
.setSource(context, meshId)
.setIsFilamentGltf(true)
.setAsyncLoadEnabled(true)
.setMaterial(material)
.build()
.thenAccept(renderable -> modelRenderable = renderable));
This will apply the color to the material of the ModelRenderable when it is being built, rather than trying to change the material after the renderable has been created.
| CustomShape using ModelRenderable and custom Texture or Color | I am trying to load custom shape glb model without any texture built into it in Sceneform using Filament as backend engine.
I could load the custom shape using ModelRenderable, but when i try to apply Color to ModelRenderable app crashes on setMaterial.
Any help would be greatly appreciated.
ModelRenderable.builder()
.setSource(context, meshId)
.setIsFilamentGltf(true)
.setAsyncLoadEnabled(true)
.build()
.thenAccept(renderable -> {
MaterialFactory.makeOpaqueWithColor(context, color).thenAccept(tMaterial -> {
renderable.setMaterial(tMaterial);
modelRenderable = renderable;
});
The setMaterial method doesnt allows applying color on the renderable.
| [
"It looks like you're trying to apply a color to the material of a ModelRenderable, but the setMaterial method does not allow you to change the material of a ModelRenderable after it has been built. Instead, you can set the material when you're building the ModelRenderable using the setMaterial method of the ModelRenderable.Builder class.\nHere's an example of how you could do this:\nMaterialFactory.makeOpaqueWithColor(context, color)\n .thenAccept(material -> ModelRenderable.builder()\n .setSource(context, meshId)\n .setIsFilamentGltf(true)\n .setAsyncLoadEnabled(true)\n .setMaterial(material)\n .build()\n .thenAccept(renderable -> modelRenderable = renderable));\n\nThis will apply the color to the material of the ModelRenderable when it is being built, rather than trying to change the material after the renderable has been created.\n"
] | [
0
] | [] | [] | [
"android",
"android_asynctask",
"filament",
"sceneform"
] | stackoverflow_0074677605_android_android_asynctask_filament_sceneform.txt |
Q:
Possible eager mmap page eviction MacOS
I have a program which accesses a large memory block allocated with mmap. It accesses it unevenly, mostly accessing the first ~1 GB on memory, sometimes the next ~2 GB of memory, and rarely the last ~4 GB of memory. The memory is a shared memory mapping with PROT_READ and PROT_WRITE backed by an unlinked file.
Compared to the Linux version, I've found the MacOS version is exceedingly slow. Yet, the memory pressure is low. (6.42 Used, 9.51 Cached.)
The following usage statistics originate from activity monitor:
"Memory": 1.17 GB
Real memory Size: 3.71 GB
Virtual Memory Size: 51.15 GB
Shared Memory Size: 440 KB
Private Memory Size: 3.74 GB
Why is this? Is there anyway to improve caching behavior?
A:
The MacOS version of your program is slow because the mmap implementation in MacOS may not be optimized for large memory blocks and uneven access patterns. Additionally, the low memory pressure reported by activity monitor may not accurately reflect the true memory usage of your program, as it only measures the amount of memory that is actively being used by running processes and not the amount of memory that has been mapped by mmap.
To improve the caching behavior of your program on MacOS, you can try using madvise with the MADV_WILLNEED flag to let the operating system know that your program will need to access the entire memory mapping soon, so that it can proactively cache the relevant pages in memory. You can also try using the MADV_SEQUENTIAL flag to let the operating system know that your program will be accessing the memory mapping in a sequential pattern, which can help improve performance by allowing the operating system to optimize its caching strategy.
Another option to improve the performance of your program on MacOS is to use a different memory mapping mechanism, such as shm_open, which provides more fine-grained control over the shared memory region and can be more efficient for large memory blocks and uneven access patterns.
Overall, there are several potential ways to improve the performance of your program on MacOS, but the best solution will depend on the specific details of your program and its memory usage patterns. It may be worth experimenting with different approaches and using performance profiling tools to identify the optimal solution for your specific use case.
| Possible eager mmap page eviction MacOS | I have a program which accesses a large memory block allocated with mmap. It accesses it unevenly, mostly accessing the first ~1 GB on memory, sometimes the next ~2 GB of memory, and rarely the last ~4 GB of memory. The memory is a shared memory mapping with PROT_READ and PROT_WRITE backed by an unlinked file.
Compared to the Linux version, I've found the MacOS version is exceedingly slow. Yet, the memory pressure is low. (6.42 Used, 9.51 Cached.)
The following usage statistics originate from activity monitor:
"Memory": 1.17 GB
Real memory Size: 3.71 GB
Virtual Memory Size: 51.15 GB
Shared Memory Size: 440 KB
Private Memory Size: 3.74 GB
Why is this? Is there anyway to improve caching behavior?
| [
"The MacOS version of your program is slow because the mmap implementation in MacOS may not be optimized for large memory blocks and uneven access patterns. Additionally, the low memory pressure reported by activity monitor may not accurately reflect the true memory usage of your program, as it only measures the amount of memory that is actively being used by running processes and not the amount of memory that has been mapped by mmap.\nTo improve the caching behavior of your program on MacOS, you can try using madvise with the MADV_WILLNEED flag to let the operating system know that your program will need to access the entire memory mapping soon, so that it can proactively cache the relevant pages in memory. You can also try using the MADV_SEQUENTIAL flag to let the operating system know that your program will be accessing the memory mapping in a sequential pattern, which can help improve performance by allowing the operating system to optimize its caching strategy.\nAnother option to improve the performance of your program on MacOS is to use a different memory mapping mechanism, such as shm_open, which provides more fine-grained control over the shared memory region and can be more efficient for large memory blocks and uneven access patterns.\nOverall, there are several potential ways to improve the performance of your program on MacOS, but the best solution will depend on the specific details of your program and its memory usage patterns. It may be worth experimenting with different approaches and using performance profiling tools to identify the optimal solution for your specific use case.\n"
] | [
0
] | [] | [] | [
"macos",
"mmap",
"paging"
] | stackoverflow_0074581030_macos_mmap_paging.txt |
Q:
How to mathematicaly prove the Time Complexity of the recursive Fibonacci program with Memoization
Well, I am looking for a more mathematical approach to things.
Using this two-analysis approach.
For the standard Fibonacci recursive function, we all know that it runs with time complexity O(2^n)
the proof found by upper bound :
T(n-1)=T(n-2)
T(n)=2T(n-1)+c
=4T(n-2)+3c
=8T(n-3)+7c
=2^k T(n-k)+(2^k-1)c
n - k = 0 , hence k = n
T(n) = 2^n T(0) + (2^n - 1)c
T(n) = (1 + c) * 2^n - c
T(n) <= 2^n
I tried to optimize this time, I used the Memoization approach of Dynamic Programming in the following code :
private static long fib(int n) {
if (n <= 1) return n;
if (memo[n] != 0) {
return memo[n];
}
long result = fib(n - 1) + fib(n - 2);
memo[n] = result;
return result;
}
I know that looking at, and by trying some n the n value; this code is much better. And also that the time complexity dropped to O(n).
I want to do the same proof thing for this code using upper/lower bounds to prove this, but I don't know how to start.
The thing to say, I am doing this to see where my worst and best scenarios are.
A:
The relationship between the elements of the sequence doesn't change. T(n) would be still expressed in the same way:
T(n) = T(n - 1) + T(n - 2)
And
T(n - 1) = T(n - 2) + T(n - 3)
And
T(n - 2) = T(n - 3) + T(n - 4)
And so on, until recursion hit the base case: T(0) = c and T(1) = c.
What changes when you're applying Memoization is the number of recursive calls. It would be 2 * n instead of 2n. And every repeated recursive call (like T(n - 2) and T(n - 3) above) would now have a constant time complexity.
It would be more apparent if you would draw a tree of recursive calls on a paper, then you would observe that branches on one side of the tree turned into a leaves (because the result of these calls was already computed, and we don't propagate them further).
Here's such a tree of call for plain recursion:
t(n) Naive reqursive implementation
/ \ 2 ^ n recursive calls
/ \
t(n-1) t(n-2)
/ \ / \
/ \ / \
t(n-2) t(n-3) t(n-3) t(n-4)
/ \ / \ / \ / \
.................................
t(2)
/ \
t(1) t(0)
And that's how it changes if we apply Memoization:
t(n) Memoization
/ \ ~ 2 * n recursive calls
/ \
t(n-1) t(n-2)
/ \
/ \
t(n-2) t(n-3)
/ \
.................................
t(2)
/ \
t(1) t(0)
I.e.
T(n) = T(n - 1) + c = T(n - 2) + 2 * c = T(n - 3) + 3 * c = ... = T(1) + n * c
Which would give T(n) = O(n)
| How to mathematicaly prove the Time Complexity of the recursive Fibonacci program with Memoization | Well, I am looking for a more mathematical approach to things.
Using this two-analysis approach.
For the standard Fibonacci recursive function, we all know that it runs with time complexity O(2^n)
the proof found by upper bound :
T(n-1)=T(n-2)
T(n)=2T(n-1)+c
=4T(n-2)+3c
=8T(n-3)+7c
=2^k T(n-k)+(2^k-1)c
n - k = 0 , hence k = n
T(n) = 2^n T(0) + (2^n - 1)c
T(n) = (1 + c) * 2^n - c
T(n) <= 2^n
I tried to optimize this time, I used the Memoization approach of Dynamic Programming in the following code :
private static long fib(int n) {
if (n <= 1) return n;
if (memo[n] != 0) {
return memo[n];
}
long result = fib(n - 1) + fib(n - 2);
memo[n] = result;
return result;
}
I know that looking at, and by trying some n the n value; this code is much better. And also that the time complexity dropped to O(n).
I want to do the same proof thing for this code using upper/lower bounds to prove this, but I don't know how to start.
The thing to say, I am doing this to see where my worst and best scenarios are.
| [
"The relationship between the elements of the sequence doesn't change. T(n) would be still expressed in the same way:\nT(n) = T(n - 1) + T(n - 2)\nAnd\nT(n - 1) = T(n - 2) + T(n - 3)\nAnd\nT(n - 2) = T(n - 3) + T(n - 4)\nAnd so on, until recursion hit the base case: T(0) = c and T(1) = c.\nWhat changes when you're applying Memoization is the number of recursive calls. It would be 2 * n instead of 2n. And every repeated recursive call (like T(n - 2) and T(n - 3) above) would now have a constant time complexity.\nIt would be more apparent if you would draw a tree of recursive calls on a paper, then you would observe that branches on one side of the tree turned into a leaves (because the result of these calls was already computed, and we don't propagate them further).\nHere's such a tree of call for plain recursion:\n t(n) Naive reqursive implementation\n / \\ 2 ^ n recursive calls\n / \\\n t(n-1) t(n-2)\n / \\ / \\\n / \\ / \\\n t(n-2) t(n-3) t(n-3) t(n-4)\n / \\ / \\ / \\ / \\\n .................................\n t(2)\n / \\\nt(1) t(0)\n\nAnd that's how it changes if we apply Memoization:\n t(n) Memoization\n / \\ ~ 2 * n recursive calls\n / \\\n t(n-1) t(n-2)\n / \\\n / \\\n t(n-2) t(n-3)\n / \\ \n .................................\n t(2)\n / \\\nt(1) t(0)\n\nI.e.\nT(n) = T(n - 1) + c = T(n - 2) + 2 * c = T(n - 3) + 3 * c = ... = T(1) + n * c\nWhich would give T(n) = O(n)\n"
] | [
1
] | [] | [] | [
"algorithm",
"big_o",
"fibonacci",
"java",
"memoization"
] | stackoverflow_0074677128_algorithm_big_o_fibonacci_java_memoization.txt |
Q:
Python missing or unusable error while cross compiling GDB
I get this error while attempting to cross-compile GDB (using the --with-python flag):
checking for python: /usr/bin/python
checking for python2.7: no
configure: error: python is missing or unusable
I made sure I had python2.7 installed in /usr/bin. I even removed the package and installed it again. I tried using --with-python=/usr/bin and --with-python=/usr/local, but no luck. I know for sure though that 2.7 is installed though. Any idea on what to do?
A:
I had the same problem on Debian 6.0 when compiling GDB 7.4.1
The solution was to install python headers
sudo apt-get install python2.6-dev
and then configure with the right flag
./configure --with-python
A:
I had the same problem with gdb 7.4 and finally made it worked after spending some time debugging.
By checking the file <gdb-source-path>/gdb/config.log, you will notice one line:
configure:11031: gcc -o conftest -g -O2 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 conftest.c -lncurses -lz -lm -L/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config -ldl -framework CoreFoundation -lpython2.7 -u _PyMac_Error Python.framework/Versions/2.7/Python >&5
Seems that the script python/python-config.py returned some invalid flags that caused the gcc command to fail.
The solution is to open <gdb-source-directory>/gdb/python/python-config.py and comment out these two lines:
# if getvar('LINKFORSHARED') is not None:
# libs.extend(getvar('LINKFORSHARED').split())
A:
I just came across a similar issue building gdb 7.8.1 using Continuum's Python 2.7, which, in my case, was installed in a non-standard location.
In this case, the solution was to provide an additional piece of configuration before running 'configure':
export LDFLAGS="-Wl,-rpath,<non-standard-Python-lib-location> -L<non-standard-Python-lib-location>"
configure --with-python=<non-standard-Python-executable-location>
A:
I hit this error building the ESP8266 SDK. Just did a
sudo apt-get install python-dev
and now it works.
A:
I came up with almost the same error building gdb 13.0.50 with python 3.8 for a more recent udpate. Running make after ./configure --with-python it shows python missing error.
During compilation it seems to be looking for usr/bin/python for python 3.8 while we only have usr/bin/python3.
So I quickly changed the name of the python directory from usr/bin/python3 to usr/bin/python and it compiled and found python successfully.
Don't forget to change it back for dependencies
A:
Just adding my own solution since I cannot see it among the rest here. In my case I was able to solve this by using configure as follows:
./configure --with-python=/usr/bin/python3
This was on a Ubuntu 22.04 machine. I suspect --with-python requires a full path to an existing python binary, so this seems like a much easier solution for standard distributions.
| Python missing or unusable error while cross compiling GDB | I get this error while attempting to cross-compile GDB (using the --with-python flag):
checking for python: /usr/bin/python
checking for python2.7: no
configure: error: python is missing or unusable
I made sure I had python2.7 installed in /usr/bin. I even removed the package and installed it again. I tried using --with-python=/usr/bin and --with-python=/usr/local, but no luck. I know for sure though that 2.7 is installed though. Any idea on what to do?
| [
"I had the same problem on Debian 6.0 when compiling GDB 7.4.1\nThe solution was to install python headers\nsudo apt-get install python2.6-dev\n\nand then configure with the right flag\n./configure --with-python\n\n",
"I had the same problem with gdb 7.4 and finally made it worked after spending some time debugging.\nBy checking the file <gdb-source-path>/gdb/config.log, you will notice one line:\nconfigure:11031: gcc -o conftest -g -O2 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 conftest.c -lncurses -lz -lm -L/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config -ldl -framework CoreFoundation -lpython2.7 -u _PyMac_Error Python.framework/Versions/2.7/Python >&5\n\nSeems that the script python/python-config.py returned some invalid flags that caused the gcc command to fail.\nThe solution is to open <gdb-source-directory>/gdb/python/python-config.py and comment out these two lines:\n# if getvar('LINKFORSHARED') is not None:\n# libs.extend(getvar('LINKFORSHARED').split())\n\n",
"I just came across a similar issue building gdb 7.8.1 using Continuum's Python 2.7, which, in my case, was installed in a non-standard location.\nIn this case, the solution was to provide an additional piece of configuration before running 'configure':\nexport LDFLAGS=\"-Wl,-rpath,<non-standard-Python-lib-location> -L<non-standard-Python-lib-location>\"\nconfigure --with-python=<non-standard-Python-executable-location>\n\n",
"I hit this error building the ESP8266 SDK. Just did a \nsudo apt-get install python-dev \nand now it works.\n",
"I came up with almost the same error building gdb 13.0.50 with python 3.8 for a more recent udpate. Running make after ./configure --with-python it shows python missing error.\nDuring compilation it seems to be looking for usr/bin/python for python 3.8 while we only have usr/bin/python3.\nSo I quickly changed the name of the python directory from usr/bin/python3 to usr/bin/python and it compiled and found python successfully.\nDon't forget to change it back for dependencies\n",
"Just adding my own solution since I cannot see it among the rest here. In my case I was able to solve this by using configure as follows:\n./configure --with-python=/usr/bin/python3\n\nThis was on a Ubuntu 22.04 machine. I suspect --with-python requires a full path to an existing python binary, so this seems like a much easier solution for standard distributions.\n"
] | [
21,
13,
7,
6,
0,
0
] | [] | [] | [
"gdb",
"python"
] | stackoverflow_0010792844_gdb_python.txt |
Q:
How to get only variable names in TCL expression which is passed to the proc
I have a expression which I'm passing through proc. My proc should return all the varible names.
ex : By calling getvalue {expr [$a + $b]} should give me $a and $b.
proc getvariables {q} {
set aa [lsearch -inline -all [split $q " "] {*$*}]
puts $aa
}
getvariables {expr [$a + $b]}
This is my code, it is returning
{[$a} {$b]}
But it should return only
$a $b
Thanks!!
A:
In your example, you split your string by a space character to get a list with four items:
expr
[$a <--- matches *$*
+
$b] <--- matches *$*
After that you searched for any list items matching *$*, which matched [$a] and $b].
You probably want to use regexp instead in order to be more specific with your matching requrements. The pattern \$\w+ matches anything starting with a literal dollar sign followed by one or more alphanumeric+underscore characters. Please finetune the regex as needed.
proc getvariables {q} {
set matches [regexp -all -inline {\$\w+} $q]
return $matches
}
getvariables {expr [$a + $b]}
This returns list {$a} {$b}. The curly braces are displayed around the variable names in this list context because start with a dollar sign, but are not literally in the value of the list items. To confirm this, call join on the resulting list to get the string $a $b
| How to get only variable names in TCL expression which is passed to the proc | I have a expression which I'm passing through proc. My proc should return all the varible names.
ex : By calling getvalue {expr [$a + $b]} should give me $a and $b.
proc getvariables {q} {
set aa [lsearch -inline -all [split $q " "] {*$*}]
puts $aa
}
getvariables {expr [$a + $b]}
This is my code, it is returning
{[$a} {$b]}
But it should return only
$a $b
Thanks!!
| [
"In your example, you split your string by a space character to get a list with four items:\nexpr\n[$a <--- matches *$*\n+\n$b] <--- matches *$*\n\nAfter that you searched for any list items matching *$*, which matched [$a] and $b].\nYou probably want to use regexp instead in order to be more specific with your matching requrements. The pattern \\$\\w+ matches anything starting with a literal dollar sign followed by one or more alphanumeric+underscore characters. Please finetune the regex as needed.\nproc getvariables {q} {\n set matches [regexp -all -inline {\\$\\w+} $q] \n return $matches\n}\ngetvariables {expr [$a + $b]}\n\nThis returns list {$a} {$b}. The curly braces are displayed around the variable names in this list context because start with a dollar sign, but are not literally in the value of the list items. To confirm this, call join on the resulting list to get the string $a $b\n"
] | [
0
] | [] | [] | [
"string",
"tcl"
] | stackoverflow_0074669903_string_tcl.txt |
Q:
Select only one column using case or pivot in PLSQL
I have a table or data like this
This data has a same invoice number, so I want to show table only one column using case or pivot. The result that I want is like this
Can you help me about this ?
A:
Using CASE expressions:
WITH
tbl AS -- Sample Data
(
Select 'WSIV/H/02/22/00122' "NO_INVOICE", To_Date('04.08-2022', 'dd.mm.yyyy') "PAID_DATE", 50000 "AMOUNT_APPLY" From Dual Union All
Select 'WSIV/H/02/22/00122' "NO_INVOICE", To_Date('06.08-2022', 'dd.mm.yyyy') "PAID_DATE", 60000 "AMOUNT_APPLY" From Dual Union All
Select 'WSIV/H/02/22/00122' "NO_INVOICE", To_Date('07.08-2022', 'dd.mm.yyyy') "PAID_DATE", 70000 "AMOUNT_APPLY" From Dual
)
SELECT
NO_INVOICE,
Max(PAID_DATE_1) "PAID_DATE_1", Max(AMOUNT_APPLY_1) "AMOUNT_APPLY_1",
Max(PAID_DATE_2) "PAID_DATE_2", Max(AMOUNT_APPLY_2) "AMOUNT_APPLY_2",
Max(PAID_DATE_3) "PAID_DATE_3", Max(AMOUNT_APPLY_3) "AMOUNT_APPLY_3",
Max(PAID_DATE_4) "PAID_DATE_4", Max(AMOUNT_APPLY_4) "AMOUNT_APPLY_4",
Nvl(Max(AMOUNT_APPLY_1), 0) + Nvl(Max(AMOUNT_APPLY_2), 0) + Nvl(Max(AMOUNT_APPLY_3), 0) + Nvl(Max(AMOUNT_APPLY_4), 0) "TOTAL"
FROM
(
Select
NO_INVOICE,
CASE WHEN ROW_NUMBER() OVER(Partition By NO_INVOICE Order By PAID_DATE) = 1 THEN PAID_DATE END "PAID_DATE_1",
CASE WHEN ROW_NUMBER() OVER(Partition By NO_INVOICE Order By PAID_DATE) = 2 THEN PAID_DATE END "PAID_DATE_2",
CASE WHEN ROW_NUMBER() OVER(Partition By NO_INVOICE Order By PAID_DATE) = 3 THEN PAID_DATE END "PAID_DATE_3",
CASE WHEN ROW_NUMBER() OVER(Partition By NO_INVOICE Order By PAID_DATE) = 4 THEN PAID_DATE END "PAID_DATE_4",
CASE WHEN ROW_NUMBER() OVER(Partition By NO_INVOICE Order By PAID_DATE) = 1 THEN AMOUNT_APPLY END "AMOUNT_APPLY_1",
CASE WHEN ROW_NUMBER() OVER(Partition By NO_INVOICE Order By PAID_DATE) = 2 THEN AMOUNT_APPLY END "AMOUNT_APPLY_2",
CASE WHEN ROW_NUMBER() OVER(Partition By NO_INVOICE Order By PAID_DATE) = 3 THEN AMOUNT_APPLY END "AMOUNT_APPLY_3",
CASE WHEN ROW_NUMBER() OVER(Partition By NO_INVOICE Order By PAID_DATE) = 4 THEN AMOUNT_APPLY END "AMOUNT_APPLY_4"
From
tbl
)
GROUP BY NO_INVOICE
ORDER BY NO_INVOICE
Result:
NO_INVOICE
PAID_DATE_1
AMOUNT_APPLY_1
PAID_DATE_2
AMOUNT_APPLY_2
PAID_DATE_3
AMOUNT_APPLY_3
PAID_DATE_4
AMOUNT_APPLY_4
TOTAL
WSIV/H/02/22/00122
04-AUG-22
50000
06-AUG-22
60000
07-AUG-22
70000
180000
A:
Using PIVOT clause
WITH
tbl AS -- Sample Data
(
SELECT 'WSIV/H/02/22/00122' no_invoice, DATE '2022-08-04' paid_date, 50000 amount_apply FROM DUAL UNION ALL
SELECT 'WSIV/H/02/22/00122' no_invoice, DATE '2022-08-06' paid_date, 60000 amount_apply FROM DUAL UNION ALL
SELECT 'WSIV/H/02/22/00122' no_invoice, DATE '2022-08-07' paid_date, 70000 amount_apply FROM DUAL
)
SELECT
no_invoice,
"1_PAID_DATE" paid_date_1, "1_AMOUNT_APPLY" amount_apply_1,
"2_PAID_DATE" paid_date_2, "2_AMOUNT_APPLY" amount_apply_2,
"3_PAID_DATE" paid_date_3, "3_AMOUNT_APPLY" amount_apply_3,
"4_PAID_DATE" paid_date_4, "4_AMOUNT_APPLY" amount_apply_4,
NVL("1_AMOUNT_APPLY",0)+NVL("2_AMOUNT_APPLY",0)+NVL("3_AMOUNT_APPLY",0)+NVL("4_AMOUNT_APPLY",0)+NVL("5_AMOUNT_APPLY",0) total
FROM
( SELECT
no_invoice, paid_date, amount_apply,
LEAST(5, ROW_NUMBER() OVER (PARTITION BY NO_INVOICE ORDER BY paid_date)) bucket
FROM tbl
)
PIVOT
( ANY_VALUE(paid_date) paid_date, ANY_VALUE(amount_apply) amount_apply
FOR bucket IN (1,2,3,4,5)
)
Bucket 5 is used to trap all amount_apply's beyond the first 4 dates so they may be included in the total even though those amounts will not be shown in the columns (a catch all).
In Oracles prior to 19c use MAX rather than ANY_VALUE.
If you want the paid_date's to be aggregated so that all payments for an no_invoice on the same date appear just in one column, then change ROW_NUMBER to DENSE_RANK and ANY_VALUE(amount_apply) to SUM(amount_apply).
Result is as per OP. Thanks to @d-r for Sample Data.
| Select only one column using case or pivot in PLSQL | I have a table or data like this
This data has a same invoice number, so I want to show table only one column using case or pivot. The result that I want is like this
Can you help me about this ?
| [
"Using CASE expressions:\nWITH\n tbl AS -- Sample Data\n (\n Select 'WSIV/H/02/22/00122' \"NO_INVOICE\", To_Date('04.08-2022', 'dd.mm.yyyy') \"PAID_DATE\", 50000 \"AMOUNT_APPLY\" From Dual Union All\n Select 'WSIV/H/02/22/00122' \"NO_INVOICE\", To_Date('06.08-2022', 'dd.mm.yyyy') \"PAID_DATE\", 60000 \"AMOUNT_APPLY\" From Dual Union All\n Select 'WSIV/H/02/22/00122' \"NO_INVOICE\", To_Date('07.08-2022', 'dd.mm.yyyy') \"PAID_DATE\", 70000 \"AMOUNT_APPLY\" From Dual \n )\nSELECT\n NO_INVOICE,\n Max(PAID_DATE_1) \"PAID_DATE_1\", Max(AMOUNT_APPLY_1) \"AMOUNT_APPLY_1\",\n Max(PAID_DATE_2) \"PAID_DATE_2\", Max(AMOUNT_APPLY_2) \"AMOUNT_APPLY_2\",\n Max(PAID_DATE_3) \"PAID_DATE_3\", Max(AMOUNT_APPLY_3) \"AMOUNT_APPLY_3\",\n Max(PAID_DATE_4) \"PAID_DATE_4\", Max(AMOUNT_APPLY_4) \"AMOUNT_APPLY_4\",\n Nvl(Max(AMOUNT_APPLY_1), 0) + Nvl(Max(AMOUNT_APPLY_2), 0) + Nvl(Max(AMOUNT_APPLY_3), 0) + Nvl(Max(AMOUNT_APPLY_4), 0) \"TOTAL\"\nFROM\n ( \n Select\n NO_INVOICE,\n CASE WHEN ROW_NUMBER() OVER(Partition By NO_INVOICE Order By PAID_DATE) = 1 THEN PAID_DATE END \"PAID_DATE_1\", \n CASE WHEN ROW_NUMBER() OVER(Partition By NO_INVOICE Order By PAID_DATE) = 2 THEN PAID_DATE END \"PAID_DATE_2\",\n CASE WHEN ROW_NUMBER() OVER(Partition By NO_INVOICE Order By PAID_DATE) = 3 THEN PAID_DATE END \"PAID_DATE_3\",\n CASE WHEN ROW_NUMBER() OVER(Partition By NO_INVOICE Order By PAID_DATE) = 4 THEN PAID_DATE END \"PAID_DATE_4\",\n CASE WHEN ROW_NUMBER() OVER(Partition By NO_INVOICE Order By PAID_DATE) = 1 THEN AMOUNT_APPLY END \"AMOUNT_APPLY_1\", \n CASE WHEN ROW_NUMBER() OVER(Partition By NO_INVOICE Order By PAID_DATE) = 2 THEN AMOUNT_APPLY END \"AMOUNT_APPLY_2\",\n CASE WHEN ROW_NUMBER() OVER(Partition By NO_INVOICE Order By PAID_DATE) = 3 THEN AMOUNT_APPLY END \"AMOUNT_APPLY_3\",\n CASE WHEN ROW_NUMBER() OVER(Partition By NO_INVOICE Order By PAID_DATE) = 4 THEN AMOUNT_APPLY END \"AMOUNT_APPLY_4\"\n From\n tbl\n )\nGROUP BY NO_INVOICE\nORDER BY NO_INVOICE\n\nResult:\n\n\n\n\nNO_INVOICE\nPAID_DATE_1\nAMOUNT_APPLY_1\nPAID_DATE_2\nAMOUNT_APPLY_2\nPAID_DATE_3\nAMOUNT_APPLY_3\nPAID_DATE_4\nAMOUNT_APPLY_4\nTOTAL\n\n\n\n\nWSIV/H/02/22/00122\n04-AUG-22\n50000\n06-AUG-22\n60000\n07-AUG-22\n70000\n\n\n180000\n\n\n\n",
"Using PIVOT clause\nWITH\n tbl AS -- Sample Data\n (\n SELECT 'WSIV/H/02/22/00122' no_invoice, DATE '2022-08-04' paid_date, 50000 amount_apply FROM DUAL UNION ALL\n SELECT 'WSIV/H/02/22/00122' no_invoice, DATE '2022-08-06' paid_date, 60000 amount_apply FROM DUAL UNION ALL\n SELECT 'WSIV/H/02/22/00122' no_invoice, DATE '2022-08-07' paid_date, 70000 amount_apply FROM DUAL \n )\nSELECT\n no_invoice,\n \"1_PAID_DATE\" paid_date_1, \"1_AMOUNT_APPLY\" amount_apply_1,\n \"2_PAID_DATE\" paid_date_2, \"2_AMOUNT_APPLY\" amount_apply_2,\n \"3_PAID_DATE\" paid_date_3, \"3_AMOUNT_APPLY\" amount_apply_3,\n \"4_PAID_DATE\" paid_date_4, \"4_AMOUNT_APPLY\" amount_apply_4,\n NVL(\"1_AMOUNT_APPLY\",0)+NVL(\"2_AMOUNT_APPLY\",0)+NVL(\"3_AMOUNT_APPLY\",0)+NVL(\"4_AMOUNT_APPLY\",0)+NVL(\"5_AMOUNT_APPLY\",0) total\nFROM \n ( SELECT \n no_invoice, paid_date, amount_apply,\n LEAST(5, ROW_NUMBER() OVER (PARTITION BY NO_INVOICE ORDER BY paid_date)) bucket\n FROM tbl\n )\nPIVOT\n ( ANY_VALUE(paid_date) paid_date, ANY_VALUE(amount_apply) amount_apply\n FOR bucket IN (1,2,3,4,5)\n )\n\nBucket 5 is used to trap all amount_apply's beyond the first 4 dates so they may be included in the total even though those amounts will not be shown in the columns (a catch all).\nIn Oracles prior to 19c use MAX rather than ANY_VALUE.\nIf you want the paid_date's to be aggregated so that all payments for an no_invoice on the same date appear just in one column, then change ROW_NUMBER to DENSE_RANK and ANY_VALUE(amount_apply) to SUM(amount_apply).\nResult is as per OP. Thanks to @d-r for Sample Data.\n"
] | [
0,
0
] | [] | [] | [
"case",
"oracle",
"pivot",
"plsql",
"sql"
] | stackoverflow_0074664014_case_oracle_pivot_plsql_sql.txt |
Q:
JavaScript setTimeout parameters and selectors
I am trying to select elements in the loop and pass them to setTimeout.
Why doesn't the following work as it is supposed to?
Is it because el.querySelector('.b') is slower than setTimeout?
var ids = document.querySelectorAll('.a'),
span
ids.forEach(el => {
span = el.querySelector('.b')
setTimeout(function() {
span.classList.add('visible');
}, 20, span);
})
.visible{
color:red;
}
<p class="a"><span class="b">1</span></p>
<p class="a"><span class="b">2</span></p>
<p class="a"><span class="b">3</span></p>
A:
Just don't use var and declare variables in their scope
const ids = document.querySelectorAll('.a')
ids.forEach(el => {
const span = el.querySelector('.b')
setTimeout(function() {
span.classList.add('visible');
}, 20, span);
})
.visible {
color: red;
}
<p class="a"><span class="b">1</span></p>
<p class="a"><span class="b">2</span></p>
<p class="a"><span class="b">3</span></p>
A:
In the code you provided, the span variable is overwritten on each iteration of the forEach loop, so when the callback function is executed, it will always reference the same element (the last one selected by querySelector). To fix this, you can move the querySelector call inside the callback function, like this:
var ids = document.querySelectorAll('.a'),
span
ids.forEach(el => {
setTimeout(function() {
var span = el.querySelector('.b')
span.classList.add('visible');
}, 2000);
})
.visible{
color:red;
}
<p class="a"><span class="b">1</span></p>
<p class="a"><span class="b">2</span></p>
<p class="a"><span class="b">3</span></p>
This should work as expected. I've increased the delay to make the change more visible.
| JavaScript setTimeout parameters and selectors | I am trying to select elements in the loop and pass them to setTimeout.
Why doesn't the following work as it is supposed to?
Is it because el.querySelector('.b') is slower than setTimeout?
var ids = document.querySelectorAll('.a'),
span
ids.forEach(el => {
span = el.querySelector('.b')
setTimeout(function() {
span.classList.add('visible');
}, 20, span);
})
.visible{
color:red;
}
<p class="a"><span class="b">1</span></p>
<p class="a"><span class="b">2</span></p>
<p class="a"><span class="b">3</span></p>
| [
"Just don't use var and declare variables in their scope\n\n\nconst ids = document.querySelectorAll('.a')\n\nids.forEach(el => {\n const span = el.querySelector('.b')\n setTimeout(function() {\n span.classList.add('visible');\n }, 20, span);\n})\n.visible {\n color: red;\n}\n<p class=\"a\"><span class=\"b\">1</span></p>\n<p class=\"a\"><span class=\"b\">2</span></p>\n<p class=\"a\"><span class=\"b\">3</span></p>\n\n\n\n",
"In the code you provided, the span variable is overwritten on each iteration of the forEach loop, so when the callback function is executed, it will always reference the same element (the last one selected by querySelector). To fix this, you can move the querySelector call inside the callback function, like this:\n\n\nvar ids = document.querySelectorAll('.a'),\n span\n \nids.forEach(el => {\n setTimeout(function() {\n var span = el.querySelector('.b')\n span.classList.add('visible');\n }, 2000);\n})\n.visible{\n color:red;\n}\n<p class=\"a\"><span class=\"b\">1</span></p>\n<p class=\"a\"><span class=\"b\">2</span></p>\n<p class=\"a\"><span class=\"b\">3</span></p>\n\n\n\nThis should work as expected. I've increased the delay to make the change more visible.\n"
] | [
2,
2
] | [] | [] | [
"html",
"javascript",
"settimeout"
] | stackoverflow_0074677569_html_javascript_settimeout.txt |
Q:
How to prevent tabs from updating / re-rendering when they are not focused?
I'm using material top tabs. Problem is, when a state changes in one tab, all other tabs that use the same state render again which slows the app a little. How do I prevent tabs from getting updated unless they are focused / seen ?
A:
<TabNavigator.Navigator
// set lazy true to prevent pre-render
lazy={true}
optimizationsEnabled={true}
tabBarOptions={tabBarOptions}>
<TabNavigator.Screen name="HOME" component={HOME} />
<TabNavigator.Screen name="SHOP" component={SHOP} />
</TabNavigator.Navigator>
A:
In your components, you can get state property and detect is it in focus or not. And if it is not in focus you can prevent rerendering or place your own logic. An example is here:
https://reactnavigation.org/docs/material-top-tab-navigator#tabbar
| How to prevent tabs from updating / re-rendering when they are not focused? | I'm using material top tabs. Problem is, when a state changes in one tab, all other tabs that use the same state render again which slows the app a little. How do I prevent tabs from getting updated unless they are focused / seen ?
| [
"<TabNavigator.Navigator\n // set lazy true to prevent pre-render\n lazy={true}\n optimizationsEnabled={true}\n tabBarOptions={tabBarOptions}>\n <TabNavigator.Screen name=\"HOME\" component={HOME} />\n <TabNavigator.Screen name=\"SHOP\" component={SHOP} />\n</TabNavigator.Navigator>\n\n",
"In your components, you can get state property and detect is it in focus or not. And if it is not in focus you can prevent rerendering or place your own logic. An example is here:\nhttps://reactnavigation.org/docs/material-top-tab-navigator#tabbar\n"
] | [
0,
0
] | [] | [] | [
"react_native",
"react_navigation"
] | stackoverflow_0074672594_react_native_react_navigation.txt |
Q:
Looping through nested JSON returns NULL
I'm trying to better understand how to work with nested JSON objects in JavaScript/React.
I am getting data through the GitLab API in the following form:
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "[email protected]",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "[email protected]",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "[email protected]",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "[email protected]",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},]
I want to loop through all objects(merge requests) in this JSON and create a new array with the merge_user.name.
console.log(merge_requests[0].merge_user.name);
console.log(merge_requests[1].merge_user.name);
The logs above return both the correct values. However, I cannot loop through the JSON to create a new array from the data like this:
const arrTest = [];
for(var i = 0; i < Object.keys(merge_requests).length; i++)
{
var mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
}
The code above leads to the following error: Uncaught (in promise) TypeError: resultData[i].merge_user is null
Here is a picture:
I am currently learning JS coming from R. I have huge problems working with JSON instead of dataframes and I cannot find any documentation to learn from. I would appreciated any advice/ sources.
A:
There is no need to use Object.keys(),you can use merge_requests.length directly
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "[email protected]",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "[email protected]",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "[email protected]",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "[email protected]",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
}]
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
A:
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user?.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
merge_requests[i].merge_user?.name will return undefined if object is not present in the json.
A:
I copy & pasted your code & JSON and it works fine.
Make sure your JSON is parsed after getting it from ate API typeof merge_requests should return object, if it returns string then do the following:
const parsedData = JSON.parse(merge_requests) and loop through parsedData
A:
i checked your code it's working fine.
Check your api request, are you sure you waiting for it till it get fulfilled?
| Looping through nested JSON returns NULL | I'm trying to better understand how to work with nested JSON objects in JavaScript/React.
I am getting data through the GitLab API in the following form:
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "[email protected]",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "[email protected]",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "[email protected]",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "[email protected]",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},]
I want to loop through all objects(merge requests) in this JSON and create a new array with the merge_user.name.
console.log(merge_requests[0].merge_user.name);
console.log(merge_requests[1].merge_user.name);
The logs above return both the correct values. However, I cannot loop through the JSON to create a new array from the data like this:
const arrTest = [];
for(var i = 0; i < Object.keys(merge_requests).length; i++)
{
var mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
}
The code above leads to the following error: Uncaught (in promise) TypeError: resultData[i].merge_user is null
Here is a picture:
I am currently learning JS coming from R. I have huge problems working with JSON instead of dataframes and I cannot find any documentation to learn from. I would appreciated any advice/ sources.
| [
"There is no need to use Object.keys(),you can use merge_requests.length directly\nconst arrTest = [];\n\nfor(var i = 0; i < merge_requests.length; i++){\n let mergeUserName = merge_requests[i].merge_user.name;\n arrTest.push(mergeUserName);\n}\n\nconsole.log(arrTest);\n\n\n\nconst merge_requests = [\n {\n \"id\": 39329289,\n \"iid\": 156,\n \"project_id\": 231,\n \"title\": \"Repaired some Links\",\n \"description\": \"\",\n \"state\": \"merged\",\n \"created_at\": \"2022-12-03T12:22:14.690Z\",\n \"updated_at\": \"2022-12-03T12:22:20.060Z\",\n \"merged_by\": {\n \"id\": 1000,\n \"username\": \"test.user\",\n \"name\": \"[email protected]\",\n \"state\": \"active\",\n \"avatar_url\": \"\",\n \"web_url\": \"\"\n },\n \"merge_user\": {\n \"id\": 2802,\n \"username\": \"tes.user\",\n \"name\": \"[email protected]\",\n \"state\": \"active\",\n \"avatar_url\": \"\",\n \"web_url\": \"\"\n },\n \"merged_at\": \"2022-12-03T12:22:20.072Z\",\n \"closed_by\": null,\n \"closed_at\": null,\n \"assignees\": [],\n \"assignee\": null,\n \"reviewers\": [],\n \"source_project_id\": 231,\n \"target_project_id\": 231,\n \"labels\": [],\n \"squash_commit_sha\": null,\n \"discussion_locked\": null,\n \"should_remove_source_branch\": null,\n \"force_remove_source_branch\": null,\n \"reference\": \"!156\",\n \"references\": {\n \"short\": \"!156\",\n \"relative\": \"!156\",\n \"full\": \"\"\n },\n \"web_url\": \"\",\n \"time_stats\": {\n \"time_estimate\": 0,\n \"total_time_spent\": 0,\n \"human_time_estimate\": null,\n \"human_total_time_spent\": null\n },\n \"squash\": false,\n \"task_completion_status\": {\n \"count\": 0,\n \"completed_count\": 0\n },\n \"has_conflicts\": false,\n \"blocking_discussions_resolved\": true,\n \"approvals_before_merge\": null\n },\n {\n \"id\": 39329289,\n \"iid\": 156,\n \"project_id\": 231,\n \"title\": \"Repaired some Links\",\n \"description\": \"\",\n \"state\": \"merged\",\n \"created_at\": \"2022-12-03T12:22:14.690Z\",\n \"updated_at\": \"2022-12-03T12:22:20.060Z\",\n \"merged_by\": {\n \"id\": 1000,\n \"username\": \"test.user\",\n \"name\": \"[email protected]\",\n \"state\": \"active\",\n \"avatar_url\": \"\",\n \"web_url\": \"\"\n },\n \"merge_user\": {\n \"id\": 2802,\n \"username\": \"test.user\",\n \"name\": \"[email protected]\",\n \"state\": \"active\",\n \"avatar_url\": \"\",\n \"web_url\": \"\"\n },\n \"merged_at\": \"2022-12-03T12:22:20.072Z\",\n \"closed_by\": null,\n \"closed_at\": null,\n \"assignees\": [],\n \"assignee\": null,\n \"reviewers\": [],\n \"source_project_id\": 231,\n \"target_project_id\": 231,\n \"labels\": [],\n \"squash_commit_sha\": null,\n \"discussion_locked\": null,\n \"should_remove_source_branch\": null,\n \"force_remove_source_branch\": null,\n \"reference\": \"!156\",\n \"references\": {\n \"short\": \"!156\",\n \"relative\": \"!156\",\n \"full\": \"\"\n },\n \"web_url\": \"\",\n \"time_stats\": {\n \"time_estimate\": 0,\n \"total_time_spent\": 0,\n \"human_time_estimate\": null,\n \"human_total_time_spent\": null\n },\n \"squash\": false,\n \"task_completion_status\": {\n \"count\": 0,\n \"completed_count\": 0\n },\n \"has_conflicts\": false,\n \"blocking_discussions_resolved\": true,\n \"approvals_before_merge\": null\n }]\n \nconst arrTest = [];\n\nfor(var i = 0; i < merge_requests.length; i++){\n let mergeUserName = merge_requests[i].merge_user.name;\n arrTest.push(mergeUserName);\n}\n\nconsole.log(arrTest);\n\n\n\n",
"const arrTest = [];\n\nfor(var i = 0; i < merge_requests.length; i++){\n let mergeUserName = merge_requests[i].merge_user?.name;\n arrTest.push(mergeUserName);\n}\n\nconsole.log(arrTest);\n\nmerge_requests[i].merge_user?.name will return undefined if object is not present in the json.\n",
"I copy & pasted your code & JSON and it works fine.\nMake sure your JSON is parsed after getting it from ate API typeof merge_requests should return object, if it returns string then do the following:\nconst parsedData = JSON.parse(merge_requests) and loop through parsedData\n",
"i checked your code it's working fine.\nCheck your api request, are you sure you waiting for it till it get fulfilled?\n"
] | [
0,
0,
0,
0
] | [] | [] | [
"javascript",
"json"
] | stackoverflow_0074675137_javascript_json.txt |
Q:
How to hide the navigation button when using NavigationSplitView?
Now that the NavigationView was deprecated, I try to use the NavigationSplitView. But I can't hide the navigation toggle button, and also can't custom the title bar (I want to keep title and add filter button).
My app screenshot
I just want to realize like the Mail.app
Mail.app screenshot
Some other app screenshot
code snippet as bellow:
// ...
var body: some View {
NavigationSplitView(columnVisibility: $columnVisibility) {
DirectoryList(selection: $selectionDir)
} content: {
PaperList(selection: $selectionPaper)
.navigationTitle(Text("Papers"))
.toolbar {
HStack {
Button {
// something todo
} label: {
Label("Experience", systemImage: "wand.and.stars")
}
}
.frame(maxWidth: .infinity, alignment: .trailing)
}
} detail: {
Editor(selectionPaper?.name ?? "")
}
}
// ...
A:
You could try to use isToggleButtonHidden:
NavigationSplitView(columnVisibility: $columnVisibility, isToggleButtonHidden: true) {
// Your content here
}
| How to hide the navigation button when using NavigationSplitView? | Now that the NavigationView was deprecated, I try to use the NavigationSplitView. But I can't hide the navigation toggle button, and also can't custom the title bar (I want to keep title and add filter button).
My app screenshot
I just want to realize like the Mail.app
Mail.app screenshot
Some other app screenshot
code snippet as bellow:
// ...
var body: some View {
NavigationSplitView(columnVisibility: $columnVisibility) {
DirectoryList(selection: $selectionDir)
} content: {
PaperList(selection: $selectionPaper)
.navigationTitle(Text("Papers"))
.toolbar {
HStack {
Button {
// something todo
} label: {
Label("Experience", systemImage: "wand.and.stars")
}
}
.frame(maxWidth: .infinity, alignment: .trailing)
}
} detail: {
Editor(selectionPaper?.name ?? "")
}
}
// ...
| [
"You could try to use isToggleButtonHidden:\nNavigationSplitView(columnVisibility: $columnVisibility, isToggleButtonHidden: true) {\n // Your content here\n}\n\n"
] | [
0
] | [] | [] | [
"swift",
"swiftui"
] | stackoverflow_0074677504_swift_swiftui.txt |
Q:
PL-SQL I'm trying to use a variable value into an Insert Into - ERROR ORA-00984
I have a package that contains the following procedure:
`
PROCEDURE PRC_DO_ISCRIZIONE( P_ID_STUD IN NUMBER, P_ID_CORSO IN NUMBER)
IS
V_ID_CORSO NUMBER := NULL;
V_ID_STUD NUMBER := NULL;
V_NEXT_ID NUMBER := NULL;
EX_NO_STUD EXCEPTION;
EX_NO_CORSO EXCEPTION;
CURSOR C_LISTA_CORSI IS ( SELECT ID FROM CORSO);
CURSOR C_LISTA_STUD IS ( SELECT ID FROM STUDENTE);
BEGIN
SELECT MAX(ID) +1
INTO V_NEXT_ID
FROM ISCRIZIONE;
FOR S IN C_LISTA_STUD
LOOP
IF P_ID_STUD != S.ID
THEN RAISE EX_NO_STUD;
END IF;
END LOOP;
FOR C IN C_LISTA_CORSI
LOOP
IF P_ID_CORSO != C.ID
THEN RAISE EX_NO_CORSO;
END IF;
END LOOP;
SELECT ID
INTO V_ID_CORSO
FROM CORSO
WHERE ID = P_ID_CORSO;
SELECT ID
INTO V_ID_STUD
FROM STUDENTE
WHERE ID = P_ID_STUD;
INSERT INTO ISCRIZIONE(ID, ID_CORSO, ID_STUDENTE, DATA)
VALUES ( V_NEXT_ID , V_ID_CORSO, V_ID_STUDENTE, SYSDATE);
EXCEPTION
WHEN EX_NO_STUD
THEN DBMS_OUTPUT.PUT_LINE('NESSUNO STUDENTE CORRISPONDE ALL''ID INSERITO');
RETURN;
WHEN EX_NO_CORSO
THEN DBMS_OUTPUT.PUT_LINE('NESSUN CORSO CORRISPONDENTE ALL''ID INSERITO');
RETURN;
END PRC_DO_ISCRIZIONE;
`
But when I launch the create package body I get the error ora-00984: column not allowed in this case
the goal is that given a student ID and a course ID,if they exists in their relative tables, the procedure adds to the ENROLLMENT(Iscrizione) table a row containing student id, course id and date
A:
The source of your error appears to be the identifier V_ID_STUDENTE in the VALUES clause of your INSERT statement.
You don't have a local variable named V_ID_STUDENTE, but you do have one named V_ID_STUD. Try replacing V_ID_STUDENTE with V_ID_STUD.
| PL-SQL I'm trying to use a variable value into an Insert Into - ERROR ORA-00984 | I have a package that contains the following procedure:
`
PROCEDURE PRC_DO_ISCRIZIONE( P_ID_STUD IN NUMBER, P_ID_CORSO IN NUMBER)
IS
V_ID_CORSO NUMBER := NULL;
V_ID_STUD NUMBER := NULL;
V_NEXT_ID NUMBER := NULL;
EX_NO_STUD EXCEPTION;
EX_NO_CORSO EXCEPTION;
CURSOR C_LISTA_CORSI IS ( SELECT ID FROM CORSO);
CURSOR C_LISTA_STUD IS ( SELECT ID FROM STUDENTE);
BEGIN
SELECT MAX(ID) +1
INTO V_NEXT_ID
FROM ISCRIZIONE;
FOR S IN C_LISTA_STUD
LOOP
IF P_ID_STUD != S.ID
THEN RAISE EX_NO_STUD;
END IF;
END LOOP;
FOR C IN C_LISTA_CORSI
LOOP
IF P_ID_CORSO != C.ID
THEN RAISE EX_NO_CORSO;
END IF;
END LOOP;
SELECT ID
INTO V_ID_CORSO
FROM CORSO
WHERE ID = P_ID_CORSO;
SELECT ID
INTO V_ID_STUD
FROM STUDENTE
WHERE ID = P_ID_STUD;
INSERT INTO ISCRIZIONE(ID, ID_CORSO, ID_STUDENTE, DATA)
VALUES ( V_NEXT_ID , V_ID_CORSO, V_ID_STUDENTE, SYSDATE);
EXCEPTION
WHEN EX_NO_STUD
THEN DBMS_OUTPUT.PUT_LINE('NESSUNO STUDENTE CORRISPONDE ALL''ID INSERITO');
RETURN;
WHEN EX_NO_CORSO
THEN DBMS_OUTPUT.PUT_LINE('NESSUN CORSO CORRISPONDENTE ALL''ID INSERITO');
RETURN;
END PRC_DO_ISCRIZIONE;
`
But when I launch the create package body I get the error ora-00984: column not allowed in this case
the goal is that given a student ID and a course ID,if they exists in their relative tables, the procedure adds to the ENROLLMENT(Iscrizione) table a row containing student id, course id and date
| [
"The source of your error appears to be the identifier V_ID_STUDENTE in the VALUES clause of your INSERT statement.\nYou don't have a local variable named V_ID_STUDENTE, but you do have one named V_ID_STUD. Try replacing V_ID_STUDENTE with V_ID_STUD.\n"
] | [
1
] | [] | [] | [
"ora_00984",
"oracle",
"plsql"
] | stackoverflow_0074677328_ora_00984_oracle_plsql.txt |
Q:
How to use 'this' pointer passed to a lambda as a function argument within a lambda?
I am using VS 2019 (C++20).
I can't compile a code where I am using std::visit with std::variant and function overload. The compiler reports an error "Function Visit does not take one argument". Obviously, the problem is with 'this' argument, but I could not figure out what is wrong.
class MyObj
{
public:
void Visit(MyClass& arg) {};
};
void MyClass::Accept(std::variant<MyObj> arg)
{
std::visit(
overload{
[=, this](MyObj& target) {target.Visit(*this);}
}, arg);
}
What am I missing?
A:
The problem was with included header files. While VS IDE was fine, the compiler needed 'extern' declaration for the MyClass.
| How to use 'this' pointer passed to a lambda as a function argument within a lambda? | I am using VS 2019 (C++20).
I can't compile a code where I am using std::visit with std::variant and function overload. The compiler reports an error "Function Visit does not take one argument". Obviously, the problem is with 'this' argument, but I could not figure out what is wrong.
class MyObj
{
public:
void Visit(MyClass& arg) {};
};
void MyClass::Accept(std::variant<MyObj> arg)
{
std::visit(
overload{
[=, this](MyObj& target) {target.Visit(*this);}
}, arg);
}
What am I missing?
| [
"The problem was with included header files. While VS IDE was fine, the compiler needed 'extern' declaration for the MyClass.\n"
] | [
0
] | [] | [] | [
"lambda",
"std",
"visual_c++"
] | stackoverflow_0074675633_lambda_std_visual_c++.txt |
Q:
How do I store a Firestore document reference as a field from nextjs?
Im creating simple blog posts and trying to connect the post to the logged in user.
When i create a document reference to be stored as a field with reference type, I get a map as shown below:
Here is what I tried
The logged in user is stored in context and the data is sent to an api route along with user as a reference that already exists in the database:
import {useAuth} from '../../context/AuthContext';
page function() {
const {user} = useAuth();
const onSubmit = async () => {
const { title, body } = content;
await axios.post('/api/post', {title, slug: dashify(title), body, author: doc(db, 'users/' + user.uid)
setContent({title: '', content: ''})
}
}
the api code is as follows
const handler = async (req, res) => {
try {
const posts = await getDocs(postsRef);
const postsData = posts.docs.map((post) => post.data());
if (postsData.some((post) => post.slug == "slug")) res.status(406).end();
else {
const newPost = await addDoc(collection(db, 'posts'), {
...req.body,
createdAt: serverTimestamp(),
});
log(newPost, "post details");
res.status(200).json({ newPost });
}
// res.status(201).json({ author });
} catch (e) {
log(e, "error occured post");
res.status(400).end();
}
};
export default handler;
A:
Instead of passing a DocumentReference directly from frontend, try passing the document path and then create a DocumentReference object on server side as shown below:
// API request
await axios.post('/api/post', {
title,
slug: dashify(title),
body,
author: `users/${user.uid}`
})
// Handler
const newPost = await addDoc(collection(db, 'posts'), {
...req.body,
author: doc(db, req.body.author)
createdAt: serverTimestamp(),
});
| How do I store a Firestore document reference as a field from nextjs? | Im creating simple blog posts and trying to connect the post to the logged in user.
When i create a document reference to be stored as a field with reference type, I get a map as shown below:
Here is what I tried
The logged in user is stored in context and the data is sent to an api route along with user as a reference that already exists in the database:
import {useAuth} from '../../context/AuthContext';
page function() {
const {user} = useAuth();
const onSubmit = async () => {
const { title, body } = content;
await axios.post('/api/post', {title, slug: dashify(title), body, author: doc(db, 'users/' + user.uid)
setContent({title: '', content: ''})
}
}
the api code is as follows
const handler = async (req, res) => {
try {
const posts = await getDocs(postsRef);
const postsData = posts.docs.map((post) => post.data());
if (postsData.some((post) => post.slug == "slug")) res.status(406).end();
else {
const newPost = await addDoc(collection(db, 'posts'), {
...req.body,
createdAt: serverTimestamp(),
});
log(newPost, "post details");
res.status(200).json({ newPost });
}
// res.status(201).json({ author });
} catch (e) {
log(e, "error occured post");
res.status(400).end();
}
};
export default handler;
| [
"Instead of passing a DocumentReference directly from frontend, try passing the document path and then create a DocumentReference object on server side as shown below:\n// API request\nawait axios.post('/api/post', {\n title,\n slug: dashify(title),\n body,\n author: `users/${user.uid}`\n})\n\n// Handler\nconst newPost = await addDoc(collection(db, 'posts'), {\n ...req.body,\n author: doc(db, req.body.author)\n createdAt: serverTimestamp(),\n});\n\n"
] | [
1
] | [] | [] | [
"firebase",
"google_cloud_firestore",
"javascript",
"next.js"
] | stackoverflow_0074677584_firebase_google_cloud_firestore_javascript_next.js.txt |
Q:
How to split multiple word Models in ASP.NET MVC?
My project has models with 2 or more words in the name:
EngineConfigurationModel
MyProductModel
CurrentProductModel
CheckNetworkInventoryModel
I've got an extension that can create a breadcrumb:
public static string BuildBreadcrumbNavigation(this HtmlHelper helper)
{
// optional condition: I didn't wanted it to show on home and account controller
if (helper.ViewContext.RouteData.Values["controller"].ToString() == "Home" ||
helper.ViewContext.RouteData.Values["controller"].ToString() == "Account")
{
return string.Empty;
}
var htmlLink = helper.ActionLink("Home", "Index", "Home").ToHtmlString();
var sb = new StringBuilder("<ol class='breadcrumb'><li>");
sb.Append(htmlLink);
sb.Append("</li>");
sb.Append("<li>");
sb.Append(helper.ActionLink(helper.ViewContext.RouteData.Values["controller"].ToString().Titleize(),
"", // "Index",
helper.ViewContext.RouteData.Values["controller"].ToString()));
sb.Append("</li>");
if (helper.ViewContext.RouteData.Values["action"].ToString() != "Index")
{
sb.Append("<li>");
sb.Append(helper.ActionLink(helper.ViewContext.RouteData.Values["action"].ToString().Titleize(),
helper.ViewContext.RouteData.Values["action"].ToString(),
helper.ViewContext.RouteData.Values["controller"].ToString()));
sb.Append("</li>");
}
var result = sb.Append("</ol>").ToString().Replace("Index", "");
return result;
}
Source: https://stackoverflow.com/a/26439510/153923
But, I want to split-up the words for project models with 2 or more words in the name.
for EngineConfigurationModel, class name EngineConfiguration would be 'Engine Configuration'
MyProductModel, class name MyProduct would be 'My Product'
CurrentProductModel, class name CurrentProduct would be 'Current Product'
CheckNetworkInventoryModel, class name CheckNetworkInventory would be 'Check Network Inventory'
For model properties with multiple words, I can use a [Display(Name = "some thing")] parameter like this:
[Display(Name = "Some Thing")]
public string SomeThing { get; set; }
I tried putting the Display attribute on the class declaration, but VS2022 says:
Attribute 'Display' is not valid on this declaration type. It is only valid on 'method, property, indexer, field, parameter' declarations.
A:
I made something and I put it into an extension.
Adding my work here for others to use.
public static string SplitTitleWords(this string value)
{
var result = value;
if (!string.IsNullOrEmpty(result) && (1 < result.Length))
{
var offset = 0;
var indexes = from c in result.ToArray()
where Char.IsUpper(c)
select result.IndexOf(c, 1);
foreach (var index in indexes)
{
if ((0 < index) && (index < result.Length))
{
result = $"{result.Substring(0, index)} {result.Substring(index + offset++)}";
}
}
}
return result;
}
| How to split multiple word Models in ASP.NET MVC? | My project has models with 2 or more words in the name:
EngineConfigurationModel
MyProductModel
CurrentProductModel
CheckNetworkInventoryModel
I've got an extension that can create a breadcrumb:
public static string BuildBreadcrumbNavigation(this HtmlHelper helper)
{
// optional condition: I didn't wanted it to show on home and account controller
if (helper.ViewContext.RouteData.Values["controller"].ToString() == "Home" ||
helper.ViewContext.RouteData.Values["controller"].ToString() == "Account")
{
return string.Empty;
}
var htmlLink = helper.ActionLink("Home", "Index", "Home").ToHtmlString();
var sb = new StringBuilder("<ol class='breadcrumb'><li>");
sb.Append(htmlLink);
sb.Append("</li>");
sb.Append("<li>");
sb.Append(helper.ActionLink(helper.ViewContext.RouteData.Values["controller"].ToString().Titleize(),
"", // "Index",
helper.ViewContext.RouteData.Values["controller"].ToString()));
sb.Append("</li>");
if (helper.ViewContext.RouteData.Values["action"].ToString() != "Index")
{
sb.Append("<li>");
sb.Append(helper.ActionLink(helper.ViewContext.RouteData.Values["action"].ToString().Titleize(),
helper.ViewContext.RouteData.Values["action"].ToString(),
helper.ViewContext.RouteData.Values["controller"].ToString()));
sb.Append("</li>");
}
var result = sb.Append("</ol>").ToString().Replace("Index", "");
return result;
}
Source: https://stackoverflow.com/a/26439510/153923
But, I want to split-up the words for project models with 2 or more words in the name.
for EngineConfigurationModel, class name EngineConfiguration would be 'Engine Configuration'
MyProductModel, class name MyProduct would be 'My Product'
CurrentProductModel, class name CurrentProduct would be 'Current Product'
CheckNetworkInventoryModel, class name CheckNetworkInventory would be 'Check Network Inventory'
For model properties with multiple words, I can use a [Display(Name = "some thing")] parameter like this:
[Display(Name = "Some Thing")]
public string SomeThing { get; set; }
I tried putting the Display attribute on the class declaration, but VS2022 says:
Attribute 'Display' is not valid on this declaration type. It is only valid on 'method, property, indexer, field, parameter' declarations.
| [
"I made something and I put it into an extension.\nAdding my work here for others to use.\npublic static string SplitTitleWords(this string value)\n{\n var result = value;\n if (!string.IsNullOrEmpty(result) && (1 < result.Length))\n {\n var offset = 0;\n var indexes = from c in result.ToArray()\n where Char.IsUpper(c)\n select result.IndexOf(c, 1);\n foreach (var index in indexes)\n {\n if ((0 < index) && (index < result.Length))\n {\n result = $\"{result.Substring(0, index)} {result.Substring(index + offset++)}\";\n }\n }\n }\n return result;\n}\n\n"
] | [
0
] | [] | [] | [
"asp.net_mvc",
"c#"
] | stackoverflow_0074660478_asp.net_mvc_c#.txt |
Q:
Angular 6: provide HTTP_INTERCEPTORS for 'root'
With the change from Angular 5 where you provide service in AppModule to Angular 6 where you set 'provideIn' key in @Injectable decorator I have changed all services to use new "provideIn" method. However, exception is my Interceptor Service.
How can I provide HTTP_INTERCEPTORS token for 'root' and use InterceptorService?
this is the Angular 5 way I use atm:
@Injectable()
export class InterceptorService implements HttpInterceptor {
...
}
in AppModule:
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: InterceptorService,
multi: true
}]
But what would be Angular 6 way?
I've tried something like
@Injectable({
provideIn: 'root',
useValue: HTTP_INTERCEPTORS,
deps: [forwardRef(() => InterceptorService)]
})
export class InterceptorService implements HttpInterceptor {
...
}
and a lot of other variants with Injectable but can't seem to figure out how to make it work without writing an object literal directly into providers of a module.
A:
A couple things to note here:
1. providedIn: 'root' is a nice feature but it probably wasn't built for you
As @Leon mentioned, this feature is meant to make services more tree shakeable. It is not meant to completely replace using the providers: [] property of a module. It is an option mostly meant for library developers, not as much for application developers.
Imagine this scenario:
You created a service a few months ago and now your app is no longer using it. You know it's not using it because it's your app and you have full knowledge and control over the codebase. What do you do to that service?
A) Make sure it's using providedIn: 'root' so that Angular can tree shake it out of the bundle since you're not using it anymore
B) Delete the service.
My guess is B!
Imagine another scenario:
You are using a 3rd party Angular module from an npm package. That module has 12 difference services you can use in your app to take advantage of its features. Your app doesn't need all those features so you only inject 3 of those service types into your application components or services.
How do you resolve this?
A) Fork the repository so you can remove all the services your app doesn't use so you don't have to include them in your bundle.
B) Ask the project owner to use providedIn: 'root'. If the library author used providedIn: 'root' the services you don't use don't have an impact on your bundle size and they can stay in the npm package/Angular module for other teams to use if they need them.
My guess is B!
2. providedIn: 'root' doesn't work for interceptors
Interceptors are a multi DI token service which means you can provide multiple values for the same DI token. That token is HTTP_INTERCEPTORS. The @Injectable({...}) decorator exposes no api for providing the decorated type for a different token the way the @NgModule({...}) decorator does.
This means you can't tell Angular Anywhere you would normally ask for 'HTTP_INTERCEPTORS' add this service to the set of values to use instead using the @Injectable({...}) decorator.
You can only do this in a @NgModule({...}) decorator.
3. Providing interceptors is order dependent
Interceptors are a pipeline and the order they are provided in matters in determining the order they get access to the request object (to modify or inspect) and the response object (to modify or inspect).
While some interceptors might be order agnostic you still probably want some determinism in that ordering.
So even if providedIn: 'root' worked for interceptors the order they would be provided in would be determined by the resolution order of types during the Angular compile step - probably not what you want.
Instead providing them in the providers: [] array in an @NgModule({...}) decorator means you can explicitly set the order they will be called in.
A:
The provideIn-property of Angular 6 is just an addition to the behaviour in Angular 5. If you want to provide something with an already existing InjectionToken, you still have to use the { provide: ClassA, useClass: ClassB } syntax.
See -> https://angular.io/guide/dependency-injection-in-action#external-module-configuration
tl;dr:
The way you provide HTTP_INTERCEPTORS has not changed in Angular 6 and there is no "Angular 6"-way.
A:
In Interceptor
@Injectable()
export class InterceptorService implements HttpInterceptor {
...
}
In App Module
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: InterceptorService,
multi: true
}]
"providedIn ... tells Angular that the root injector is responsible for
creating an instance of the [service]. Services that are provided this way are > automatically made available to the entire application and don't need to be
listed in any module."
"If a provider cannot be configured in the @Injectable decorator of the
service, then register application-wide providers in the root AppModule, not
in the AppComponent. Generally, register providers in the NgModule rather than > in the root application component."
Furthermore, if the scope of the service should be limited to a feature or branch of the application, provide that service at the top level component for that branch/feature
https://angular.io/guide/dependency-injection-in-action
A:
Here is an example of a JWT token interceptor:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler) {
// Get the JWT token from local storage
const token = localStorage.getItem('jwtToken');
// If the token exists, add it to the authorization header of the request
if (token) {
request = request.clone({
setHeaders: {
'x-token': token
}
});
}
return next.handle(request);
}
}
To use the interceptor, you will need to register it in the @NgModule where it will be used. In the providers array, include the interceptor class and provide it with the HTTP_INTERCEPTORS token.
import { JwtInterceptor } from './jwt.interceptor';
@NgModule({
// ...
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true
}
]
})
export class AppModule { }
The JWT token interceptor will automatically add the JWT token to the "x-token" header of the HTTP request, allowing the server to authenticate the request.
| Angular 6: provide HTTP_INTERCEPTORS for 'root' | With the change from Angular 5 where you provide service in AppModule to Angular 6 where you set 'provideIn' key in @Injectable decorator I have changed all services to use new "provideIn" method. However, exception is my Interceptor Service.
How can I provide HTTP_INTERCEPTORS token for 'root' and use InterceptorService?
this is the Angular 5 way I use atm:
@Injectable()
export class InterceptorService implements HttpInterceptor {
...
}
in AppModule:
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: InterceptorService,
multi: true
}]
But what would be Angular 6 way?
I've tried something like
@Injectable({
provideIn: 'root',
useValue: HTTP_INTERCEPTORS,
deps: [forwardRef(() => InterceptorService)]
})
export class InterceptorService implements HttpInterceptor {
...
}
and a lot of other variants with Injectable but can't seem to figure out how to make it work without writing an object literal directly into providers of a module.
| [
"A couple things to note here:\n1. providedIn: 'root' is a nice feature but it probably wasn't built for you\nAs @Leon mentioned, this feature is meant to make services more tree shakeable. It is not meant to completely replace using the providers: [] property of a module. It is an option mostly meant for library developers, not as much for application developers.\nImagine this scenario:\nYou created a service a few months ago and now your app is no longer using it. You know it's not using it because it's your app and you have full knowledge and control over the codebase. What do you do to that service?\nA) Make sure it's using providedIn: 'root' so that Angular can tree shake it out of the bundle since you're not using it anymore\nB) Delete the service.\nMy guess is B!\nImagine another scenario:\nYou are using a 3rd party Angular module from an npm package. That module has 12 difference services you can use in your app to take advantage of its features. Your app doesn't need all those features so you only inject 3 of those service types into your application components or services.\nHow do you resolve this?\nA) Fork the repository so you can remove all the services your app doesn't use so you don't have to include them in your bundle.\nB) Ask the project owner to use providedIn: 'root'. If the library author used providedIn: 'root' the services you don't use don't have an impact on your bundle size and they can stay in the npm package/Angular module for other teams to use if they need them.\nMy guess is B!\n2. providedIn: 'root' doesn't work for interceptors\nInterceptors are a multi DI token service which means you can provide multiple values for the same DI token. That token is HTTP_INTERCEPTORS. The @Injectable({...}) decorator exposes no api for providing the decorated type for a different token the way the @NgModule({...}) decorator does.\nThis means you can't tell Angular Anywhere you would normally ask for 'HTTP_INTERCEPTORS' add this service to the set of values to use instead using the @Injectable({...}) decorator.\nYou can only do this in a @NgModule({...}) decorator.\n3. Providing interceptors is order dependent\nInterceptors are a pipeline and the order they are provided in matters in determining the order they get access to the request object (to modify or inspect) and the response object (to modify or inspect).\nWhile some interceptors might be order agnostic you still probably want some determinism in that ordering.\nSo even if providedIn: 'root' worked for interceptors the order they would be provided in would be determined by the resolution order of types during the Angular compile step - probably not what you want.\nInstead providing them in the providers: [] array in an @NgModule({...}) decorator means you can explicitly set the order they will be called in.\n",
"The provideIn-property of Angular 6 is just an addition to the behaviour in Angular 5. If you want to provide something with an already existing InjectionToken, you still have to use the { provide: ClassA, useClass: ClassB } syntax.\nSee -> https://angular.io/guide/dependency-injection-in-action#external-module-configuration\ntl;dr:\nThe way you provide HTTP_INTERCEPTORS has not changed in Angular 6 and there is no \"Angular 6\"-way.\n",
"In Interceptor\n@Injectable()\nexport class InterceptorService implements HttpInterceptor {\n...\n}\n\nIn App Module\nproviders: [{\n provide: HTTP_INTERCEPTORS,\n useClass: InterceptorService,\n multi: true\n}]\n\n\n\"providedIn ... tells Angular that the root injector is responsible for\ncreating an instance of the [service]. Services that are provided this way are > automatically made available to the entire application and don't need to be\nlisted in any module.\"\n\"If a provider cannot be configured in the @Injectable decorator of the\nservice, then register application-wide providers in the root AppModule, not\nin the AppComponent. Generally, register providers in the NgModule rather than > in the root application component.\"\n\nFurthermore, if the scope of the service should be limited to a feature or branch of the application, provide that service at the top level component for that branch/feature\nhttps://angular.io/guide/dependency-injection-in-action\n",
"Here is an example of a JWT token interceptor:\nimport { Injectable } from '@angular/core';\nimport { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';\n\n@Injectable()\nexport class JwtInterceptor implements HttpInterceptor {\n intercept(request: HttpRequest<any>, next: HttpHandler) {\n // Get the JWT token from local storage\n const token = localStorage.getItem('jwtToken');\n\n // If the token exists, add it to the authorization header of the request\n if (token) {\n request = request.clone({\n setHeaders: {\n 'x-token': token\n }\n });\n }\n\n return next.handle(request);\n }\n}\n\nTo use the interceptor, you will need to register it in the @NgModule where it will be used. In the providers array, include the interceptor class and provide it with the HTTP_INTERCEPTORS token.\nimport { JwtInterceptor } from './jwt.interceptor';\n\n@NgModule({\n // ...\n providers: [\n {\n provide: HTTP_INTERCEPTORS,\n useClass: JwtInterceptor,\n multi: true\n }\n ]\n})\nexport class AppModule { }\n\nThe JWT token interceptor will automatically add the JWT token to the \"x-token\" header of the HTTP request, allowing the server to authenticate the request.\n"
] | [
8,
5,
3,
0
] | [] | [] | [
"angular",
"angular6",
"injectable",
"service",
"typescript"
] | stackoverflow_0050211120_angular_angular6_injectable_service_typescript.txt |
Q:
Data types int and double in calculating e
Why, when I use double i the output is (an approximation to) the value of e?
#include <iostream>
using namespace std;
int main ()
{
double s=0;
double i=1;
for (int m=1;m<5;m++)
{
i=m*i;
s=s+1/i;
}
cout<<s+1;
return 0;
}
But when I use int i, the output is 2:
#include <iostream>
using namespace std;
int main ()
{
double s=0;
int i=1;
for (int m=1;m<5;m++)
{
i=m*i;
s=s+1/i;
}
cout<<s+1;
return 0;
}
The variable that stores the value of e is s, which is double, so I was expecting that the datatype of i doesn't matter.
A:
The reason that the output is different when you use double or int for the i variable is because of the way that division works in C++. When you use integer division, the result of the division is also an integer. So, in the second example where i is an int, each time you perform the division 1/i, the result is always an integer, which is then converted to a double and added to s. This means that some of the fractional parts of the calculation are being lost.
In the first example, where i is a double, the result of the division 1/i is also a double, and the fractional parts of the calculation are preserved. This is why the output is different in the two cases.
One way to fix this would be to use the 1.0 instead of 1 in the division, like this:
#include <iostream>
using namespace std;
int main ()
{
double s=0;
int i=1;
for (int m=1;m<5;m++)
{
i=m*i;
s=s+1.0/i;
}
cout<<s+1;
return 0;
}
This way, the 1.0 will be treated as a double, and the result of the division will also be a double, so the fractional parts of the calculation will be preserved.
| Data types int and double in calculating e | Why, when I use double i the output is (an approximation to) the value of e?
#include <iostream>
using namespace std;
int main ()
{
double s=0;
double i=1;
for (int m=1;m<5;m++)
{
i=m*i;
s=s+1/i;
}
cout<<s+1;
return 0;
}
But when I use int i, the output is 2:
#include <iostream>
using namespace std;
int main ()
{
double s=0;
int i=1;
for (int m=1;m<5;m++)
{
i=m*i;
s=s+1/i;
}
cout<<s+1;
return 0;
}
The variable that stores the value of e is s, which is double, so I was expecting that the datatype of i doesn't matter.
| [
"The reason that the output is different when you use double or int for the i variable is because of the way that division works in C++. When you use integer division, the result of the division is also an integer. So, in the second example where i is an int, each time you perform the division 1/i, the result is always an integer, which is then converted to a double and added to s. This means that some of the fractional parts of the calculation are being lost.\nIn the first example, where i is a double, the result of the division 1/i is also a double, and the fractional parts of the calculation are preserved. This is why the output is different in the two cases.\nOne way to fix this would be to use the 1.0 instead of 1 in the division, like this:\n#include <iostream>\nusing namespace std;\nint main ()\n{\n double s=0;\n int i=1;\n for (int m=1;m<5;m++)\n {\n i=m*i;\n s=s+1.0/i;\n }\n cout<<s+1;\n return 0;\n}\n\nThis way, the 1.0 will be treated as a double, and the result of the division will also be a double, so the fractional parts of the calculation will be preserved.\n"
] | [
-2
] | [
"You're doing integer division on this line when i is an integer:\ns=s+1/i;\n\nYou want to instead do floating point division:\ns = s + 1.0 / i;\n\n"
] | [
-2
] | [
"c++"
] | stackoverflow_0074677598_c++.txt |
Q:
Can nerdctl/crictl be used to list containers started by docker
I'm using version 20.10.21 of docker, in my understanding docker with this version uses containerd to manage image and container lifecycle, but why cannot I use crictl/nerdctl to list the containers which I started by docker cli?
What I've tried:
Check if docker uses containerd to manage contianers, ths is the result of systemctl status docker
docker.service - Docker Application Container Engine
Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; preset: disabled)
Drop-In: /etc/systemd/system/docker.service.d
└─http-proxy.conf
Active: active (running) since Sun 2022-12-04 22:44:27 CST; 1min 18s ago TriggeredBy: ● docker.socket
Docs: https://docs.docker.com Main PID: 1821 (dockerd)
Tasks: 91 (limit: 38297)
Memory: 229.6M
CPU: 1.214s
CGroup: /system.slice/docker.service
├─1821 /usr/bin/dockerd -H fd://
├─1845 containerd --config /var/run/docker/containerd/containerd.toml --log-level info
I guess this means containerd is started by docker daemon. And the unix socket is located at /var/run/docker/containerd/containerd.sock
Try nerdctl to list containers but got error message:
$ nerdctl --address unix:///var/run/docker/containerd/containerd.sock ps
FATA[0000] rootless containerd not running? (hint: use `containerd-rootless-setuptool.sh install` to start rootless containerd): stat /run/user/1000/containerd-rootless: no such file or directory
Then I tried it again with sudo
sudo nerdctl --address unix:///var/run/docker/containerd/containerd.sock ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
As you can see, there's no container listed, but docker ps shows many containers I started.
Try crictl to check result, but got errors:
sudo crictl --r unix:///var/run/docker/containerd/containerd.sock ps
E1204 22:47:27.190569 3925 remote_runtime.go:557] "ListContainers with filter from runtime service failed" err="rpc error: code = Unimplemented desc = unknown service runtime.v1alpha2.RuntimeService" filter="&ContainerFilter{Id:,State:&ContainerStateValue{State:CONTAINER_RUNNING,},PodSandboxId:,LabelSelector:map[string]string{},}"
FATA[0000] listing containers: rpc error: code = Unimplemented desc = unknown service runtime.v1alpha2.RuntimeService
So my questions is: Why can't I get the same results of docker cli by nerdctl/crictl? Is there anything wrong I've done? or anything wrong in my understanding?
Thanks for any tips.
A:
Yes, nerdctl and crictl can be used to list containers started by Docker. In fact, nerdctl and crictl are command line tools that provide an interface to containerd, which is the component in Docker that is responsible for managing the lifecycle of containers. So, if Docker is using containerd to manage its containers, you should be able to use nerdctl or crictl to list those containers.
To use nerdctl or crictl, you will need to specify the address of the containerd socket, which you can find by running the systemctl status docker command and looking for the containerd.sock file. You can then use the --address flag to specify the socket when running nerdctl or crictl commands. For example, to list all containers using nerdctl, you could run the following command:
nerdctl --address unix:///var/run/docker/containerd/containerd.sock ps
If you are still not able to see any containers when running this command, there may be a problem with the connection to the containerd socket. You can try using the --debug flag when running nerdctl or crictl commands to see more detailed output and diagnose the problem.
UPDATE:
It sounds like you are encountering some errors when using nerdctl and crictl to list containers managed by docker. There could be a few potential reasons for this.
First, it is important to note that, by default, docker uses its own internal container runtime to manage containers, and it does not expose the underlying containerd runtime directly to users. As a result, you may not be able to use tools like nerdctl and crictl to directly interact with the containers managed by docker.
Additionally, it is possible that the versions of nerdctl and crictl that you are using are not compatible with the version of containerd that docker is using. As containerd is an evolving technology, the API and functionality exposed by different versions of containerd can vary, and you may need to use versions of nerdctl and crictl that are specifically designed to work with the version of containerd that docker is using.
Lastly, it is worth noting that, in some cases, you may need to use the --rootless flag when running nerdctl and crictl to interact with a rootless docker installation. This flag tells the tools to use the rootless version of containerd, which is used by docker in rootless mode.
In summary, there could be a few potential reasons why you are not able to use nerdctl and crictl to list the containers managed by docker. It may be worth trying to use different versions of these tools, and using the --rootless flag, to see if that helps resolve the issues that you are encountering.
| Can nerdctl/crictl be used to list containers started by docker | I'm using version 20.10.21 of docker, in my understanding docker with this version uses containerd to manage image and container lifecycle, but why cannot I use crictl/nerdctl to list the containers which I started by docker cli?
What I've tried:
Check if docker uses containerd to manage contianers, ths is the result of systemctl status docker
docker.service - Docker Application Container Engine
Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; preset: disabled)
Drop-In: /etc/systemd/system/docker.service.d
└─http-proxy.conf
Active: active (running) since Sun 2022-12-04 22:44:27 CST; 1min 18s ago TriggeredBy: ● docker.socket
Docs: https://docs.docker.com Main PID: 1821 (dockerd)
Tasks: 91 (limit: 38297)
Memory: 229.6M
CPU: 1.214s
CGroup: /system.slice/docker.service
├─1821 /usr/bin/dockerd -H fd://
├─1845 containerd --config /var/run/docker/containerd/containerd.toml --log-level info
I guess this means containerd is started by docker daemon. And the unix socket is located at /var/run/docker/containerd/containerd.sock
Try nerdctl to list containers but got error message:
$ nerdctl --address unix:///var/run/docker/containerd/containerd.sock ps
FATA[0000] rootless containerd not running? (hint: use `containerd-rootless-setuptool.sh install` to start rootless containerd): stat /run/user/1000/containerd-rootless: no such file or directory
Then I tried it again with sudo
sudo nerdctl --address unix:///var/run/docker/containerd/containerd.sock ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
As you can see, there's no container listed, but docker ps shows many containers I started.
Try crictl to check result, but got errors:
sudo crictl --r unix:///var/run/docker/containerd/containerd.sock ps
E1204 22:47:27.190569 3925 remote_runtime.go:557] "ListContainers with filter from runtime service failed" err="rpc error: code = Unimplemented desc = unknown service runtime.v1alpha2.RuntimeService" filter="&ContainerFilter{Id:,State:&ContainerStateValue{State:CONTAINER_RUNNING,},PodSandboxId:,LabelSelector:map[string]string{},}"
FATA[0000] listing containers: rpc error: code = Unimplemented desc = unknown service runtime.v1alpha2.RuntimeService
So my questions is: Why can't I get the same results of docker cli by nerdctl/crictl? Is there anything wrong I've done? or anything wrong in my understanding?
Thanks for any tips.
| [
"Yes, nerdctl and crictl can be used to list containers started by Docker. In fact, nerdctl and crictl are command line tools that provide an interface to containerd, which is the component in Docker that is responsible for managing the lifecycle of containers. So, if Docker is using containerd to manage its containers, you should be able to use nerdctl or crictl to list those containers.\nTo use nerdctl or crictl, you will need to specify the address of the containerd socket, which you can find by running the systemctl status docker command and looking for the containerd.sock file. You can then use the --address flag to specify the socket when running nerdctl or crictl commands. For example, to list all containers using nerdctl, you could run the following command:\nnerdctl --address unix:///var/run/docker/containerd/containerd.sock ps\n\nIf you are still not able to see any containers when running this command, there may be a problem with the connection to the containerd socket. You can try using the --debug flag when running nerdctl or crictl commands to see more detailed output and diagnose the problem.\nUPDATE:\nIt sounds like you are encountering some errors when using nerdctl and crictl to list containers managed by docker. There could be a few potential reasons for this.\nFirst, it is important to note that, by default, docker uses its own internal container runtime to manage containers, and it does not expose the underlying containerd runtime directly to users. As a result, you may not be able to use tools like nerdctl and crictl to directly interact with the containers managed by docker.\nAdditionally, it is possible that the versions of nerdctl and crictl that you are using are not compatible with the version of containerd that docker is using. As containerd is an evolving technology, the API and functionality exposed by different versions of containerd can vary, and you may need to use versions of nerdctl and crictl that are specifically designed to work with the version of containerd that docker is using.\nLastly, it is worth noting that, in some cases, you may need to use the --rootless flag when running nerdctl and crictl to interact with a rootless docker installation. This flag tells the tools to use the rootless version of containerd, which is used by docker in rootless mode.\nIn summary, there could be a few potential reasons why you are not able to use nerdctl and crictl to list the containers managed by docker. It may be worth trying to use different versions of these tools, and using the --rootless flag, to see if that helps resolve the issues that you are encountering.\n"
] | [
1
] | [] | [] | [
"containerd",
"docker",
"nerdctl"
] | stackoverflow_0074677606_containerd_docker_nerdctl.txt |
Q:
How do I put space between each element of a list?
I have an appendable list of View and I want to add space to between each element of my list.
Here is an overview of my code -
list = []
function func(){
button(){
list.append(
<View style = {1}>
...
...
...
<\View>
)
}
return(
<View>
<View>
<Text onPress = {() => button()}> + </Text>
<\View>
<ScrollView style = {3}>
<View style = {2}>
{list}
<\View>
<\ScrollView>
<\View>
)
}
My app currently looks something like this -
My question is which CSS component should I style - {1}, {2} or {3}?
Here is my actual code -
import React, { Component, useState, useEffect } from "react";
import {
View,
Text,
StyleSheet,
TextInput,
ScrollView
} from 'react-native';
function WeatherApp(){
const [data, setData] = useState([])
const[i, setI] = useState(0)
const dates = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const temperatures = [20, 21, 26, 19, 30, 32, 23, 22, 24]
const cities = ['LA', 'SAN', 'SFO', 'LGA', 'HND', 'KIX', 'DEN', 'MUC', 'BOM']
const buttonPressed = () => {
if(i < 9){
data.push(
<View style = {styles.weatherBoard}>
<Text key = {dates[i]} style = {styles.date}>{dates[i]}</Text>
<Text key = {temperatures[i]} style = {styles.temperature}>{temperatures[i]}</Text>
<Text key = {cities[i]} style = {styles.cityName}>{cities[i]}</Text>
</View>
)
setData(data)
setI(i => i + 1)
}
}
useEffect(()=>{}, [i])
return(
<View style = {styles.appBackground}>
<View style = {styles.searchBar}>
<TextInput style = {styles.searchText} placeholder = "Search City"></TextInput>
<Text onPress={() => buttonPressed()} style = {styles.addButton}>+</Text>
</View>
{/* ScrollView can only have one view in it */}
<ScrollView style = {styles.weatherPanel} >
<View>
{data}
</View>
</ScrollView>
</View>
)
}
Here is my css file -
const styles = StyleSheet.create({
appBackground:{
flex: 1,
backgroundColor: 'black',
flexDirection: 'column'
},
searchBar:{
flex: 0.1,
flexDirection: 'row',
backgroundColor: 'white',
fontSize: 25
},
searchText:{
flex: 8,
borderWidth: 1
},
addButton:{
flex: 2,
textAlign: 'center',
fontSize: 40,
borderWidth: 1
},
// Place where all cities' weather are shown
weatherPanel:{
flex: 0.9,
flexDirection: 'column',
padding: 15
},
// Style for each city
weatherBoard:{
flex: 9,
backgroundColor: 'blue',
borderRadius: 10,
padding: 10
},
// Temorary styles -
date: {
fontSize: 20,
color: 'white'
},
temperature:{
fontSize: 30
},
cityName:{
fontSize: 30
}
})
A:
Placing a style={{marginTop: 12}} should be fine
list.append(
<View style={{marginTop: 12}}>
...
...
...
</View>
)
A:
You can use ItemSeparatorComponent property for your list and provide any separator component you want.
https://reactnative.dev/docs/virtualizedlist#itemseparatorcomponent
| How do I put space between each element of a list? | I have an appendable list of View and I want to add space to between each element of my list.
Here is an overview of my code -
list = []
function func(){
button(){
list.append(
<View style = {1}>
...
...
...
<\View>
)
}
return(
<View>
<View>
<Text onPress = {() => button()}> + </Text>
<\View>
<ScrollView style = {3}>
<View style = {2}>
{list}
<\View>
<\ScrollView>
<\View>
)
}
My app currently looks something like this -
My question is which CSS component should I style - {1}, {2} or {3}?
Here is my actual code -
import React, { Component, useState, useEffect } from "react";
import {
View,
Text,
StyleSheet,
TextInput,
ScrollView
} from 'react-native';
function WeatherApp(){
const [data, setData] = useState([])
const[i, setI] = useState(0)
const dates = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const temperatures = [20, 21, 26, 19, 30, 32, 23, 22, 24]
const cities = ['LA', 'SAN', 'SFO', 'LGA', 'HND', 'KIX', 'DEN', 'MUC', 'BOM']
const buttonPressed = () => {
if(i < 9){
data.push(
<View style = {styles.weatherBoard}>
<Text key = {dates[i]} style = {styles.date}>{dates[i]}</Text>
<Text key = {temperatures[i]} style = {styles.temperature}>{temperatures[i]}</Text>
<Text key = {cities[i]} style = {styles.cityName}>{cities[i]}</Text>
</View>
)
setData(data)
setI(i => i + 1)
}
}
useEffect(()=>{}, [i])
return(
<View style = {styles.appBackground}>
<View style = {styles.searchBar}>
<TextInput style = {styles.searchText} placeholder = "Search City"></TextInput>
<Text onPress={() => buttonPressed()} style = {styles.addButton}>+</Text>
</View>
{/* ScrollView can only have one view in it */}
<ScrollView style = {styles.weatherPanel} >
<View>
{data}
</View>
</ScrollView>
</View>
)
}
Here is my css file -
const styles = StyleSheet.create({
appBackground:{
flex: 1,
backgroundColor: 'black',
flexDirection: 'column'
},
searchBar:{
flex: 0.1,
flexDirection: 'row',
backgroundColor: 'white',
fontSize: 25
},
searchText:{
flex: 8,
borderWidth: 1
},
addButton:{
flex: 2,
textAlign: 'center',
fontSize: 40,
borderWidth: 1
},
// Place where all cities' weather are shown
weatherPanel:{
flex: 0.9,
flexDirection: 'column',
padding: 15
},
// Style for each city
weatherBoard:{
flex: 9,
backgroundColor: 'blue',
borderRadius: 10,
padding: 10
},
// Temorary styles -
date: {
fontSize: 20,
color: 'white'
},
temperature:{
fontSize: 30
},
cityName:{
fontSize: 30
}
})
| [
"Placing a style={{marginTop: 12}} should be fine\nlist.append(\n <View style={{marginTop: 12}}> \n ...\n ...\n ...\n </View>\n)\n\n",
"You can use ItemSeparatorComponent property for your list and provide any separator component you want.\nhttps://reactnative.dev/docs/virtualizedlist#itemseparatorcomponent\n"
] | [
1,
0
] | [] | [] | [
"react_native",
"reactjs"
] | stackoverflow_0074672270_react_native_reactjs.txt |
Q:
What's the difference between the two `SetState()` usages?
Just wondering if there is any difference between:
// == Add all picked idoes to the mix table
setState(() {
Future.forEach(result, (asset) async {
final video = await MixTableVideo.create(original: asset);
videos.add(video);
});
});
and:
// == Add all picked idoes to the mix table
Future.forEach(result, (asset) async {
final video = await MixTableVideo.create(original: asset);
videos.add(video);
});
setState(() {});
A:
In the first code snippet, the setState function is being called with a callback that runs the Future.forEach function, which iterates over the elements in the result list and adds each element to the videos list using the MixTableVideo.create function.
In the second code snippet, the Future.forEach function is run outside of the setState callback. This means that the videos list will be updated before the setState function is called, but the UI will not be updated until after setState is called.
A:
Before we can use state, we need to declare a default set of values for the initial state. This can be done by either creating a state object in the constructor or directly within the class.
A:
Finally I did this which fires a UI update at each video addition:
// == Add all picked videos to the mix table
Future.forEach(result, (asset) async {
final video = await MixTableVideo.create(original: asset);
setState(() {
videos.add(video);
});
});
| What's the difference between the two `SetState()` usages? | Just wondering if there is any difference between:
// == Add all picked idoes to the mix table
setState(() {
Future.forEach(result, (asset) async {
final video = await MixTableVideo.create(original: asset);
videos.add(video);
});
});
and:
// == Add all picked idoes to the mix table
Future.forEach(result, (asset) async {
final video = await MixTableVideo.create(original: asset);
videos.add(video);
});
setState(() {});
| [
"In the first code snippet, the setState function is being called with a callback that runs the Future.forEach function, which iterates over the elements in the result list and adds each element to the videos list using the MixTableVideo.create function.\nIn the second code snippet, the Future.forEach function is run outside of the setState callback. This means that the videos list will be updated before the setState function is called, but the UI will not be updated until after setState is called.\n",
"Before we can use state, we need to declare a default set of values for the initial state. This can be done by either creating a state object in the constructor or directly within the class.\n",
"Finally I did this which fires a UI update at each video addition:\n // == Add all picked videos to the mix table\n Future.forEach(result, (asset) async {\n final video = await MixTableVideo.create(original: asset);\n setState(() {\n videos.add(video);\n });\n });\n\n"
] | [
1,
1,
0
] | [] | [] | [
"dart",
"flutter",
"state"
] | stackoverflow_0074677432_dart_flutter_state.txt |
Q:
Regex that doesn't recognise a pattern
I want to make a regex that recognize some patterns and some not.
_*[a-zA-Z][a-zA-Z0-9_][^-]*.*(?<!_)
The sample of patterns that i want to recognize:
a100__version_2
_a100__version2
And the sample of patterns that i dont want to recognize:
100__version_2
a100__version2_
_100__version_2
a100--version-2
The regex works for all of them except this one:
a100--version-2
So I don't want to match the dashes.
I tried _*[a-zA-Z][a-zA-Z0-9_][^-]*.*(?<!_)
so the problem is at [^-]
A:
You could write the pattern like this, but [^-]* can also match newlines and spaces.
To not match newlines and spaces, and matching at least 2 characters:
^_*[a-zA-Z][a-zA-Z0-9_][^-\s]*$(?<!_)
Regex demo
Or matching only word characters, matching at least a single character repeating \w* zero or more times:
^_*[a-zA-Z]\w*$(?<!_)
^ Start of string
_* Match optional underscores
[a-zA-Z] Match a single char a-zA-Z
\w* Match optional word chars (Or [a-zA-Z0-9_]*)
$ End of string
(?<!_) Assert not _ to the left at the end of the string
Regex demo
A:
To exclude dashes from the regex, you can use the negative lookahead assertion (?!-) after the [^-] character class. This will make sure that the regex does not match any dashes after the [^-] character class.
Here's an updated version of the regex that excludes dashes:
[a-zA-Z]a-zA-Z0-9_.*(?<!)
This regex should match the patterns you want to recognize, and exclude the patterns you don't want to recognize.
Here are some examples of how this regex will work:
a100__version_2 // matches
_a100__version2 // matches
100__version_2 // does not match
a100__version2_ // does not match
_100__version_2 // does not match
a100--version-2 // does not match
| Regex that doesn't recognise a pattern | I want to make a regex that recognize some patterns and some not.
_*[a-zA-Z][a-zA-Z0-9_][^-]*.*(?<!_)
The sample of patterns that i want to recognize:
a100__version_2
_a100__version2
And the sample of patterns that i dont want to recognize:
100__version_2
a100__version2_
_100__version_2
a100--version-2
The regex works for all of them except this one:
a100--version-2
So I don't want to match the dashes.
I tried _*[a-zA-Z][a-zA-Z0-9_][^-]*.*(?<!_)
so the problem is at [^-]
| [
"You could write the pattern like this, but [^-]* can also match newlines and spaces.\nTo not match newlines and spaces, and matching at least 2 characters:\n^_*[a-zA-Z][a-zA-Z0-9_][^-\\s]*$(?<!_)\n\nRegex demo\nOr matching only word characters, matching at least a single character repeating \\w* zero or more times:\n^_*[a-zA-Z]\\w*$(?<!_)\n\n\n^ Start of string\n_* Match optional underscores\n[a-zA-Z] Match a single char a-zA-Z\n\\w* Match optional word chars (Or [a-zA-Z0-9_]*)\n$ End of string\n(?<!_) Assert not _ to the left at the end of the string\n\nRegex demo\n",
"To exclude dashes from the regex, you can use the negative lookahead assertion (?!-) after the [^-] character class. This will make sure that the regex does not match any dashes after the [^-] character class.\nHere's an updated version of the regex that excludes dashes:\n[a-zA-Z]a-zA-Z0-9_.*(?<!)\nThis regex should match the patterns you want to recognize, and exclude the patterns you don't want to recognize.\nHere are some examples of how this regex will work:\na100__version_2 // matches\n_a100__version2 // matches\n100__version_2 // does not match\na100__version2_ // does not match\n_100__version_2 // does not match\na100--version-2 // does not match\n\n"
] | [
1,
0
] | [] | [] | [
"regex"
] | stackoverflow_0074677589_regex.txt |
Q:
What is the purpose of Target in Get-ItemProperty of powershell
enter image description here
I am wondering what's the purpose of Target? If the type of Target is hash, how to set the key/value.
PS Set-ItemProperty -Path a.txt -Name Target -Value { "key1":"value1"}
At line:1 char:58
+ Set-ItemProperty -Path a.txt -Name Target -Value { "key1":"value1"}
+ ~~~~~~~~~
Unexpected token ':"value1"' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
A:
As for your post title:
What is the purpose of Target in Get-ItemProperty of powershell
Use Get-Member to find out.
(Get-ItemProperty -Path 'D:\temp\ZenMusic.mp3' |
Get-Member) -match 'Target' |
Format-List
# Results
<#
TypeName : System.IO.FileInfo
Name : Target
MemberType : CodeProperty
Definition : System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
Target{get=GetTarget;}
#>
As you can see, there is no setter for this property.
A:
The purpose of the Target parameter in the Set-ItemProperty cmdlet is to specify the path and file name of the item to be modified. It is typically used to set or modify the values of properties for a file, registry key, or other item.
In the example you provided, it looks like you are trying to set the Target property to a hash table with the key "key1" and the value "value1". However, the syntax for defining a hash table in PowerShell is incorrect in the example.
To set the Target property to a hash table with the key "key1" and the value "value1", you would use the following syntax:
Set-ItemProperty -Path a.txt -Name Target -Value @{ "key1" = "value1" }
Alternatively, you could use the following syntax to define the hash table inline:
Set-ItemProperty -Path a.txt -Name Target -Value @{ "key1" = "value1"; "key2" = "value2" }
In this syntax, the keys and values of the hash table are separated by the equals sign (=), and the key-value pairs are separated by semicolons (;).
A:
There is a target property for symlinks that's just a string, but it can't be set with set-itemproperty (Set accessor is unavailable).
New-Item -Path c -ItemType SymbolicLink -Value c:\ # elevated prompt
get-item c | % target | % gettype
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
get-itemproperty -path c -name target
target : {C:\}
PSPath : Microsoft.PowerShell.Core\FileSystem::C:\Users\admin\foo\c
PSParentPath : Microsoft.PowerShell.Core\FileSystem::C:\Users\admin\foo
PSChildName : c
PSDrive : C
PSProvider : Microsoft.PowerShell.Core\FileSystem
Set-ItemProperty -Path c -Name Target -Value c:\users
Set-ItemProperty : Set accessor for property "Target" is unavailable.
At line:1 char:1
+ Set-ItemProperty -Path c -Name Target -Value c:\users
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Set-ItemProperty], SetValueException
+ FullyQualifiedErrorId : SetWithoutSetterFromCodeProperty,Microsoft.PowerShell.Commands.SetItemPropertyCommand
| What is the purpose of Target in Get-ItemProperty of powershell | enter image description here
I am wondering what's the purpose of Target? If the type of Target is hash, how to set the key/value.
PS Set-ItemProperty -Path a.txt -Name Target -Value { "key1":"value1"}
At line:1 char:58
+ Set-ItemProperty -Path a.txt -Name Target -Value { "key1":"value1"}
+ ~~~~~~~~~
Unexpected token ':"value1"' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
| [
"As for your post title:\n\nWhat is the purpose of Target in Get-ItemProperty of powershell\n\nUse Get-Member to find out.\n(Get-ItemProperty -Path 'D:\\temp\\ZenMusic.mp3' | \nGet-Member) -match 'Target' | \nFormat-List\n\n# Results\n<#\nTypeName : System.IO.FileInfo\nName : Target\nMemberType : CodeProperty\nDefinition : System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] \n Target{get=GetTarget;}\n#>\n\nAs you can see, there is no setter for this property.\n",
"The purpose of the Target parameter in the Set-ItemProperty cmdlet is to specify the path and file name of the item to be modified. It is typically used to set or modify the values of properties for a file, registry key, or other item.\nIn the example you provided, it looks like you are trying to set the Target property to a hash table with the key \"key1\" and the value \"value1\". However, the syntax for defining a hash table in PowerShell is incorrect in the example.\nTo set the Target property to a hash table with the key \"key1\" and the value \"value1\", you would use the following syntax:\nSet-ItemProperty -Path a.txt -Name Target -Value @{ \"key1\" = \"value1\" }\n\nAlternatively, you could use the following syntax to define the hash table inline:\nSet-ItemProperty -Path a.txt -Name Target -Value @{ \"key1\" = \"value1\"; \"key2\" = \"value2\" }\n\nIn this syntax, the keys and values of the hash table are separated by the equals sign (=), and the key-value pairs are separated by semicolons (;).\n",
"There is a target property for symlinks that's just a string, but it can't be set with set-itemproperty (Set accessor is unavailable).\nNew-Item -Path c -ItemType SymbolicLink -Value c:\\ # elevated prompt\n\n\nget-item c | % target | % gettype\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True String System.Object\n\n\nget-itemproperty -path c -name target\n\ntarget : {C:\\}\nPSPath : Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\admin\\foo\\c\nPSParentPath : Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\admin\\foo\nPSChildName : c\nPSDrive : C\nPSProvider : Microsoft.PowerShell.Core\\FileSystem\n\n\nSet-ItemProperty -Path c -Name Target -Value c:\\users\n\nSet-ItemProperty : Set accessor for property \"Target\" is unavailable.\nAt line:1 char:1\n+ Set-ItemProperty -Path c -Name Target -Value c:\\users\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n + CategoryInfo : NotSpecified: (:) [Set-ItemProperty], SetValueException\n + FullyQualifiedErrorId : SetWithoutSetterFromCodeProperty,Microsoft.PowerShell.Commands.SetItemPropertyCommand\n\n"
] | [
0,
0,
0
] | [] | [] | [
"file",
"powershell"
] | stackoverflow_0074670352_file_powershell.txt |
Q:
How to run useQueries only after clicking a button in react-query?
export const useDeleteArticles = ({ ids, onSuccess }) => {
const queryResult = useQueries(
ids.map(id => ({
queryKey: ["article-delete", id],
queryFn: () => articlesApi.destroy(id),
}))
);
const isLoading = queryResult.some(result => result.isLoading);
if (!isLoading) {
onSuccess();
}
return { isLoading, queryResult };
};
This customHook will simply delete some articles.
I tried to use enabled with a state as following.
export const useDeleteArticles = ({ ids, onSuccess, enabled }) => {
const queryResult = useQueries(
ids.map(id => ({
queryKey: ["article-delete", id],
queryFn: () => articlesApi.destroy(id),
enabled,
}))
);
const isLoading = queryResult.some(result => result.isLoading);
if (!isLoading) {
onSuccess();
}
return { isLoading, queryResult };
};
const [enabled, setEnabled] = useState(false);
useDeleteArticles({ ids, onSuccess: refetch, enabled });
enabled && setEnabled(false); //to avoid api call after deleting the articles
const handleArticleDelete = () => { //this function will invoke onClick button
setEnabled(true);
};
But this not making the api call.
could anyone help me to implement this in correct way.
Thank you.
A:
To use the enabled parameter in your useQueries hook, you need to pass it as a separate argument, not as part of the object that's passed to map. Here's how you can do that:
const queryResult = useQueries(
ids.map(id => ({
queryKey: ["article-delete", id],
queryFn: () => articlesApi.destroy(id),
})),
enabled
);
This way, the enabled parameter will be applied to all of the queries in the useQueries hook.
It's also important to note that enabled needs to be a boolean value (true or false), not a state variable. You can use the useState hook to create a boolean state variable, but you need to use the setEnabled function to update its value, not the setState function. Here's how you can do that:
const [enabled, setEnabled] = useState(false);
// To enable the queries:
setEnabled(true);
// To disable the queries:
setEnabled(false);
You can then pass the enabled variable as the second argument to the useQueries hook, as shown above.
| How to run useQueries only after clicking a button in react-query? | export const useDeleteArticles = ({ ids, onSuccess }) => {
const queryResult = useQueries(
ids.map(id => ({
queryKey: ["article-delete", id],
queryFn: () => articlesApi.destroy(id),
}))
);
const isLoading = queryResult.some(result => result.isLoading);
if (!isLoading) {
onSuccess();
}
return { isLoading, queryResult };
};
This customHook will simply delete some articles.
I tried to use enabled with a state as following.
export const useDeleteArticles = ({ ids, onSuccess, enabled }) => {
const queryResult = useQueries(
ids.map(id => ({
queryKey: ["article-delete", id],
queryFn: () => articlesApi.destroy(id),
enabled,
}))
);
const isLoading = queryResult.some(result => result.isLoading);
if (!isLoading) {
onSuccess();
}
return { isLoading, queryResult };
};
const [enabled, setEnabled] = useState(false);
useDeleteArticles({ ids, onSuccess: refetch, enabled });
enabled && setEnabled(false); //to avoid api call after deleting the articles
const handleArticleDelete = () => { //this function will invoke onClick button
setEnabled(true);
};
But this not making the api call.
could anyone help me to implement this in correct way.
Thank you.
| [
"To use the enabled parameter in your useQueries hook, you need to pass it as a separate argument, not as part of the object that's passed to map. Here's how you can do that:\nconst queryResult = useQueries(\n ids.map(id => ({\n queryKey: [\"article-delete\", id],\n queryFn: () => articlesApi.destroy(id),\n })),\n enabled\n);\n\nThis way, the enabled parameter will be applied to all of the queries in the useQueries hook.\nIt's also important to note that enabled needs to be a boolean value (true or false), not a state variable. You can use the useState hook to create a boolean state variable, but you need to use the setEnabled function to update its value, not the setState function. Here's how you can do that:\nconst [enabled, setEnabled] = useState(false);\n\n// To enable the queries:\nsetEnabled(true);\n\n// To disable the queries:\nsetEnabled(false);\n\nYou can then pass the enabled variable as the second argument to the useQueries hook, as shown above.\n"
] | [
0
] | [] | [] | [
"react_hooks",
"react_query",
"reactjs"
] | stackoverflow_0074677596_react_hooks_react_query_reactjs.txt |
Q:
Should numbers in scheme be quoted?
Should numbers in scheme be quoted?
In the following examples (tested in ikarus), it seems that quoting numbers does not matter while too much quoting creates problems.
> (+ '1 1)
2
> (+ '1 '1)
2
> (+ '1 ''1)
1
What is the standard way to use numbers (e.g. in the definition of a function body)? quoted or not quoted?
A:
Numbers in Scheme are self evaluating. That means they act in the same way if they are quoted or not.
If you enter (some 1) in DrRacket and start the Macro stepper and disable macro hiding the call will end up looking like:
(#%app call-with-values (lambda () (#%app some (quote 1))) print-values))
Thus Racket actually quotes the values that are self evaluating because their runtime doesn't support self evaluation in the core language / fully expanded program.
It might be that in some implementations a unquoted and a quoted number will be evaluated differently even if Racket threats them the same, however it would be surprising if it had any real impact.
Most programmers are lazy and would refrain from quoting self evaluating code. The exception would be as communication to the reader. Eg. in Common Lisp nil () and the quoted variants are all the same and could indeed used () everywhere, but many choose to use nil when the object is used as a boolean and '() if it is used as a literal list.
A:
R6RS's definition of quotation says so:
(quote <datum>) syntax
Syntax: <Datum> should be a syntactic datum.
Semantics: (quote <datum>) evaluates to the datum value represented by
<datum> (see section 4.3). This notation is used to include constants.
So it is correct to do '"aa" or '123 but I have never seen it, I would find it funny to read code quoting the numbers or other constants.
In older lisps, such as emacs lisp, it is the same (in emacs lisp the syntax is called sexp or S-Expression instead of datun). But the real origin of the quotation's meaning comes from McCarthy and described in A Micro-Manual for Lisp.
| Should numbers in scheme be quoted? | Should numbers in scheme be quoted?
In the following examples (tested in ikarus), it seems that quoting numbers does not matter while too much quoting creates problems.
> (+ '1 1)
2
> (+ '1 '1)
2
> (+ '1 ''1)
1
What is the standard way to use numbers (e.g. in the definition of a function body)? quoted or not quoted?
| [
"Numbers in Scheme are self evaluating. That means they act in the same way if they are quoted or not.\nIf you enter (some 1) in DrRacket and start the Macro stepper and disable macro hiding the call will end up looking like:\n(#%app call-with-values (lambda () (#%app some (quote 1))) print-values))\n\nThus Racket actually quotes the values that are self evaluating because their runtime doesn't support self evaluation in the core language / fully expanded program.\nIt might be that in some implementations a unquoted and a quoted number will be evaluated differently even if Racket threats them the same, however it would be surprising if it had any real impact.\nMost programmers are lazy and would refrain from quoting self evaluating code. The exception would be as communication to the reader. Eg. in Common Lisp nil () and the quoted variants are all the same and could indeed used () everywhere, but many choose to use nil when the object is used as a boolean and '() if it is used as a literal list.\n",
"R6RS's definition of quotation says so:\n\n(quote <datum>) syntax\nSyntax: <Datum> should be a syntactic datum.\nSemantics: (quote <datum>) evaluates to the datum value represented by\n<datum> (see section 4.3). This notation is used to include constants.\n\nSo it is correct to do '\"aa\" or '123 but I have never seen it, I would find it funny to read code quoting the numbers or other constants.\nIn older lisps, such as emacs lisp, it is the same (in emacs lisp the syntax is called sexp or S-Expression instead of datun). But the real origin of the quotation's meaning comes from McCarthy and described in A Micro-Manual for Lisp.\n"
] | [
2,
0
] | [] | [] | [
"scheme"
] | stackoverflow_0074587070_scheme.txt |
Q:
"Unable to locate Android SDK. " while running flutter doctor on windows 10
currently my andoid studio is in location
C:\Android\AndroidStudio
on console
C:\Users\aditya jain>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.2.0, on Microsoft Windows [Version 10.0.19043.985], locale en-IN)
[X] Android toolchain - develop for Android devices
X Unable to locate Android SDK.
Install Android Studio from: https://developer.android.com/studio/index.html
On first launch it will assist you in installing the Android SDK components.
(or visit https://flutter.dev/docs/get-started/install/windows#android-setup for detailed instructions).
If the Android SDK has been installed to a custom location, please use
`flutter config --android-sdk` to update to that location.
[√] Chrome - develop for the web
[√] Android Studio
[√] Connected device (2 available)
! Doctor found issues in 1 category.
my sdk location is
C:\Users\aditya jain\AppData\Local\Android\Sdk
1>i have installed Android sdk platform tools and Android sdk tools (obsoloete)
2>I only have a Local, Loacallow and Roaming File but not a Platforms file
, as i have seen many youtube videos ..they said to add to path platform file but i can't see any in my appdata folder in users(it is hidden by default).
https://www.youtube.com/watch?v=7GuGlATHYX8&t=195s
3> ran flutter config command for my sdk and got
C:\Users\aditya jain>flutter config --android-sdk flutter config --android-sdk \C:\Users\aditya jain\AppData\Local\Android\Sdk
Setting "android-sdk" value to "flutter".
You may need to restart any open editors for them to read new settings.
C:\Users\aditya jain>
Android SDK cannot be found by flutter
in this que there is an answer
to run
flutter config --android-sdk /path/to/android/sdk
flutter config --android-studio-dir /path/to/android/studio
but i don't know what i should for my sdk location ..i have less reputation so i can't comment there to ask there so here i am posting ques
also tried
C:\Users\aditya jain>flutter config --android-sdk <sdk-"C:\Users\aditya jain\AppData\Local\Android\Sdk">
The syntax of the command is incorrect.
C:\Users\aditya jain>flutter config --android-sdk <sdk-C:\Users\aditya jain\AppData\Local\Android\Sdk>
The syntax of the command is incorrect.
as is suggested in same que ans but getting this given above
(i know my path contain spaces ..i tried to put my android in downloads so that there will be no spaces but there also i get errors as below
C:\Users\aditya jain>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.2.0, on Microsoft Windows [Version 10.0.19043.985], locale en-IN)
[X] Android toolchain - develop for Android devices
X Unable to locate Android SDK.
Install Android Studio from: https://developer.android.com/studio/index.html
On first launch it will assist you in installing the Android SDK components.
(or visit https://flutter.dev/docs/get-started/install/windows#android-setup for detailed instructions).
If the Android SDK has been installed to a custom location, please use
`flutter config --android-sdk` to update to that location.
[√] Chrome - develop for the web
[!] Android Studio
X android-studio-dir = C:\Android\AndroidStudio
X Android Studio not found at C:\Android\AndroidStudio
[√] Connected device (2 available)
! Doctor found issues in 2 categories.
C:\Users\aditya jain>flutter config --android-studio-dir=C:\Users\aditya jain\Downloads\Android\AndroidStudio
Setting "android-studio-dir" value to "C:\Users\aditya".
You may need to restart any open editors for them to read new settings.
C:\Users\aditya jain>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.2.0, on Microsoft Windows [Version 10.0.19043.985], locale en-IN)
[X] Android toolchain - develop for Android devices
X Unable to locate Android SDK.
Install Android Studio from: https://developer.android.com/studio/index.html
On first launch it will assist you in installing the Android SDK components.
(or visit https://flutter.dev/docs/get-started/install/windows#android-setup for detailed instructions).
If the Android SDK has been installed to a custom location, please use
`flutter config --android-sdk` to update to that location.
[√] Chrome - develop for the web
[!] Android Studio
X android-studio-dir = C:\Users\aditya
X Android Studio not found at C:\Users\aditya
[√] Connected device (2 available)
! Doctor found issues in 2 categories.
C:\Users\aditya jain>
i can't rename ' aditya jain' folder to 'adityajain'...it takes space....pls help mee.
please help and thanks community!!
A:
If the path name has spaces, you can wrap the path with double quotes. This allows Windows to identify the path as a single String: "C:\Users\aditya jain\Downloads\Android\AndroidStudio"
A:
If you have already configured SDK path for Flutter (flutter config --android-sdk ) and yet not working than...
Install the platform-tools resolves the problem.
Go to the SDK Manager (top-right in the toolbar), then open SDK Tools, then check-mark ✅ Android-SDK Platform-Tools and apply the changes (As shown below).
For me this solution worked.
Enjoy...
Check image
| "Unable to locate Android SDK. " while running flutter doctor on windows 10 | currently my andoid studio is in location
C:\Android\AndroidStudio
on console
C:\Users\aditya jain>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.2.0, on Microsoft Windows [Version 10.0.19043.985], locale en-IN)
[X] Android toolchain - develop for Android devices
X Unable to locate Android SDK.
Install Android Studio from: https://developer.android.com/studio/index.html
On first launch it will assist you in installing the Android SDK components.
(or visit https://flutter.dev/docs/get-started/install/windows#android-setup for detailed instructions).
If the Android SDK has been installed to a custom location, please use
`flutter config --android-sdk` to update to that location.
[√] Chrome - develop for the web
[√] Android Studio
[√] Connected device (2 available)
! Doctor found issues in 1 category.
my sdk location is
C:\Users\aditya jain\AppData\Local\Android\Sdk
1>i have installed Android sdk platform tools and Android sdk tools (obsoloete)
2>I only have a Local, Loacallow and Roaming File but not a Platforms file
, as i have seen many youtube videos ..they said to add to path platform file but i can't see any in my appdata folder in users(it is hidden by default).
https://www.youtube.com/watch?v=7GuGlATHYX8&t=195s
3> ran flutter config command for my sdk and got
C:\Users\aditya jain>flutter config --android-sdk flutter config --android-sdk \C:\Users\aditya jain\AppData\Local\Android\Sdk
Setting "android-sdk" value to "flutter".
You may need to restart any open editors for them to read new settings.
C:\Users\aditya jain>
Android SDK cannot be found by flutter
in this que there is an answer
to run
flutter config --android-sdk /path/to/android/sdk
flutter config --android-studio-dir /path/to/android/studio
but i don't know what i should for my sdk location ..i have less reputation so i can't comment there to ask there so here i am posting ques
also tried
C:\Users\aditya jain>flutter config --android-sdk <sdk-"C:\Users\aditya jain\AppData\Local\Android\Sdk">
The syntax of the command is incorrect.
C:\Users\aditya jain>flutter config --android-sdk <sdk-C:\Users\aditya jain\AppData\Local\Android\Sdk>
The syntax of the command is incorrect.
as is suggested in same que ans but getting this given above
(i know my path contain spaces ..i tried to put my android in downloads so that there will be no spaces but there also i get errors as below
C:\Users\aditya jain>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.2.0, on Microsoft Windows [Version 10.0.19043.985], locale en-IN)
[X] Android toolchain - develop for Android devices
X Unable to locate Android SDK.
Install Android Studio from: https://developer.android.com/studio/index.html
On first launch it will assist you in installing the Android SDK components.
(or visit https://flutter.dev/docs/get-started/install/windows#android-setup for detailed instructions).
If the Android SDK has been installed to a custom location, please use
`flutter config --android-sdk` to update to that location.
[√] Chrome - develop for the web
[!] Android Studio
X android-studio-dir = C:\Android\AndroidStudio
X Android Studio not found at C:\Android\AndroidStudio
[√] Connected device (2 available)
! Doctor found issues in 2 categories.
C:\Users\aditya jain>flutter config --android-studio-dir=C:\Users\aditya jain\Downloads\Android\AndroidStudio
Setting "android-studio-dir" value to "C:\Users\aditya".
You may need to restart any open editors for them to read new settings.
C:\Users\aditya jain>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.2.0, on Microsoft Windows [Version 10.0.19043.985], locale en-IN)
[X] Android toolchain - develop for Android devices
X Unable to locate Android SDK.
Install Android Studio from: https://developer.android.com/studio/index.html
On first launch it will assist you in installing the Android SDK components.
(or visit https://flutter.dev/docs/get-started/install/windows#android-setup for detailed instructions).
If the Android SDK has been installed to a custom location, please use
`flutter config --android-sdk` to update to that location.
[√] Chrome - develop for the web
[!] Android Studio
X android-studio-dir = C:\Users\aditya
X Android Studio not found at C:\Users\aditya
[√] Connected device (2 available)
! Doctor found issues in 2 categories.
C:\Users\aditya jain>
i can't rename ' aditya jain' folder to 'adityajain'...it takes space....pls help mee.
please help and thanks community!!
| [
"If the path name has spaces, you can wrap the path with double quotes. This allows Windows to identify the path as a single String: \"C:\\Users\\aditya jain\\Downloads\\Android\\AndroidStudio\"\n",
"If you have already configured SDK path for Flutter (flutter config --android-sdk ) and yet not working than...\nInstall the platform-tools resolves the problem.\nGo to the SDK Manager (top-right in the toolbar), then open SDK Tools, then check-mark ✅ Android-SDK Platform-Tools and apply the changes (As shown below).\nFor me this solution worked.\nEnjoy...\nCheck image\n"
] | [
0,
0
] | [] | [] | [
"android_studio",
"flutter"
] | stackoverflow_0067649681_android_studio_flutter.txt |
Q:
Call function in dynamic library in assembly?
I'm probably way off but this is what I did, I'm also trying to get this to work from linux to cross compile to mac
I did a hello world kind of thing in C with write, malloc and realloc. I notice in the assembly it used adrp but I couldn't figure out how to use that instruction. I kept getting a label must be GOT relative error. I was hoping I could use the section as the label but ended up writing a label which didn't help.
Essentially the write c stub function uses adrp, then ldr [x16, #24]. Since I couldn't figure out adrp I used mov and movk. It seemed to do the same thing but I got a segment fault when I execute it. Stepping through lldb it appears that the code did what I thought however the GOT section wasn't replaced at runtime like I thought it would. Objdump leaves me to believe I named the section right. I don't know if figuring out adrp is all I need to get this to work or if I did everything completely wrong
.global _main
.align 2
_main:
mov X0, #1
adr X1, hello
mov X2, #13
mov X16, #4
svc 0
mov x16, 16384
movk x16, 0x1, lsl 32
ldr x16, [x16, #24]
#adrp x16, HowGOTLabel
#ldr x16, [x16, #24]
br x16
mov X0, #0
mov X16, #1
svc 0
hello: .ascii "Hello\n"
.section __DATA_CONST,__got
.align 3
HowGOTLabel:
.word 0
.word 0x80100000
.word 1
.word 0x80100000
.word 2
.word 0x80100000
.word 3
.word 0x80000000
A:
Darwin on arm64 forces all userland binaries to use ASLR, so you cannot use movz/movk for PC-relative addresses.
The reason why your adrp doesn't work is because it can only refer to 0x1000-byte aligned locations. For more granular targeting you'd use adr, but there you have the issue of being limited to ±1MB of the instruction. For Linux targets, the compiler seems to be more lenient here, but for Darwin targets, adr can only really be used for locations within the same section, and you're trying to refer to __DATA_CONST.__got from __TEXT.__text.
So how can you fix this? You use @PAGE and @PAGEOFF:
adrp x16, HowGOTLabel@PAGE
add x16, x16, HowGOTLabel@PAGEOFF
You can even have this be fixed up to adr+nop at link-time if the target is in range, with some asm directives:
Lloh0:
adrp x16, HowGOTLabel@PAGE
Lloh1:
add x16, x16, HowGOTLabel@PAGEOFF
.loh AdrpAdd Lloh0, Lloh1
You can also do this with AdrpLdr if the second instruction is ldr rather than add.
But once you fix that, you've got two other issues in your code:
You use br x16. This means you won't return to the callsite. Use blr for function calls.
You don't actually have any imports? It's not clear how you think this would end up calling library functions, but really you can just do it like this:
bl _printf
And the compiler and linker will take care of imports.
| Call function in dynamic library in assembly? | I'm probably way off but this is what I did, I'm also trying to get this to work from linux to cross compile to mac
I did a hello world kind of thing in C with write, malloc and realloc. I notice in the assembly it used adrp but I couldn't figure out how to use that instruction. I kept getting a label must be GOT relative error. I was hoping I could use the section as the label but ended up writing a label which didn't help.
Essentially the write c stub function uses adrp, then ldr [x16, #24]. Since I couldn't figure out adrp I used mov and movk. It seemed to do the same thing but I got a segment fault when I execute it. Stepping through lldb it appears that the code did what I thought however the GOT section wasn't replaced at runtime like I thought it would. Objdump leaves me to believe I named the section right. I don't know if figuring out adrp is all I need to get this to work or if I did everything completely wrong
.global _main
.align 2
_main:
mov X0, #1
adr X1, hello
mov X2, #13
mov X16, #4
svc 0
mov x16, 16384
movk x16, 0x1, lsl 32
ldr x16, [x16, #24]
#adrp x16, HowGOTLabel
#ldr x16, [x16, #24]
br x16
mov X0, #0
mov X16, #1
svc 0
hello: .ascii "Hello\n"
.section __DATA_CONST,__got
.align 3
HowGOTLabel:
.word 0
.word 0x80100000
.word 1
.word 0x80100000
.word 2
.word 0x80100000
.word 3
.word 0x80000000
| [
"Darwin on arm64 forces all userland binaries to use ASLR, so you cannot use movz/movk for PC-relative addresses.\nThe reason why your adrp doesn't work is because it can only refer to 0x1000-byte aligned locations. For more granular targeting you'd use adr, but there you have the issue of being limited to ±1MB of the instruction. For Linux targets, the compiler seems to be more lenient here, but for Darwin targets, adr can only really be used for locations within the same section, and you're trying to refer to __DATA_CONST.__got from __TEXT.__text.\nSo how can you fix this? You use @PAGE and @PAGEOFF:\nadrp x16, HowGOTLabel@PAGE\nadd x16, x16, HowGOTLabel@PAGEOFF\n\nYou can even have this be fixed up to adr+nop at link-time if the target is in range, with some asm directives:\nLloh0:\n adrp x16, HowGOTLabel@PAGE\nLloh1:\n add x16, x16, HowGOTLabel@PAGEOFF\n.loh AdrpAdd Lloh0, Lloh1\n\nYou can also do this with AdrpLdr if the second instruction is ldr rather than add.\nBut once you fix that, you've got two other issues in your code:\n\nYou use br x16. This means you won't return to the callsite. Use blr for function calls.\n\nYou don't actually have any imports? It's not clear how you think this would end up calling library functions, but really you can just do it like this:\nbl _printf\n\nAnd the compiler and linker will take care of imports.\n\n\n"
] | [
0
] | [] | [] | [
"apple_m1",
"arm64",
"assembly",
"macos",
"shared_libraries"
] | stackoverflow_0074672825_apple_m1_arm64_assembly_macos_shared_libraries.txt |
Q:
New Relic with graalvm
I am developing spring boot 3 app with native graalvm support.
For that I want to integrate Newrelic with it.
Any idea on integrating new Relic with graalvm.
I tried to add new Relic agent by using --jvmargs option.
A:
It is possible to integrate New Relic with a Spring Boot 3 app that has native GraalVM support. You can add the New Relic agent to your app by using the --jvmargs option when starting the app. This will allow the agent to be loaded and initialized when the app is launched, and will enable New Relic to monitor and collect data on the app's performance.
In order to use the --jvmargs option, you will need to include the newrelic.jar file in your app's classpath, and specify the location of the newrelic.yml file that contains your New Relic license key and other configuration settings. You can then pass the --jvmargs option to the java command when starting your app, along with the necessary arguments to enable the New Relic agent.
Here is an example of how this might look:
java -cp newrelic.jar:<other classpath entries> \
-Dnewrelic.config.file=<path to newrelic.yml> \
--jvmargs '-javaagent:newrelic.jar' \
com.example.MyApp
In this example, we are adding the newrelic.jar file to the classpath, setting the location of the newrelic.yml file, and passing the -javaagent argument to the --jvmargs option to enable the New Relic agent.
Once the New Relic agent is added and configured, it will automatically start collecting data on the performance of your app, and you can view this data in the New Relic UI. This will allow you to monitor the performance of your app and identify any potential performance issues.
| New Relic with graalvm | I am developing spring boot 3 app with native graalvm support.
For that I want to integrate Newrelic with it.
Any idea on integrating new Relic with graalvm.
I tried to add new Relic agent by using --jvmargs option.
| [
"It is possible to integrate New Relic with a Spring Boot 3 app that has native GraalVM support. You can add the New Relic agent to your app by using the --jvmargs option when starting the app. This will allow the agent to be loaded and initialized when the app is launched, and will enable New Relic to monitor and collect data on the app's performance.\nIn order to use the --jvmargs option, you will need to include the newrelic.jar file in your app's classpath, and specify the location of the newrelic.yml file that contains your New Relic license key and other configuration settings. You can then pass the --jvmargs option to the java command when starting your app, along with the necessary arguments to enable the New Relic agent.\nHere is an example of how this might look:\njava -cp newrelic.jar:<other classpath entries> \\\n -Dnewrelic.config.file=<path to newrelic.yml> \\\n --jvmargs '-javaagent:newrelic.jar' \\\n com.example.MyApp\n\nIn this example, we are adding the newrelic.jar file to the classpath, setting the location of the newrelic.yml file, and passing the -javaagent argument to the --jvmargs option to enable the New Relic agent.\nOnce the New Relic agent is added and configured, it will automatically start collecting data on the performance of your app, and you can view this data in the New Relic UI. This will allow you to monitor the performance of your app and identify any potential performance issues.\n"
] | [
0
] | [] | [] | [
"graalvm_native_image",
"newrelic"
] | stackoverflow_0074677650_graalvm_native_image_newrelic.txt |
Q:
Can we avoid repeating table joins by views in sql?
I have some queries, all of them work on the same table joins. Their difference is in the where clause. I want not to repeat table joins for each query. So I created a view and wrote table joins in it and used it for each query. My question is: does using views really avoid repeating table joins? Or it is the same as writing a function and putting the table joins in it and then calling it for each query? I am using laravel.
I tried to avoid repeating table joins by creating a view.
A:
According to wiki, a view is the result set of a stored query on the data, which the database users can query just as they would in a persistent database collection object.
Therefore, by calling a view in a code, you're executing a stored query.
| Can we avoid repeating table joins by views in sql? | I have some queries, all of them work on the same table joins. Their difference is in the where clause. I want not to repeat table joins for each query. So I created a view and wrote table joins in it and used it for each query. My question is: does using views really avoid repeating table joins? Or it is the same as writing a function and putting the table joins in it and then calling it for each query? I am using laravel.
I tried to avoid repeating table joins by creating a view.
| [
"According to wiki, a view is the result set of a stored query on the data, which the database users can query just as they would in a persistent database collection object.\nTherefore, by calling a view in a code, you're executing a stored query.\n"
] | [
0
] | [] | [] | [
"laravel",
"mysql",
"php",
"sql",
"view"
] | stackoverflow_0074677631_laravel_mysql_php_sql_view.txt |
Q:
Opencv (JS) select finger area from image
I'm coding ionic app that allow user to take finger photo and upload to server.
My objective is I would like to find any solution to select area of finger and cut it of from background (please see image below).
I found that opencv can do that (https://gigadom.in/2011/10/) but I would like to find the way to to with javascript or NodeJS.
Any idea for this.
A:
OpenCV has a JS library: https://docs.opencv.org/3.4/d0/d84/tutorial_js_usage.html
This means you can take many of the python implementations of this logic and port it to JS.
Technique 1 to remove the background using color thresholding: How to remove the background of an object using OpenCV (Python)
Technique 2 to remove background using contours:
Removing Background Around Contour
Your use case may require a combination of these techniques and some fine tuning.
A:
Background removal is a generic concept in computer vision, usually associated with removing areas that are not moving.
Perhaps what you are looking for is something related to object detection, and as a result, removing everything that is not the detected object.
Try to research something like that: "Finger Object Detection"
Or if the application is in a controlled location, perhaps the other solution discussed here, with the solution of removing everything that is not of a certain color, united with morphology, will have some result.
Anyway, I believe this solution should be applied on the server side. Applying this solution on the frontend will require a lot of performance-related care.
Anyway², look at how opencv's background removal works on a moving video.
App Link: https://online.opencvflow.org/
Project Link: https://opencvflow.org/
| Opencv (JS) select finger area from image | I'm coding ionic app that allow user to take finger photo and upload to server.
My objective is I would like to find any solution to select area of finger and cut it of from background (please see image below).
I found that opencv can do that (https://gigadom.in/2011/10/) but I would like to find the way to to with javascript or NodeJS.
Any idea for this.
| [
"OpenCV has a JS library: https://docs.opencv.org/3.4/d0/d84/tutorial_js_usage.html\nThis means you can take many of the python implementations of this logic and port it to JS.\nTechnique 1 to remove the background using color thresholding: How to remove the background of an object using OpenCV (Python)\nTechnique 2 to remove background using contours:\nRemoving Background Around Contour\nYour use case may require a combination of these techniques and some fine tuning.\n",
"Background removal is a generic concept in computer vision, usually associated with removing areas that are not moving.\nPerhaps what you are looking for is something related to object detection, and as a result, removing everything that is not the detected object.\nTry to research something like that: \"Finger Object Detection\"\nOr if the application is in a controlled location, perhaps the other solution discussed here, with the solution of removing everything that is not of a certain color, united with morphology, will have some result.\nAnyway, I believe this solution should be applied on the server side. Applying this solution on the frontend will require a lot of performance-related care.\nAnyway², look at how opencv's background removal works on a moving video.\n\nApp Link: https://online.opencvflow.org/\nProject Link: https://opencvflow.org/\n"
] | [
1,
0
] | [] | [] | [
"opencv"
] | stackoverflow_0068564786_opencv.txt |
Q:
Return array in construct method in php
I am trying to create a homepage where I will output question with its answers
I have a question which has 3 answers, but when I create the object it only return 1 answer, whereas I need it to return the array of answers. Do I need to create additional class answers in order to do that?
My code:
include("connect-database.inc.php");
$question_query = "SELECT
questions.questionID,
answers.answer,
questions.question,
questions.feedback,
questions.mark,
questions.questionTypeID
FROM questions
JOIN answers ON questions.questionID=answers.questionID";
$questionList=array();
$answerList = array();
try {
$mysqliResult = $link->query($question_query);
while($var=$mysqliResult->fetch_assoc()){
$questionList[$var['questionID']]=new questions($var['question'],$var['feedback'], $var['mark'], $var['questionTypeID'], $var['answer']);
}
} catch (Exception $e) {
echo "MySQLi Error Code: " . $e->getCode() . "<br />";
echo "Exception Msg: " . $e->getMessage();
exit();
}
var_dump($questionList);
class questions {
public function __construct($question, $feedback, $mark, $questionTypeID, $answerList){
$this->question = $question;
$this->feedback = $feedback;
$this->mark = $mark;
$this->questionTypeID = $questionTypeID;
$this->answers($answerList);
}
public function answers($answers) {
$answers = array();
$this->answers = $answers;
}
}
I have tried to change to query and retrieve data by answerID, but then I get the same question 3 times. Can anybody help with the solution?
A:
You can separate new Question instance creating from add new answers to existing Question like:
$question_query = "SELECT
questions.questionID,
answers.answer,
questions.question,
questions.feedback,
questions.mark,
questions.questionTypeID
FROM questions
JOIN answers ON questions.questionID=answers.questionID";
$questionList=array();
$answerList = array();
try {
$mysqliResult = $link->query($question_query);
while($var=$mysqliResult->fetch_assoc()){
if (!isset($questionList[$var['questionID']])) {
$questionList[$var['questionID']]= new Question(
$var['question'],
$var['feedback'],
$var['mark'],
$var['questionTypeID']
);
}
$questionList[$var['questionID']]->addAnswer($var['answer']);
}
} catch (Exception $e) {
echo "MySQLi Error Code: " . $e->getCode() . "<br />";
echo "Exception Msg: " . $e->getMessage();
exit();
}
var_dump($questionList);
class Question {
public function __construct($question, $feedback, $mark, $questionTypeID, $answerList = []){
$this->question = $question;
$this->feedback = $feedback;
$this->mark = $mark;
$this->questionTypeID = $questionTypeID;
$this->setAnswers($answerList);
}
public function addAnswer($answer) {
$this->answers[] = $answer;
}
public function setAnswers($answers) {
$this->answers = $answers;
}
}
PHPize - online PHP environment
A:
Just use seperate quieries for both question and answer.
If you want to use group by answerID, of course it will return result with multiple answer with same question. mysql return result as flat. Just save the value inside an array as such
$array[questionID]['answer'][] = $var['answer'];
Then you build the class object by looping through each questionID.
| Return array in construct method in php | I am trying to create a homepage where I will output question with its answers
I have a question which has 3 answers, but when I create the object it only return 1 answer, whereas I need it to return the array of answers. Do I need to create additional class answers in order to do that?
My code:
include("connect-database.inc.php");
$question_query = "SELECT
questions.questionID,
answers.answer,
questions.question,
questions.feedback,
questions.mark,
questions.questionTypeID
FROM questions
JOIN answers ON questions.questionID=answers.questionID";
$questionList=array();
$answerList = array();
try {
$mysqliResult = $link->query($question_query);
while($var=$mysqliResult->fetch_assoc()){
$questionList[$var['questionID']]=new questions($var['question'],$var['feedback'], $var['mark'], $var['questionTypeID'], $var['answer']);
}
} catch (Exception $e) {
echo "MySQLi Error Code: " . $e->getCode() . "<br />";
echo "Exception Msg: " . $e->getMessage();
exit();
}
var_dump($questionList);
class questions {
public function __construct($question, $feedback, $mark, $questionTypeID, $answerList){
$this->question = $question;
$this->feedback = $feedback;
$this->mark = $mark;
$this->questionTypeID = $questionTypeID;
$this->answers($answerList);
}
public function answers($answers) {
$answers = array();
$this->answers = $answers;
}
}
I have tried to change to query and retrieve data by answerID, but then I get the same question 3 times. Can anybody help with the solution?
| [
"You can separate new Question instance creating from add new answers to existing Question like:\n$question_query = \"SELECT\n questions.questionID,\n answers.answer,\n questions.question,\n questions.feedback,\n questions.mark,\n questions.questionTypeID \n FROM questions \n JOIN answers ON questions.questionID=answers.questionID\";\n \n $questionList=array();\n $answerList = array();\n try {\n $mysqliResult = $link->query($question_query);\n while($var=$mysqliResult->fetch_assoc()){\n if (!isset($questionList[$var['questionID']])) {\n $questionList[$var['questionID']]= new Question(\n $var['question'],\n $var['feedback'], \n $var['mark'], \n $var['questionTypeID']\n );\n }\n $questionList[$var['questionID']]->addAnswer($var['answer']);\n }\n } catch (Exception $e) { \n echo \"MySQLi Error Code: \" . $e->getCode() . \"<br />\";\n echo \"Exception Msg: \" . $e->getMessage();\n exit();\n } \n var_dump($questionList);\n\n\n class Question {\n\n public function __construct($question, $feedback, $mark, $questionTypeID, $answerList = []){\n $this->question = $question;\n $this->feedback = $feedback;\n $this->mark = $mark;\n $this->questionTypeID = $questionTypeID;\n $this->setAnswers($answerList);\n }\n \n public function addAnswer($answer) {\n $this->answers[] = $answer;\n }\n \n public function setAnswers($answers) {\n $this->answers = $answers;\n } \n }\n\nPHPize - online PHP environment\n",
"Just use seperate quieries for both question and answer.\nIf you want to use group by answerID, of course it will return result with multiple answer with same question. mysql return result as flat. Just save the value inside an array as such\n$array[questionID]['answer'][] = $var['answer'];\nThen you build the class object by looping through each questionID.\n"
] | [
0,
0
] | [] | [] | [
"arrays",
"class",
"constructor",
"php"
] | stackoverflow_0074677037_arrays_class_constructor_php.txt |
Q:
How to make a form for class A that depends on class B
In Ruby on Rails if I have class/model A that reference class/model B.
Let us say that (just examples)
class B
@attr_acessor :name
end
class A
@attr_accessor :B
@attr_accessor :amount
end
How do I make a form such that when creating A, I get a list of all potential B's and so the references is made for me on A object creation? It would be brilliant if I could search in the list as well.
The classes are just for an abstract example.
A:
If what you mean are actual database backed models then you do it by using assocations and the collection helpers:
class Foo < ApplicationRecord
has_many :bars
end
class Bar < ApplicationRecord
belongs_to :foo
end
This creates a Foo#bar_ids getter and a Foo#bar_ids= setter.
<%= form_with(model: @foo) do |form| %>
<%= form.label(:bar_ids, "Bars") %>
<%= form.collection_checkboxes(:bar_ids, @bars, :id, :label_method) %>
<% end %>
class FoosController < ApplicationController
def new
@foo = Foo.new
@bars = Bar.all
end
def create
@foo = Foo.new(foo_params)
if @foo.save
redirect_to @foo
else
@bars = Bar.all
render :new
end
end
private
def foo_params
params.require(:foo)
.permit(:a, :b, bar_ids: [])
end
end
It would be brilliant if I could search in the list as well.
You should learn how to walk before you do your first marathon.
| How to make a form for class A that depends on class B | In Ruby on Rails if I have class/model A that reference class/model B.
Let us say that (just examples)
class B
@attr_acessor :name
end
class A
@attr_accessor :B
@attr_accessor :amount
end
How do I make a form such that when creating A, I get a list of all potential B's and so the references is made for me on A object creation? It would be brilliant if I could search in the list as well.
The classes are just for an abstract example.
| [
"If what you mean are actual database backed models then you do it by using assocations and the collection helpers:\nclass Foo < ApplicationRecord\n has_many :bars\nend\n\nclass Bar < ApplicationRecord\n belongs_to :foo\nend\n\nThis creates a Foo#bar_ids getter and a Foo#bar_ids= setter.\n<%= form_with(model: @foo) do |form| %>\n <%= form.label(:bar_ids, \"Bars\") %>\n <%= form.collection_checkboxes(:bar_ids, @bars, :id, :label_method) %>\n<% end %>\n\nclass FoosController < ApplicationController\n def new \n @foo = Foo.new\n @bars = Bar.all\n end\n\n def create\n @foo = Foo.new(foo_params)\n if @foo.save\n redirect_to @foo\n else\n @bars = Bar.all\n render :new\n end\n end\n\n private \n\n def foo_params\n params.require(:foo)\n .permit(:a, :b, bar_ids: [])\n end\nend \n\n\nIt would be brilliant if I could search in the list as well.\n\nYou should learn how to walk before you do your first marathon.\n"
] | [
0
] | [] | [] | [
"ruby_on_rails"
] | stackoverflow_0074675218_ruby_on_rails.txt |
Q:
I can't convert .duration or .currentTime to MM:SS in java script
since I don't know JavaScript I downloaded an audio player and changed the html and CSS but the audio player shows audio duration in seconds and; I tried to look for results in google but that did not work as well, I even tried to copy code from other audio players but it did not work. I would be happy if anyone help me.
thanks...
$(document).ready(function() {
var timeDrag = false; /* Drag status */
var isPlaying = false;
var theSound = $("#firstTrack");
var allIcons = $("i");
var isLoaded = false;
theSound.on("timeupdate", function() {
var currentPos = theSound[0].currentTime; //Get currenttime
var maxduration = theSound[0].duration; //Get video duration
var percentage = 100 * currentPos / maxduration; //in %
$('.timeBar').css('width', percentage + '%');
$("#getTime").html(Math.floor(theSound[0].duration));
$('#goTime').html(Math.floor(theSound[0].currentTime));
});
$("#playIt").click(function(event) {
// run once.
if (!isLoaded) {
theSound.trigger('load');
setTimeout(startBuffer, 500);
isLoaded = true;
}
// toggle play/pause
if (!isPlaying) {
theSound.trigger('play');
$("#playIt").find(allIcons).removeClass("fa-play");
$("#playIt").find(allIcons).addClass("fa-pause");
isPlaying = true;
} else {
theSound.trigger('pause');
$("#playIt").find(allIcons).removeClass("fa-pause");
$("#playIt").find(allIcons).addClass("fa-play");
isPlaying = false;
}
});
$("#stepFive").click(function() {
var currentPos = theSound[0].currentTime + 5;
theSound[0].currentTime = currentPos;
});
$("#stepFiveback").click(function() {
var currentPos = theSound[0].currentTime - 5;
theSound[0].currentTime = currentPos;
});
$('.progressBar').mousedown(function(e) {
timeDrag = true;
updatebar(e.pageX);
});
$(document).mouseup(function(e) {
if (timeDrag) {
timeDrag = false;
updatebar(e.pageX);
}
});
$(document).mousemove(function(e) {
if (timeDrag) {
updatebar(e.pageX);
}
});
//update Progress Bar control
var updatebar = function(x) {
var progress = $('.progressBar');
var maxduration = theSound[0].duration; //Video duraiton
var position = x - progress.offset().left; //Click pos
var percentage = 100 * position / progress.width();
//Check within range
if (percentage > 100) {
percentage = 100;
}
if (percentage < 0) {
percentage = 0;
}
//Update progress bar and video currenttime
$('.timeBar').css('width', percentage + '%');
theSound[0].currentTime = maxduration * percentage / 100;
};
//loop to get HTML5 video buffered data
var startBuffer = function() {
var maxduration = $("#firstTrack")[0].duration;
var currentBuffer = $("#firstTrack")[0].buffered.end(0);
var percentage = 100 * currentBuffer / maxduration;
$('.bufferBar').css('width', percentage + '%');
//re-loop if not entierely buffered
if (currentBuffer < maxduration) {
setTimeout(startBuffer, 500);
}
};
});
@charset "utf-8";
/*head*/
html,
html * {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: #1e1f1f;
max-height: 100vh;
/* change here */
}
/* -- */
.noPad {
padding: 0;
}
.playBar {
transition: all 0.5s ease;
height: 10px;
background-color: rgba(186, 44, 44, 0.59);
/*border: 1.5px;*/
/*border-color: black;*/
/*border-style: inset;*/
opacity: 0.85;
width: 0;
}
#audioCtrl>div {
margin: 0;
padding: 0;
}
.progressBar {
position: relative;
width: 100%;
height: .4em;
backgroud-color: #474848;
color: #474848;
scroll-behavior: smooth;
border: solid;
border-color: #474848;
border-width: 1px;
border-radius: 5px;
}
.timeBar {
transition: all 0.5s ease;
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background-color: #8c8d8e;
border-radius: 5px;
}
.bufferBar {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background-color: #474949;
opacity: 0.5;
border-radius: 5px;
}
/* -- */
.row {
/* background-color: #535252; */
border-radius: 10px;
}
.img-container img {
margin-top: 10em;
border-radius: 15px;
height: 22em;
}
.navigation {
display: flex;
align-items: center;
justify-content: center;
}
.info1 {}
.title {
font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, "sans-serif";
font-size: 1.7em;
margin: 0;
padding-bottom: .4em;
margin-left: .2em;
color: #f1f1f1;
}
.time-btn {
float: right;
margin-top: .3em;
background-color: #1E1F1F;
color: aliceblue;
border: 0;
font-family: Constantia, "Lucida Bright", "DejaVu Serif", Georgia, "serif";
font-size: 1em;
margin-right: .3em;
}
.time-btn2 {
margin-top: .3em;
background-color: #1E1F1F;
color: aliceblue;
border: 0;
font-family: Constantia, "Lucida Bright", "DejaVu Serif", Georgia, "serif";
font-size: 1em;
margin-left: .2em;
}
.btn {
background-color: #1e1f1f;
color: #D7D7D7;
border: 0;
font-size: 2.2em;
padding: .3em .7em;
}
.btn-big {
color: #FFFFFF;
font-size: 2.4em;
}
.btn:focus {
border: 0;
}
.scrollformore {
color: #FFFFFF;
font-family: "Gill Sans", "Gill Sans MT", "Myriad Pro", "DejaVu Sans Condensed", Helvetica, Arial, "sans-serif";
font-size: 1em;
margin-top: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<title>audio_player_2</title>
<link rel="stylesheet" href="assets/css/styles.css">
<link rel="stylesheet" href="assets/css/aistyles.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.min.css" />
</head>
<body>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="simple_player.js"></script>
<div class="container-fluid"><audio id="firstTrack" width="100%" preload="none">
<source src="https://www.bensound.com/bensound-music/bensound-ukulele.mp3" type="audio/mpeg" />
</audio>
<div class="img-container"><img src="https://www.bensound.com/bensound-img/ukulele.jpg" alt="cover"></div>
<h2 class="title info1">Ukulele</h2>
<div class="row" id="audioCtrl">
<div class="col-xs-3 progressBar">
<div class="bufferBar"></div>
<div class="timeBar"></div>
</div>
<div class="col-xs-3"><button class="time-btn info1" type="timebar"> <i class="fas fa-refresh"> <span class="hidden-xs" id="getTime"><div class="durationTime">00</div></span></i></button></div>
<div class="col-xs-3"><button class="time-btn2 info1" type="timebar"> <i class="fas fa-refresh"> <span class="hidden-xs" id="goTime"><div class="currentTime">00</div></span></i></button></div>
<div class="navigation">
<div class="col-xs-3"><button class="btn btn-default blackb" id="stepFiveback" type="button"> <i class="fa fa-backward"> <span class="hidden-xs"></span></i></button></div>
<div class="col-xs-3"><button class="btn btn-default blackb btn-big" id="playIt" type="button"> <i class="fa fa-play"> </i></button></div>
<div class="col-xs-3"><button class="btn btn-default blackb" id="stepFive" type="button"> <i class="fa fa-forward"> <span class="hidden-xs"></span></i></button></div>
</div>
</div>
</div>
</div>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/js/simple_player.js"></script>
</body>
</html>
strong text
A:
You will want to add a function to help convert all the Seconds to Minutes and Seconds.
Consider the following Example.
function convertSeconds(sec) {
var m = Math.floor(sec / 60);
var s = sec % 60;
return (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s);
}
This get the calculated Minutes and Seconds from a total number of Seconds using Division and Modulus. It may look like this in use:
$(document).ready(function() {
var timeDrag = false; /* Drag status */
var isPlaying = false;
var theSound = $("#firstTrack");
var allIcons = $("i");
var isLoaded = false;
function convertSeconds(sec) {
var m = Math.floor(sec / 60);
var s = sec % 60;
return (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s);
}
theSound.on("timeupdate", function() {
var currentPos = theSound[0].currentTime; //Get currenttime
var maxduration = theSound[0].duration; //Get video duration
var percentage = 100 * currentPos / maxduration; //in %
$('.timeBar').css('width', percentage + '%');
$("#getTime").html(convertSeconds(Math.floor(theSound[0].duration)));
$('#goTime').html(convertSeconds(Math.floor(theSound[0].currentTime)));
});
$("#playIt").click(function(event) {
if (!isLoaded) {
theSound.trigger('load');
setTimeout(startBuffer, 500);
isLoaded = true;
}
if (!isPlaying) {
theSound.trigger('play');
$("#playIt").find(allIcons).removeClass("fa-play");
$("#playIt").find(allIcons).addClass("fa-pause");
isPlaying = true;
} else {
theSound.trigger('pause');
$("#playIt").find(allIcons).removeClass("fa-pause");
$("#playIt").find(allIcons).addClass("fa-play");
isPlaying = false;
}
});
$("#stepFive").click(function() {
var currentPos = theSound[0].currentTime + 5;
theSound[0].currentTime = currentPos;
});
$("#stepFiveback").click(function() {
var currentPos = theSound[0].currentTime - 5;
theSound[0].currentTime = currentPos;
});
$('.progressBar').mousedown(function(e) {
timeDrag = true;
updatebar(e.pageX);
});
$(document).mouseup(function(e) {
if (timeDrag) {
timeDrag = false;
updatebar(e.pageX);
}
});
$(document).mousemove(function(e) {
if (timeDrag) {
updatebar(e.pageX);
}
});
//update Progress Bar control
var updatebar = function(x) {
var progress = $('.progressBar');
var maxduration = theSound[0].duration; //Video duraiton
var position = x - progress.offset().left; //Click pos
var percentage = 100 * position / progress.width();
//Check within range
if (percentage > 100) {
percentage = 100;
}
if (percentage < 0) {
percentage = 0;
}
//Update progress bar and video currenttime
$('.timeBar').css('width', percentage + '%');
theSound[0].currentTime = maxduration * percentage / 100;
};
//loop to get HTML5 video buffered data
var startBuffer = function() {
var maxduration = $("#firstTrack")[0].duration;
var currentBuffer = $("#firstTrack")[0].buffered.end(0);
var percentage = 100 * currentBuffer / maxduration;
$('.bufferBar').css('width', percentage + '%');
//re-loop if not entierely buffered
if (currentBuffer < maxduration) {
setTimeout(startBuffer, 500);
}
};
});
@charset "utf-8";
/*head*/
html,
html * {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: #1e1f1f;
max-height: 100vh;
/* change here */
}
/* -- */
.noPad {
padding: 0;
}
.playBar {
transition: all 0.5s ease;
height: 10px;
background-color: rgba(186, 44, 44, 0.59);
/*border: 1.5px;*/
/*border-color: black;*/
/*border-style: inset;*/
opacity: 0.85;
width: 0;
}
#audioCtrl>div {
margin: 0;
padding: 0;
}
.progressBar {
position: relative;
width: 100%;
height: .4em;
backgroud-color: #474848;
color: #474848;
scroll-behavior: smooth;
border: solid;
border-color: #474848;
border-width: 1px;
border-radius: 5px;
}
.timeBar {
transition: all 0.5s ease;
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background-color: #8c8d8e;
border-radius: 5px;
}
.bufferBar {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background-color: #474949;
opacity: 0.5;
border-radius: 5px;
}
/* -- */
.row {
/* background-color: #535252; */
border-radius: 10px;
}
.img-container img {
margin-top: 10em;
border-radius: 15px;
height: 22em;
}
.navigation {
display: flex;
align-items: center;
justify-content: center;
}
.info1 {}
.title {
font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, "sans-serif";
font-size: 1.7em;
margin: 0;
padding-bottom: .4em;
margin-left: .2em;
color: #f1f1f1;
}
.time-btn {
float: right;
margin-top: .3em;
background-color: #1E1F1F;
color: aliceblue;
border: 0;
font-family: Constantia, "Lucida Bright", "DejaVu Serif", Georgia, "serif";
font-size: 1em;
margin-right: .3em;
}
.time-btn2 {
margin-top: .3em;
background-color: #1E1F1F;
color: aliceblue;
border: 0;
font-family: Constantia, "Lucida Bright", "DejaVu Serif", Georgia, "serif";
font-size: 1em;
margin-left: .2em;
}
.btn {
background-color: #1e1f1f;
color: #D7D7D7;
border: 0;
font-size: 2.2em;
padding: .3em .7em;
}
.btn-big {
color: #FFFFFF;
font-size: 2.4em;
}
.btn:focus {
border: 0;
}
.scrollformore {
color: #FFFFFF;
font-family: "Gill Sans", "Gill Sans MT", "Myriad Pro", "DejaVu Sans Condensed", Helvetica, Arial, "sans-serif";
font-size: 1em;
margin-top: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.min.css" />
<div class="container-fluid">
<audio id="firstTrack" width="100%" preload="none">
<source src="https://www.bensound.com/bensound-music/bensound-ukulele.mp3" type="audio/mpeg" />
</audio>
<div class="img-container"><img src="https://www.bensound.com/bensound-img/ukulele.jpg" alt="cover"></div>
<h2 class="title info1">Ukulele</h2>
<div class="row" id="audioCtrl">
<div class="col-xs-3 progressBar">
<div class="bufferBar"></div>
<div class="timeBar"></div>
</div>
<div class="col-xs-3"><button class="time-btn info1" type="timebar"> <i class="fas fa-refresh"> <span class="hidden-xs" id="getTime"><div class="durationTime">00:00</div></span></i></button></div>
<div class="col-xs-3"><button class="time-btn2 info1" type="timebar"> <i class="fas fa-refresh"> <span class="hidden-xs" id="goTime"><div class="currentTime">00:00</div></span></i></button></div>
<div class="navigation">
<div class="col-xs-3"><button class="btn btn-default blackb" id="stepFiveback" type="button"> <i class="fa fa-backward"> <span class="hidden-xs"></span></i></button></div>
<div class="col-xs-3"><button class="btn btn-default blackb btn-big" id="playIt" type="button"> <i class="fa fa-play"> </i></button></div>
<div class="col-xs-3"><button class="btn btn-default blackb" id="stepFive" type="button"> <i class="fa fa-forward"> <span class="hidden-xs"></span></i></button></div>
</div>
</div>
</div>
</div>
A:
Try this:
export function timeFormat(d: number) {
const duration = Math.floor(d);
const h = Math.floor(duration / 3600);
const m = Math.floor((duration - h * 3600) / 60);
const s = duration % 60;
const H = h === 0 ? '' : `${h}:`;
const M = m < 10 ? `0${m}:` : `${m}:`;
const S = s < 10 ? `0${s}` : `${s}`;
return H + M + S;
}
| I can't convert .duration or .currentTime to MM:SS in java script | since I don't know JavaScript I downloaded an audio player and changed the html and CSS but the audio player shows audio duration in seconds and; I tried to look for results in google but that did not work as well, I even tried to copy code from other audio players but it did not work. I would be happy if anyone help me.
thanks...
$(document).ready(function() {
var timeDrag = false; /* Drag status */
var isPlaying = false;
var theSound = $("#firstTrack");
var allIcons = $("i");
var isLoaded = false;
theSound.on("timeupdate", function() {
var currentPos = theSound[0].currentTime; //Get currenttime
var maxduration = theSound[0].duration; //Get video duration
var percentage = 100 * currentPos / maxduration; //in %
$('.timeBar').css('width', percentage + '%');
$("#getTime").html(Math.floor(theSound[0].duration));
$('#goTime').html(Math.floor(theSound[0].currentTime));
});
$("#playIt").click(function(event) {
// run once.
if (!isLoaded) {
theSound.trigger('load');
setTimeout(startBuffer, 500);
isLoaded = true;
}
// toggle play/pause
if (!isPlaying) {
theSound.trigger('play');
$("#playIt").find(allIcons).removeClass("fa-play");
$("#playIt").find(allIcons).addClass("fa-pause");
isPlaying = true;
} else {
theSound.trigger('pause');
$("#playIt").find(allIcons).removeClass("fa-pause");
$("#playIt").find(allIcons).addClass("fa-play");
isPlaying = false;
}
});
$("#stepFive").click(function() {
var currentPos = theSound[0].currentTime + 5;
theSound[0].currentTime = currentPos;
});
$("#stepFiveback").click(function() {
var currentPos = theSound[0].currentTime - 5;
theSound[0].currentTime = currentPos;
});
$('.progressBar').mousedown(function(e) {
timeDrag = true;
updatebar(e.pageX);
});
$(document).mouseup(function(e) {
if (timeDrag) {
timeDrag = false;
updatebar(e.pageX);
}
});
$(document).mousemove(function(e) {
if (timeDrag) {
updatebar(e.pageX);
}
});
//update Progress Bar control
var updatebar = function(x) {
var progress = $('.progressBar');
var maxduration = theSound[0].duration; //Video duraiton
var position = x - progress.offset().left; //Click pos
var percentage = 100 * position / progress.width();
//Check within range
if (percentage > 100) {
percentage = 100;
}
if (percentage < 0) {
percentage = 0;
}
//Update progress bar and video currenttime
$('.timeBar').css('width', percentage + '%');
theSound[0].currentTime = maxduration * percentage / 100;
};
//loop to get HTML5 video buffered data
var startBuffer = function() {
var maxduration = $("#firstTrack")[0].duration;
var currentBuffer = $("#firstTrack")[0].buffered.end(0);
var percentage = 100 * currentBuffer / maxduration;
$('.bufferBar').css('width', percentage + '%');
//re-loop if not entierely buffered
if (currentBuffer < maxduration) {
setTimeout(startBuffer, 500);
}
};
});
@charset "utf-8";
/*head*/
html,
html * {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: #1e1f1f;
max-height: 100vh;
/* change here */
}
/* -- */
.noPad {
padding: 0;
}
.playBar {
transition: all 0.5s ease;
height: 10px;
background-color: rgba(186, 44, 44, 0.59);
/*border: 1.5px;*/
/*border-color: black;*/
/*border-style: inset;*/
opacity: 0.85;
width: 0;
}
#audioCtrl>div {
margin: 0;
padding: 0;
}
.progressBar {
position: relative;
width: 100%;
height: .4em;
backgroud-color: #474848;
color: #474848;
scroll-behavior: smooth;
border: solid;
border-color: #474848;
border-width: 1px;
border-radius: 5px;
}
.timeBar {
transition: all 0.5s ease;
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background-color: #8c8d8e;
border-radius: 5px;
}
.bufferBar {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background-color: #474949;
opacity: 0.5;
border-radius: 5px;
}
/* -- */
.row {
/* background-color: #535252; */
border-radius: 10px;
}
.img-container img {
margin-top: 10em;
border-radius: 15px;
height: 22em;
}
.navigation {
display: flex;
align-items: center;
justify-content: center;
}
.info1 {}
.title {
font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, "sans-serif";
font-size: 1.7em;
margin: 0;
padding-bottom: .4em;
margin-left: .2em;
color: #f1f1f1;
}
.time-btn {
float: right;
margin-top: .3em;
background-color: #1E1F1F;
color: aliceblue;
border: 0;
font-family: Constantia, "Lucida Bright", "DejaVu Serif", Georgia, "serif";
font-size: 1em;
margin-right: .3em;
}
.time-btn2 {
margin-top: .3em;
background-color: #1E1F1F;
color: aliceblue;
border: 0;
font-family: Constantia, "Lucida Bright", "DejaVu Serif", Georgia, "serif";
font-size: 1em;
margin-left: .2em;
}
.btn {
background-color: #1e1f1f;
color: #D7D7D7;
border: 0;
font-size: 2.2em;
padding: .3em .7em;
}
.btn-big {
color: #FFFFFF;
font-size: 2.4em;
}
.btn:focus {
border: 0;
}
.scrollformore {
color: #FFFFFF;
font-family: "Gill Sans", "Gill Sans MT", "Myriad Pro", "DejaVu Sans Condensed", Helvetica, Arial, "sans-serif";
font-size: 1em;
margin-top: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<title>audio_player_2</title>
<link rel="stylesheet" href="assets/css/styles.css">
<link rel="stylesheet" href="assets/css/aistyles.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.min.css" />
</head>
<body>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="simple_player.js"></script>
<div class="container-fluid"><audio id="firstTrack" width="100%" preload="none">
<source src="https://www.bensound.com/bensound-music/bensound-ukulele.mp3" type="audio/mpeg" />
</audio>
<div class="img-container"><img src="https://www.bensound.com/bensound-img/ukulele.jpg" alt="cover"></div>
<h2 class="title info1">Ukulele</h2>
<div class="row" id="audioCtrl">
<div class="col-xs-3 progressBar">
<div class="bufferBar"></div>
<div class="timeBar"></div>
</div>
<div class="col-xs-3"><button class="time-btn info1" type="timebar"> <i class="fas fa-refresh"> <span class="hidden-xs" id="getTime"><div class="durationTime">00</div></span></i></button></div>
<div class="col-xs-3"><button class="time-btn2 info1" type="timebar"> <i class="fas fa-refresh"> <span class="hidden-xs" id="goTime"><div class="currentTime">00</div></span></i></button></div>
<div class="navigation">
<div class="col-xs-3"><button class="btn btn-default blackb" id="stepFiveback" type="button"> <i class="fa fa-backward"> <span class="hidden-xs"></span></i></button></div>
<div class="col-xs-3"><button class="btn btn-default blackb btn-big" id="playIt" type="button"> <i class="fa fa-play"> </i></button></div>
<div class="col-xs-3"><button class="btn btn-default blackb" id="stepFive" type="button"> <i class="fa fa-forward"> <span class="hidden-xs"></span></i></button></div>
</div>
</div>
</div>
</div>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/js/simple_player.js"></script>
</body>
</html>
strong text
| [
"You will want to add a function to help convert all the Seconds to Minutes and Seconds.\nConsider the following Example.\nfunction convertSeconds(sec) {\n var m = Math.floor(sec / 60);\n var s = sec % 60;\n return (m < 10 ? \"0\" + m : m) + \":\" + (s < 10 ? \"0\" + s : s);\n}\n\nThis get the calculated Minutes and Seconds from a total number of Seconds using Division and Modulus. It may look like this in use:\n\n\n$(document).ready(function() {\n\n var timeDrag = false; /* Drag status */\n var isPlaying = false;\n var theSound = $(\"#firstTrack\");\n var allIcons = $(\"i\");\n var isLoaded = false;\n\n function convertSeconds(sec) {\n var m = Math.floor(sec / 60);\n var s = sec % 60;\n return (m < 10 ? \"0\" + m : m) + \":\" + (s < 10 ? \"0\" + s : s);\n }\n\n theSound.on(\"timeupdate\", function() {\n var currentPos = theSound[0].currentTime; //Get currenttime\n var maxduration = theSound[0].duration; //Get video duration\n var percentage = 100 * currentPos / maxduration; //in %\n $('.timeBar').css('width', percentage + '%');\n $(\"#getTime\").html(convertSeconds(Math.floor(theSound[0].duration)));\n $('#goTime').html(convertSeconds(Math.floor(theSound[0].currentTime)));\n });\n\n $(\"#playIt\").click(function(event) {\n if (!isLoaded) {\n theSound.trigger('load');\n setTimeout(startBuffer, 500);\n isLoaded = true;\n }\n\n if (!isPlaying) {\n\n theSound.trigger('play');\n\n $(\"#playIt\").find(allIcons).removeClass(\"fa-play\");\n $(\"#playIt\").find(allIcons).addClass(\"fa-pause\");\n\n isPlaying = true;\n\n } else {\n\n theSound.trigger('pause');\n\n $(\"#playIt\").find(allIcons).removeClass(\"fa-pause\");\n $(\"#playIt\").find(allIcons).addClass(\"fa-play\");\n\n isPlaying = false;\n\n }\n });\n\n $(\"#stepFive\").click(function() {\n var currentPos = theSound[0].currentTime + 5;\n theSound[0].currentTime = currentPos;\n });\n\n\n $(\"#stepFiveback\").click(function() {\n var currentPos = theSound[0].currentTime - 5;\n theSound[0].currentTime = currentPos;\n });\n\n $('.progressBar').mousedown(function(e) {\n timeDrag = true;\n updatebar(e.pageX);\n });\n\n $(document).mouseup(function(e) {\n if (timeDrag) {\n timeDrag = false;\n updatebar(e.pageX);\n }\n });\n $(document).mousemove(function(e) {\n if (timeDrag) {\n updatebar(e.pageX);\n }\n });\n\n //update Progress Bar control\n var updatebar = function(x) {\n var progress = $('.progressBar');\n var maxduration = theSound[0].duration; //Video duraiton\n var position = x - progress.offset().left; //Click pos\n var percentage = 100 * position / progress.width();\n\n //Check within range\n if (percentage > 100) {\n percentage = 100;\n }\n if (percentage < 0) {\n percentage = 0;\n }\n\n //Update progress bar and video currenttime\n $('.timeBar').css('width', percentage + '%');\n theSound[0].currentTime = maxduration * percentage / 100;\n };\n\n //loop to get HTML5 video buffered data\n var startBuffer = function() {\n\n var maxduration = $(\"#firstTrack\")[0].duration;\n var currentBuffer = $(\"#firstTrack\")[0].buffered.end(0);\n var percentage = 100 * currentBuffer / maxduration;\n $('.bufferBar').css('width', percentage + '%');\n\n //re-loop if not entierely buffered\n if (currentBuffer < maxduration) {\n setTimeout(startBuffer, 500);\n }\n\n };\n\n});\n@charset \"utf-8\";\n\n/*head*/\n\nhtml,\nhtml * {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n}\n\nbody {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n background: #1e1f1f;\n max-height: 100vh;\n /* change here */\n}\n\n\n/* -- */\n\n.noPad {\n padding: 0;\n}\n\n.playBar {\n transition: all 0.5s ease;\n height: 10px;\n background-color: rgba(186, 44, 44, 0.59);\n /*border: 1.5px;*/\n /*border-color: black;*/\n /*border-style: inset;*/\n opacity: 0.85;\n width: 0;\n}\n\n#audioCtrl>div {\n margin: 0;\n padding: 0;\n}\n\n.progressBar {\n position: relative;\n width: 100%;\n height: .4em;\n backgroud-color: #474848;\n color: #474848;\n scroll-behavior: smooth;\n border: solid;\n border-color: #474848;\n border-width: 1px;\n border-radius: 5px;\n}\n\n.timeBar {\n transition: all 0.5s ease;\n position: absolute;\n top: 0;\n left: 0;\n width: 0;\n height: 100%;\n background-color: #8c8d8e;\n border-radius: 5px;\n}\n\n.bufferBar {\n position: absolute;\n top: 0;\n left: 0;\n width: 0;\n height: 100%;\n background-color: #474949;\n opacity: 0.5;\n border-radius: 5px;\n}\n\n\n/* -- */\n\n.row {\n /* background-color: #535252; */\n border-radius: 10px;\n}\n\n.img-container img {\n margin-top: 10em;\n border-radius: 15px;\n height: 22em;\n}\n\n.navigation {\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.info1 {}\n\n.title {\n font-family: Segoe, \"Segoe UI\", \"DejaVu Sans\", \"Trebuchet MS\", Verdana, \"sans-serif\";\n font-size: 1.7em;\n margin: 0;\n padding-bottom: .4em;\n margin-left: .2em;\n color: #f1f1f1;\n}\n\n.time-btn {\n float: right;\n margin-top: .3em;\n background-color: #1E1F1F;\n color: aliceblue;\n border: 0;\n font-family: Constantia, \"Lucida Bright\", \"DejaVu Serif\", Georgia, \"serif\";\n font-size: 1em;\n margin-right: .3em;\n}\n\n.time-btn2 {\n margin-top: .3em;\n background-color: #1E1F1F;\n color: aliceblue;\n border: 0;\n font-family: Constantia, \"Lucida Bright\", \"DejaVu Serif\", Georgia, \"serif\";\n font-size: 1em;\n margin-left: .2em;\n}\n\n.btn {\n background-color: #1e1f1f;\n color: #D7D7D7;\n border: 0;\n font-size: 2.2em;\n padding: .3em .7em;\n}\n\n.btn-big {\n color: #FFFFFF;\n font-size: 2.4em;\n}\n\n.btn:focus {\n border: 0;\n}\n\n.scrollformore {\n color: #FFFFFF;\n font-family: \"Gill Sans\", \"Gill Sans MT\", \"Myriad Pro\", \"DejaVu Sans Condensed\", Helvetica, Arial, \"sans-serif\";\n font-size: 1em;\n margin-top: 2em;\n}\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.min.css\" />\n\n<div class=\"container-fluid\">\n <audio id=\"firstTrack\" width=\"100%\" preload=\"none\">\n <source src=\"https://www.bensound.com/bensound-music/bensound-ukulele.mp3\" type=\"audio/mpeg\" />\n </audio>\n <div class=\"img-container\"><img src=\"https://www.bensound.com/bensound-img/ukulele.jpg\" alt=\"cover\"></div>\n <h2 class=\"title info1\">Ukulele</h2>\n <div class=\"row\" id=\"audioCtrl\">\n <div class=\"col-xs-3 progressBar\">\n <div class=\"bufferBar\"></div>\n <div class=\"timeBar\"></div>\n </div>\n <div class=\"col-xs-3\"><button class=\"time-btn info1\" type=\"timebar\"> <i class=\"fas fa-refresh\"> <span class=\"hidden-xs\" id=\"getTime\"><div class=\"durationTime\">00:00</div></span></i></button></div>\n <div class=\"col-xs-3\"><button class=\"time-btn2 info1\" type=\"timebar\"> <i class=\"fas fa-refresh\"> <span class=\"hidden-xs\" id=\"goTime\"><div class=\"currentTime\">00:00</div></span></i></button></div>\n <div class=\"navigation\">\n <div class=\"col-xs-3\"><button class=\"btn btn-default blackb\" id=\"stepFiveback\" type=\"button\"> <i class=\"fa fa-backward\"> <span class=\"hidden-xs\"></span></i></button></div>\n <div class=\"col-xs-3\"><button class=\"btn btn-default blackb btn-big\" id=\"playIt\" type=\"button\"> <i class=\"fa fa-play\"> </i></button></div>\n <div class=\"col-xs-3\"><button class=\"btn btn-default blackb\" id=\"stepFive\" type=\"button\"> <i class=\"fa fa-forward\"> <span class=\"hidden-xs\"></span></i></button></div>\n </div>\n </div>\n</div>\n</div>\n\n\n\n",
"Try this:\nexport function timeFormat(d: number) {\n const duration = Math.floor(d);\n const h = Math.floor(duration / 3600);\n const m = Math.floor((duration - h * 3600) / 60);\n const s = duration % 60;\n const H = h === 0 ? '' : `${h}:`;\n const M = m < 10 ? `0${m}:` : `${m}:`;\n const S = s < 10 ? `0${s}` : `${s}`;\n return H + M + S;\n}\n\n"
] | [
0,
0
] | [] | [] | [
"audio_player",
"javascript",
"jquery",
"media_player",
"time"
] | stackoverflow_0068988503_audio_player_javascript_jquery_media_player_time.txt |
Q:
Flutter - AnimateCamera not working with newLatLngBounds
I'm using Google map and after adding lot of marker i want to move camera to newLatLngBounds to show all the marker visible to user. But i'm facing this Error.
Error using newLatLngBounds(LatLngBounds, int): Map size can't be 0. Most likely, layout has not yet occured for the map view. Either wait until layout has occurred or use newLatLngBounds(LatLngBounds, int, int, int) which allows you to specify the map's dimensions., null)
Future<void> getCenterMap() async {
double minlatitude = loadInformationMap[0]['latlng'].latitude,
maxlatitude = loadInformationMap[0]['latlng'].latitude,
minlongitude = loadInformationMap[0]['latlng'].longitude,
maxlongitude = loadInformationMap[0]['latlng'].longitude;
for (int i = 0; i < loadInformationMap.length; i++) {
if (minlatitude >= loadInformationMap[i]['latlng'].latitude) {
minlatitude = loadInformationMap[i]['latlng'].latitude;
}
if (minlongitude >= loadInformationMap[i]['latlng'].longitude) {
minlongitude = loadInformationMap[i]['latlng'].longitude;
}
if (maxlatitude <= loadInformationMap[i]['latlng'].latitude) {
maxlatitude = loadInformationMap[i]['latlng'].latitude;
}
if (maxlongitude <= loadInformationMap[i]['latlng'].longitude) {
maxlongitude = loadInformationMap[i]['latlng'].longitude;
}
}
googleMapController.animateCamera(CameraUpdate.newLatLngBounds(
LatLngBounds(
southwest: LatLng(minlatitude, minlongitude),
northeast: LatLng(maxlatitude, maxlongitude)),
100));
}
A:
before animate camera await for some time:
Future<void> _onMapCreated(GoogleMapController controller) async {
_mapController.complete(controller);
_googleMapController = await _mapController.future;
Future.delayed(const Duration(seconds: 1), () => getCenterMap());
}
| Flutter - AnimateCamera not working with newLatLngBounds | I'm using Google map and after adding lot of marker i want to move camera to newLatLngBounds to show all the marker visible to user. But i'm facing this Error.
Error using newLatLngBounds(LatLngBounds, int): Map size can't be 0. Most likely, layout has not yet occured for the map view. Either wait until layout has occurred or use newLatLngBounds(LatLngBounds, int, int, int) which allows you to specify the map's dimensions., null)
Future<void> getCenterMap() async {
double minlatitude = loadInformationMap[0]['latlng'].latitude,
maxlatitude = loadInformationMap[0]['latlng'].latitude,
minlongitude = loadInformationMap[0]['latlng'].longitude,
maxlongitude = loadInformationMap[0]['latlng'].longitude;
for (int i = 0; i < loadInformationMap.length; i++) {
if (minlatitude >= loadInformationMap[i]['latlng'].latitude) {
minlatitude = loadInformationMap[i]['latlng'].latitude;
}
if (minlongitude >= loadInformationMap[i]['latlng'].longitude) {
minlongitude = loadInformationMap[i]['latlng'].longitude;
}
if (maxlatitude <= loadInformationMap[i]['latlng'].latitude) {
maxlatitude = loadInformationMap[i]['latlng'].latitude;
}
if (maxlongitude <= loadInformationMap[i]['latlng'].longitude) {
maxlongitude = loadInformationMap[i]['latlng'].longitude;
}
}
googleMapController.animateCamera(CameraUpdate.newLatLngBounds(
LatLngBounds(
southwest: LatLng(minlatitude, minlongitude),
northeast: LatLng(maxlatitude, maxlongitude)),
100));
}
| [
"before animate camera await for some time:\nFuture<void> _onMapCreated(GoogleMapController controller) async {\n_mapController.complete(controller);\n_googleMapController = await _mapController.future;\nFuture.delayed(const Duration(seconds: 1), () => getCenterMap());\n\n}\n"
] | [
0
] | [] | [] | [
"dart",
"flutter",
"google_maps",
"google_maps_markers",
"latitude_longitude"
] | stackoverflow_0060482979_dart_flutter_google_maps_google_maps_markers_latitude_longitude.txt |
Q:
Laravel 9 error Array to string conversion when run seeder
I have an error on Laravel 9 when run seeder, its say Array to string conversion
I have a same seeder type json before this DataMaster table, and its working. But when i run DataMasterSeeder, its not working
My seeder:
<?php
namespace Database\Seeders;
use App\Models\DataMaster;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DataMasterSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//SDU
DataMaster::create(['formId' => 1, 'userId' => 1, 'kecamatanId' => 1, 'desaId' => null, 'fieldDatas' => [['id' => '1', 'name' => 'jumlah', 'title' => 'Jumlah', 'value' => '4605']], 'level' => 'kecamatan']);
}
}
And my DataMaster migration:
public function up()
{
Schema::create('data_masters', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('formId');
$table->unsignedBigInteger('userId');
$table->unsignedBigInteger('kecamatanId')->nullable();
$table->unsignedBigInteger('desaId')->nullable();
$table->json('fieldDatas');
$table->enum('level', ['kecamatan', 'desa']);
$table->timestamps();
$table->foreign("formId")->references("id")->on("forms")->onDelete('cascade');
$table->foreign("userId")->references("id")->on("users")->onDelete('cascade');
$table->foreign("kecamatanId")->references("id")->on("kecamatans")->onDelete('cascade');
$table->foreign("desaId")->references("id")->on("desas")->onDelete('cascade');
});
}
I have another seeder like fieldDatas json field in this DataMaster seeder, and i run it successfully before run DataMaster seeder.
A:
you should encode the field fieldDatas before inserting
DataMaster::create([
'formId' => 1,
'userId' => 1,
'kecamatanId' => 1,
'desaId' => null,
// here...
'fieldDatas' => json_encode([['id' => '1', 'name' => 'jumlah', 'title' => 'Jumlah', 'value' => '4605']]),
'level' => 'kecamatan',
]);
| Laravel 9 error Array to string conversion when run seeder | I have an error on Laravel 9 when run seeder, its say Array to string conversion
I have a same seeder type json before this DataMaster table, and its working. But when i run DataMasterSeeder, its not working
My seeder:
<?php
namespace Database\Seeders;
use App\Models\DataMaster;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DataMasterSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//SDU
DataMaster::create(['formId' => 1, 'userId' => 1, 'kecamatanId' => 1, 'desaId' => null, 'fieldDatas' => [['id' => '1', 'name' => 'jumlah', 'title' => 'Jumlah', 'value' => '4605']], 'level' => 'kecamatan']);
}
}
And my DataMaster migration:
public function up()
{
Schema::create('data_masters', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('formId');
$table->unsignedBigInteger('userId');
$table->unsignedBigInteger('kecamatanId')->nullable();
$table->unsignedBigInteger('desaId')->nullable();
$table->json('fieldDatas');
$table->enum('level', ['kecamatan', 'desa']);
$table->timestamps();
$table->foreign("formId")->references("id")->on("forms")->onDelete('cascade');
$table->foreign("userId")->references("id")->on("users")->onDelete('cascade');
$table->foreign("kecamatanId")->references("id")->on("kecamatans")->onDelete('cascade');
$table->foreign("desaId")->references("id")->on("desas")->onDelete('cascade');
});
}
I have another seeder like fieldDatas json field in this DataMaster seeder, and i run it successfully before run DataMaster seeder.
| [
"you should encode the field fieldDatas before inserting\nDataMaster::create([\n 'formId' => 1,\n 'userId' => 1,\n 'kecamatanId' => 1,\n 'desaId' => null,\n // here...\n 'fieldDatas' => json_encode([['id' => '1', 'name' => 'jumlah', 'title' => 'Jumlah', 'value' => '4605']]),\n 'level' => 'kecamatan',\n]);\n\n"
] | [
2
] | [] | [] | [
"laravel",
"php"
] | stackoverflow_0074677678_laravel_php.txt |
Q:
JPanel not rendering correctly, it is taller than the JFrame and things that sould render on top of the bottom border render below it
When I tell awt/swing to draw a component at a given y that is smaller than the window height, that object renders on the bottom of the bottom border, but it should not, it is supposed to render at that given y.
Here some code example:
public class Main {
public static GameWindow window;
public static void main(String[] args) {
window = new GameWindow();
}
}
class GameWindow extends JFrame {
private final GamePanel panel;
public GameWindow() {
super();
this.setSize(600, 400); //Observe that the height is 400
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new GamePanel();
this.add(panel);
//Uncomment the following line and observe how the square now renders where it should
//setUndecorated(true);
this.setVisible(true);
}
//Uncomment the following method to see a black line just on top of the bottom border
/*@Override
public int getHeight() {
return panel.getHeight();
}*/
}
class GamePanel extends JPanel {
public GamePanel() {
super();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Here it should render just above the bottom border, but it doesn't, it renders well below
g.fill3DRect(0, Main.window.getHeight() - 22, 22, 22, false);
}
}
Case 1: If you live it decorated, you have to resize the window in order to see the square.
Case 2: If you make the JFrame undecorated it renders as it should: just on top of the bottom border.
Case 3: If you live it decorated, but override the getHeight method so that it returns the height of the panel, a black line is rendered in the bottom of the window.
Images:
Case 1:
Case 2:
Case 3:
A:
The coordinate system used by Swing starts in the left upper corner and is relative to the component, and so 0,0 is the left upper part of the JPanel. Here:
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fill3DRect(0, Main.window.getHeight() - 22, 22, 22, false);
}
You are in fact telling Swing to always draw in a non-visible part of your JPanel, above the JPanel, and so this code will never work.
If you want to draw at the bottom, use component's getHeight() method to find the bottom of the JPanel, and draw above that:
int yPos = getHeight() - 22;
g.fill3DRect(0, yPos, 22, 22, false);
But also, never use "magic numbers" such as 22 here. Also, avoid setting sizes but instead override getPreferredSize():
e.g.,
public class GamePanel extends JPanel {
public static final int PREF_W = 600;
public static final int PREF_H = 400;
public static final int SPRITE_WIDTH = 22;
public GamePanel() {
super();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int yPos = getHeight() - SPRITE_WIDTH;
g.fill3DRect(0, yPos, SPRITE_WIDTH, SPRITE_WIDTH, false);
}
@Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
int w = Math.max(PREF_W, superSize.width);
int h = Math.max(PREF_H, superSize.height);
return new Dimension(w, h);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
GamePanel mainPanel = new GamePanel();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
| JPanel not rendering correctly, it is taller than the JFrame and things that sould render on top of the bottom border render below it | When I tell awt/swing to draw a component at a given y that is smaller than the window height, that object renders on the bottom of the bottom border, but it should not, it is supposed to render at that given y.
Here some code example:
public class Main {
public static GameWindow window;
public static void main(String[] args) {
window = new GameWindow();
}
}
class GameWindow extends JFrame {
private final GamePanel panel;
public GameWindow() {
super();
this.setSize(600, 400); //Observe that the height is 400
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new GamePanel();
this.add(panel);
//Uncomment the following line and observe how the square now renders where it should
//setUndecorated(true);
this.setVisible(true);
}
//Uncomment the following method to see a black line just on top of the bottom border
/*@Override
public int getHeight() {
return panel.getHeight();
}*/
}
class GamePanel extends JPanel {
public GamePanel() {
super();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Here it should render just above the bottom border, but it doesn't, it renders well below
g.fill3DRect(0, Main.window.getHeight() - 22, 22, 22, false);
}
}
Case 1: If you live it decorated, you have to resize the window in order to see the square.
Case 2: If you make the JFrame undecorated it renders as it should: just on top of the bottom border.
Case 3: If you live it decorated, but override the getHeight method so that it returns the height of the panel, a black line is rendered in the bottom of the window.
Images:
Case 1:
Case 2:
Case 3:
| [
"The coordinate system used by Swing starts in the left upper corner and is relative to the component, and so 0,0 is the left upper part of the JPanel. Here:\n@Override\npublic void paintComponent(Graphics g) {\n super.paintComponent(g);\n g.fill3DRect(0, Main.window.getHeight() - 22, 22, 22, false);\n}\n\nYou are in fact telling Swing to always draw in a non-visible part of your JPanel, above the JPanel, and so this code will never work.\nIf you want to draw at the bottom, use component's getHeight() method to find the bottom of the JPanel, and draw above that:\nint yPos = getHeight() - 22;\ng.fill3DRect(0, yPos, 22, 22, false);\n\nBut also, never use \"magic numbers\" such as 22 here. Also, avoid setting sizes but instead override getPreferredSize():\ne.g.,\npublic class GamePanel extends JPanel {\n public static final int PREF_W = 600;\n public static final int PREF_H = 400;\n public static final int SPRITE_WIDTH = 22;\n\n public GamePanel() {\n super();\n }\n\n @Override\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n int yPos = getHeight() - SPRITE_WIDTH;\n g.fill3DRect(0, yPos, SPRITE_WIDTH, SPRITE_WIDTH, false);\n }\n\n @Override\n public Dimension getPreferredSize() {\n Dimension superSize = super.getPreferredSize();\n int w = Math.max(PREF_W, superSize.width);\n int h = Math.max(PREF_H, superSize.height);\n return new Dimension(w, h);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n GamePanel mainPanel = new GamePanel();\n\n JFrame frame = new JFrame(\"GUI\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.add(mainPanel);\n frame.pack();\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n });\n }\n\n}\n\n"
] | [
0
] | [
"Problem was I was using/overriding JFrame getWidth and Height, I just made a method with another name to get those informations and now it works fine, turns out that returning the panel dimensions in the window methods is not ok.\n"
] | [
-2
] | [
"awt",
"java",
"swing"
] | stackoverflow_0074677014_awt_java_swing.txt |
Q:
Cogs loads but won't work in discord.py 2.0
I've provided code of two files. bot.py - runs bot, ping.py - cog file.
The problem is that Cog doesn't work, bot doesn't respond to commands, in my ping.py file i have ping command
bot.py
import discord as ds
import asyncio
import os
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
intents = ds.Intents.all()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_message(message):
if message.author == bot.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
print(f"{username} said: '{user_message}' ({channel})")
async def load_cogs():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
@bot.event
async def on_ready():
print(f'{bot.user} is now running.')
async def main():
await load_cogs()
async with bot:
TOKEN = os.getenv('TOKEN')
await bot.start(TOKEN)
asyncio.run(main())
ping.py
import discord
from discord.ext import commands
import asyncio
class ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="ping", description="Returns Pong!")
async def ping(self, ctx):
await ctx.send("Pong!")
async def setup(bot: commands.Bot):
await bot.add_cog(ping(bot))
After running bot display 0 errors. I tried to changing intents from default() to all() but it didn't help.
A:
You override the on_message event, and you don't have a process_commands in it, so the bot won't be processing any commands.
You can fix this by adding bot.process_commands inside the event.
@bot.event
async def on_message(message):
...
await bot.process_commands(message)
Or register it as a listener so it doesn't override the default event.
@bot.listen()
async def on_message(message):
...
| Cogs loads but won't work in discord.py 2.0 | I've provided code of two files. bot.py - runs bot, ping.py - cog file.
The problem is that Cog doesn't work, bot doesn't respond to commands, in my ping.py file i have ping command
bot.py
import discord as ds
import asyncio
import os
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
intents = ds.Intents.all()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_message(message):
if message.author == bot.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
print(f"{username} said: '{user_message}' ({channel})")
async def load_cogs():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
@bot.event
async def on_ready():
print(f'{bot.user} is now running.')
async def main():
await load_cogs()
async with bot:
TOKEN = os.getenv('TOKEN')
await bot.start(TOKEN)
asyncio.run(main())
ping.py
import discord
from discord.ext import commands
import asyncio
class ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="ping", description="Returns Pong!")
async def ping(self, ctx):
await ctx.send("Pong!")
async def setup(bot: commands.Bot):
await bot.add_cog(ping(bot))
After running bot display 0 errors. I tried to changing intents from default() to all() but it didn't help.
| [
"You override the on_message event, and you don't have a process_commands in it, so the bot won't be processing any commands.\nYou can fix this by adding bot.process_commands inside the event.\[email protected]\nasync def on_message(message):\n ...\n await bot.process_commands(message)\n\nOr register it as a listener so it doesn't override the default event.\[email protected]()\nasync def on_message(message):\n ...\n\n"
] | [
1
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074677573_discord_discord.py_python.txt |
Q:
How to set dragable oblect in container on randome places jQuery
i work with draggable object, i will have lot of containers at which i need to setup objects.
But problem is that i can't set is on random place, or which i want, it's working like list
But i want to set up randomly:
I create JsFiddle with code:
$(document).ready(function() {
$("#addBtn").click(function() {
var $div = $("<div>", {
"class": "alert alert-info draggable alwaysTop",
text: "Say-Da-Tay!"
}).draggable();
$("#dropbox").prepend($div);
});
$(".droppable").droppable({
accept: ".draggable",
drop: function(event, ui) {
var dropped = ui.draggable;
var droppedOn = $(this);
$(dropped).detach().css({
top: 0,
left: 0
}).appendTo(droppedOn);
}
});
});
.alwaysTop {
width: 40%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js"></script>
<div>
<div class="col-md-4">
<div class="panel panel-primary parentPanel">
<div class="panel-heading">
<h3 class="panel-title">Dropbox</h3>
</div>
<div class="panel-body droppable" id="dropbox">
</div>
</div>
</div>
<div class="btn - btn-warning col-md-2" id="addBtn">
Add Item
</div>
<div class="col-md-4">
<div class="panel panel-success parentPanel">
<div class="panel-heading">
<h3 class="panel-title">Final Destination</h3>
</div>
<div class="panel-body droppable" id="final_dest">
</div>
</div>
</div>
</div>
I want to set object randomy on the container, i want to drag object at random place in container and it's will stay, now it's set to the list
A:
why not use a solution based on an example from the jQuery library
https://jqueryui.com/droppable/#default
https://jqueryui.com/droppable/#revert
All you have to do is change the height of the initial dropbox to whatever you want.
$( function() {
$( ".draggable" ).draggable({
revert:"invalid"
});
$( ".droppable" ).droppable({
drop: function( event, ui ) {
$( this )
}
});
} );
let btn = document.querySelector(".add-btn")
btn.addEventListener("click",()=>{
let div = document.createElement("div")
div.classList.add("draggable","ui-widget-content")
div.innerHTML = "Drag me"
let initialDropbox = document.querySelector("#initial-dropbox")
initialDropbox.appendChild(div)
$(div).draggable({
revert:"invalid"
});
})
body,p{
margin:0;
}
*{
box-sizing: border-box;
}
.draggable {
width: 100px;
min-height: 100px;
padding: 0.5em;
float: left;
margin: 10px 10px 10px 0;
}
.droppable {
width: 150px;
min-height: 250px;
padding: 0.5em;
float: left;
margin: 10px;
}
.title{
background: #dccaca;
padding: 15px;
width: 100%;
text-align: center;
}
.container{
display: flex;
align-items: baseline;
}
<link href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<div class="container">
<div id="initial-dropbox" class="droppable ui-widget-header">
<p class="title">Dropbox</p>
<div class="draggable ui-widget-content">
<p>Drag me</p>
</div>
</div>
<button class="add-btn">Add item</button>
<div class="droppable ui-widget-header">
<p class="title">Final destination</p>
</div>
</div>
| How to set dragable oblect in container on randome places jQuery | i work with draggable object, i will have lot of containers at which i need to setup objects.
But problem is that i can't set is on random place, or which i want, it's working like list
But i want to set up randomly:
I create JsFiddle with code:
$(document).ready(function() {
$("#addBtn").click(function() {
var $div = $("<div>", {
"class": "alert alert-info draggable alwaysTop",
text: "Say-Da-Tay!"
}).draggable();
$("#dropbox").prepend($div);
});
$(".droppable").droppable({
accept: ".draggable",
drop: function(event, ui) {
var dropped = ui.draggable;
var droppedOn = $(this);
$(dropped).detach().css({
top: 0,
left: 0
}).appendTo(droppedOn);
}
});
});
.alwaysTop {
width: 40%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js"></script>
<div>
<div class="col-md-4">
<div class="panel panel-primary parentPanel">
<div class="panel-heading">
<h3 class="panel-title">Dropbox</h3>
</div>
<div class="panel-body droppable" id="dropbox">
</div>
</div>
</div>
<div class="btn - btn-warning col-md-2" id="addBtn">
Add Item
</div>
<div class="col-md-4">
<div class="panel panel-success parentPanel">
<div class="panel-heading">
<h3 class="panel-title">Final Destination</h3>
</div>
<div class="panel-body droppable" id="final_dest">
</div>
</div>
</div>
</div>
I want to set object randomy on the container, i want to drag object at random place in container and it's will stay, now it's set to the list
| [
"why not use a solution based on an example from the jQuery library\nhttps://jqueryui.com/droppable/#default\nhttps://jqueryui.com/droppable/#revert\nAll you have to do is change the height of the initial dropbox to whatever you want.\n\n\n$( function() {\n $( \".draggable\" ).draggable({\n revert:\"invalid\"\n });\n $( \".droppable\" ).droppable({\n drop: function( event, ui ) {\n $( this )\n }\n });\n } );\n\n let btn = document.querySelector(\".add-btn\")\n btn.addEventListener(\"click\",()=>{\n let div = document.createElement(\"div\")\n div.classList.add(\"draggable\",\"ui-widget-content\")\n div.innerHTML = \"Drag me\"\n let initialDropbox = document.querySelector(\"#initial-dropbox\")\n initialDropbox.appendChild(div)\n $(div).draggable({\n revert:\"invalid\"\n });\n })\nbody,p{\n margin:0;\n }\n *{\n box-sizing: border-box;\n }\n .draggable {\n width: 100px;\n min-height: 100px;\n padding: 0.5em;\n float: left;\n margin: 10px 10px 10px 0;\n }\n\n .droppable {\n width: 150px;\n min-height: 250px;\n padding: 0.5em;\n float: left;\n margin: 10px;\n }\n .title{\n background: #dccaca;\n padding: 15px;\n width: 100%;\n text-align: center;\n }\n .container{\n display: flex;\n align-items: baseline;\n }\n<link href=\"https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css\" rel=\"stylesheet\"/>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.13.2/jquery-ui.js\"></script>\n<div class=\"container\">\n <div id=\"initial-dropbox\" class=\"droppable ui-widget-header\">\n <p class=\"title\">Dropbox</p>\n <div class=\"draggable ui-widget-content\">\n <p>Drag me</p>\n </div>\n</div>\n<button class=\"add-btn\">Add item</button>\n\n\n \n<div class=\"droppable ui-widget-header\">\n <p class=\"title\">Final destination</p>\n</div>\n </div>\n\n\n\n"
] | [
0
] | [] | [] | [
"css",
"html",
"javascript",
"jquery"
] | stackoverflow_0074655191_css_html_javascript_jquery.txt |
Q:
Express JS req.body undefined
req.body returns undefined.
Here is my code.
const express = require('express');
const app = express();
const courses = [
{ id: 1, name: 'course1'},
{ id: 2, name: 'course2'},
{ id: 3, name: 'course3'},
];
app.use(express.json());
app.get('/api/courses', (req, res) => {
res.send(courses);
});
app.post('/api/courses', (req, res) =>{
const course = {
id: courses.length + 1,
name: req.body.name
};
courses.push(course)
res.send(course)
});
const port = process.env.PORT || 3000
app.listen(port, () => console.log(`Listening on port ${port}...`))
Using postman to post an object, for example
{
"name" : "newCourse"
}
will return only id, not returning both the expected id and name. Console.log(course.name) returns undefined.
This code is from a tutorial by Programming with Mosh https://www.youtube.com/watch?v=pKd0Rpw7O48 Time: 33 min
I'm a beginner in node and express, any clue and explaination on why this doesn't work as it did in the tutorial?
A:
Add this line app.use(express.urlencoded({})) below app.use(express.json()) line
A:
From the documentation:
req.body:
Contains key-value pairs of data submitted in the request body. By
default, it is undefined, and is populated when you use body-parsing
middleware such as body-parser and multer.
A:
The issue is that while using postman, i forgot to change the post input type from text to JSON. Once i set it to json, it works.
| Express JS req.body undefined | req.body returns undefined.
Here is my code.
const express = require('express');
const app = express();
const courses = [
{ id: 1, name: 'course1'},
{ id: 2, name: 'course2'},
{ id: 3, name: 'course3'},
];
app.use(express.json());
app.get('/api/courses', (req, res) => {
res.send(courses);
});
app.post('/api/courses', (req, res) =>{
const course = {
id: courses.length + 1,
name: req.body.name
};
courses.push(course)
res.send(course)
});
const port = process.env.PORT || 3000
app.listen(port, () => console.log(`Listening on port ${port}...`))
Using postman to post an object, for example
{
"name" : "newCourse"
}
will return only id, not returning both the expected id and name. Console.log(course.name) returns undefined.
This code is from a tutorial by Programming with Mosh https://www.youtube.com/watch?v=pKd0Rpw7O48 Time: 33 min
I'm a beginner in node and express, any clue and explaination on why this doesn't work as it did in the tutorial?
| [
"Add this line app.use(express.urlencoded({})) below app.use(express.json()) line\n",
"From the documentation:\n\nreq.body:\nContains key-value pairs of data submitted in the request body. By\ndefault, it is undefined, and is populated when you use body-parsing\nmiddleware such as body-parser and multer.\n\n",
"The issue is that while using postman, i forgot to change the post input type from text to JSON. Once i set it to json, it works.\n"
] | [
1,
0,
0
] | [] | [] | [
"body_parser",
"express",
"javascript",
"node.js"
] | stackoverflow_0074670258_body_parser_express_javascript_node.js.txt |
Q:
Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15
In Stripe, my client wants email and cardholder name, but the Stripe payment UI doesn't provide that option in com.stripe.android.view.CardMultilineWidget. I wanted to give it a try with the latest stripe version,
I was using Stripe version (14.1.1). So I updated it to the latest one (16.8.0)
The build showed me the error that it doesn't take minSdkVersion 19. It requires 21 in manifest merger. So I updated minSdkVersion to 21.
I got
caches/transforms-2/files-2.1/4541b0189187e0017d23bbb0afebd16a/jetified-kotlin-stdlib-common-1.5.0.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
I tried changing the Gradle version, but I am still getting the same error. How can I solve the incompatible error and add the email and cardholder name in Stripe?
A:
Changing this in file build.gradle solved my problem.
From
ext.kotlin_version = '1.3.50'
to
ext.kotlin_version = '1.6.0'
Or whatever the latest version of Kotlin available and make sure to update Kotlin version on Android Studio as well.
A:
I had this problem in a Flutter project.
In my case, a line for kotlin-gradle-plugin was missing in the Android build.gradle file, so adding ext.kotlin_version = '1.6.10' didn’t fix it.
After adding
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
the error was gone.
Full code section:
buildscript {
ext.kotlin_version = '1.6.10'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
A:
If you are facing this error in Flutter build for Android then try to change the Kotlin version to
ext.kotlin_version = '1.4.32'
A:
Firstly, go to settings, and then navigate to plugins. Find the Kotlin plugin and update it.
Next, in gradle files, go to build.gradle (Project: YourApp). Then, change the following code (in buildscript) from:
ext.kotlin_version = '1.3.50'
to the latest version, such as:
ext.kotlin_version = '1.4.32'
To know the latest version, go to settings and the plugins, find the Kotlin plugin, and make sure it is updated. The latest version is under JetBrains.
After following the instructions, your error will be resolved.
A:
Make sure that the Kotlin version of your IDE is the same as the version declared in your gradle.build file.
A:
It was fixed by updating the Kotlin Gradle plugin version.
In the project level build.gradle file, update the following line.
ext.kotlin_version = '1.6.10'
You can find the latest Kotlin Gradle plugin version at
Tools / Build tools / Gradle.
A:
What do you need to to solve this?
I was facing this issue since last night. Just navigate through some webpages couldn't get to the exact solution. I finally solved it by these steps:
Replace ext.kotlin_version = '1.3.50' with ext.kotlin_version = '1.4.32' in the build.gradle file.
Clean project → Build the project with Gradle files → Run
A:
Changed the Project build gradle to
buildscript {
ext.kotlin_version = '1.7.20'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.2.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
A:
Although this question has been answered, I think it's worth explaining what is happening
For the example:
The binary version of its metadata is 1.7.1, expected version is 1.5.1.
The expected version is the Kotlin for kotlin-gradle-plugin
The binary version is the what is downloaded (or previously compiled)
for com.android.tools.build:gradle
<project_dir>/android/build.gradle
buildscript {
ext.kotlin_version = '1.5.20' // <= expected version is 1.5.1
}
dependencies {
classpath 'com.android.tools.build:gradle:7.3.1' // downloads 1.7.1 Metadata
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // <= 1.5.20 used here
Why is this Happening So Much?
The user updates the Kotlin version of the plugin to match the IDE version per the warning.
The user updates the android build tools gradle plugin per the warning
This is the WRONG version!
Now you don't have any warnings, but the version suggested is 7.1.3 which is not the latest. (I don't know why it suggests this older version) 7.3.1 is currently the latest and is meta data 1.7.1, so it will match the Kotlin version of 1.7.20 (which is also metadata 1.7.1)
What else could be wrong?
Due to caching, gradle may be using an older dependency before you updated. To start clean:
delete the ~/.gradle/cache directory
delete the android/.gradle directory
delete the project_dir/build dir
ensure the android/gradle/gradle-wrapper.properies has the correct distributionUrl (currently distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip)
from project_dir do flutter build apk
NOTE: your dependencies may need to be updated if their com.android.tools.build:gradle version is too old. Alternatively, both the kotlin and tools:gradle versions can be downgraded to compatible version that match metadata (although Android Studio will warn for that not matching the IDE Kotlin version)
How to Prevent this from happening Again?
Use the same Kotlin version as the IDE normally for ext.kotlin_version. see https://kotlinlang.org/docs/releases.html#release-details
Double check the com.android.tools.build:gradle version. See https://developer.android.com/studio/releases/gradle-plugin#updating-gradle and https://mvnrepository.com/artifact/com.android.tools.build/gradle?repo=google
A:
in my case for
The binary version of its metadata is 1.7.1, expected version is 1.5.1
got to (dependencies) inside build.gradle(project) convert from 1.5.x (x) in my case is (20)
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.20"
to 1.7.10
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10"
A:
Another solution is to downgrade androidx.core:core-ktx library to any compatible version. This one worked for kotlin_version = '1.3.31':
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.3.1' // The only working for this version (sdk/gradle)
implementation 'androidx.core:core-ktx:1.0.2' // The only working for this version (sdk/gradle)
implementation 'androidx.constraintlayout:constraintlayout:1.1.2' // higher versions require min-sdk >= 26
...
}
Android SDK: compileSdkVersion 30 and minSdkVersion 19.
Gradle build Tool: com.android.tools.build:gradle:3.3.1.
A:
Just go to file build.gradle (Project: yourProjectName).
Change
plugins {
...
id 'org.jetbrains.kotlin.android' version '1.5.x' apply false
...
}
(1.5.x means x version number at your case, such as 1.5.1.)
To
plugins {
...
id 'org.jetbrains.kotlin.android' version '1.7.10' apply false
...
}
It works in my case...
A:
Most of the answers here seem to revolve around projects that use Gradle.
I randomly encountered this problem in IntelliJ IDEA that that was compiling and running a Maven project just fine 5 minutes before - no configuration changes. I introduced a new exception class and this problem popped up.
I tried invalidating caches and restarting, which didn't resolve the issue - however, disabling and re-enabling the Kotlin plugin resolved the issue.
A:
Using Flutter, it was fixed by:
Updating Android Studio packages, specially the Kotlin plugin.
Get the last Kotlin plugin version Nbr from Gradle - Plugin and versions. For now it's 1.6.10.
Update <Your_project_name_folder>\android\build.gradle file by replacing the old Kotlin version by the new one you got from the web site above.
ext.kotlin_version = '<The_new_version_Nbr>' in my case ext.kotlin_version = '1.6.10'
Restart Visual Studio Code.
You're done.
A:
I faced the same problem in Flutter and I fixed it by going to:
File > Settings > Plugins as @Muzzamil said and I checked for the version of Kotlin in my IDE and simply replaced the value in ext.kotlin_version (that is 1.6.10) by that value
ext.kotlin_version = '1.6.10'
A:
I have faced this error in IntelliJ IDEA with a Maven project.
The solution is about to turn off Kotlin plugin in IntelliJ IDEA if you are not using Kotlin in your project.
Go to:
Menu File → Settings → Plugins
And turn off the Kotlin plugin by click on the checkbox. See here:
A:
I have the set minsdk 24 and restart the Android Studio, its working fine.
A:
project build.gradle:
ext.kotlin_version = '1.6.10'
app/build.gradle:
dependencies {
// classpath 'com.android.tools.build:gradle:7.1.2'
// classpath "org.jetbrains.kotlin:kotlin-gradle- plugin:$kotlin_version"
}
But after changes ext.kotlin_version to lower this warning stay but the red warning is gone
A:
This works for me
buildscript {
ext.kotlin_version = '1.7.20'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.2.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
A:
Go to the file build.gradle, change the version of kotlin.
In case in my flutter project I opened build.gradle and changed
`ext.kotlin_version = '1.5.30'`
to
ext.kotlin_version = '1.6.0'
Here
buildscript {
ext.kotlin_version = '1.6.0'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
Then save and do
flutter clean and flutter run.
Works fine for me.
A:
For macOS you can
rm -r $HOME/.gradle/caches/
or you can invalidate caches
File >> Invalidate caches
| Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15 | In Stripe, my client wants email and cardholder name, but the Stripe payment UI doesn't provide that option in com.stripe.android.view.CardMultilineWidget. I wanted to give it a try with the latest stripe version,
I was using Stripe version (14.1.1). So I updated it to the latest one (16.8.0)
The build showed me the error that it doesn't take minSdkVersion 19. It requires 21 in manifest merger. So I updated minSdkVersion to 21.
I got
caches/transforms-2/files-2.1/4541b0189187e0017d23bbb0afebd16a/jetified-kotlin-stdlib-common-1.5.0.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
I tried changing the Gradle version, but I am still getting the same error. How can I solve the incompatible error and add the email and cardholder name in Stripe?
| [
"Changing this in file build.gradle solved my problem.\nFrom\next.kotlin_version = '1.3.50'\n\nto\next.kotlin_version = '1.6.0'\n\nOr whatever the latest version of Kotlin available and make sure to update Kotlin version on Android Studio as well.\n",
"I had this problem in a Flutter project.\nIn my case, a line for kotlin-gradle-plugin was missing in the Android build.gradle file, so adding ext.kotlin_version = '1.6.10' didn’t fix it.\nAfter adding\nclasspath \"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\"\nthe error was gone.\nFull code section:\nbuildscript {\n ext.kotlin_version = '1.6.10'\n repositories {\n google()\n mavenCentral()\n }\n\n dependencies {\n classpath 'com.android.tools.build:gradle:4.1.0'\n classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\"\n }\n}\n\n",
"If you are facing this error in Flutter build for Android then try to change the Kotlin version to\next.kotlin_version = '1.4.32'\n\n",
"Firstly, go to settings, and then navigate to plugins. Find the Kotlin plugin and update it.\nNext, in gradle files, go to build.gradle (Project: YourApp). Then, change the following code (in buildscript) from:\next.kotlin_version = '1.3.50'\n\nto the latest version, such as:\next.kotlin_version = '1.4.32'\n\nTo know the latest version, go to settings and the plugins, find the Kotlin plugin, and make sure it is updated. The latest version is under JetBrains.\nAfter following the instructions, your error will be resolved.\n",
"Make sure that the Kotlin version of your IDE is the same as the version declared in your gradle.build file.\n",
"It was fixed by updating the Kotlin Gradle plugin version.\nIn the project level build.gradle file, update the following line.\next.kotlin_version = '1.6.10'\n\nYou can find the latest Kotlin Gradle plugin version at\nTools / Build tools / Gradle.\n",
"What do you need to to solve this?\nI was facing this issue since last night. Just navigate through some webpages couldn't get to the exact solution. I finally solved it by these steps:\n\nReplace ext.kotlin_version = '1.3.50' with ext.kotlin_version = '1.4.32' in the build.gradle file.\nClean project → Build the project with Gradle files → Run\n\n",
"Changed the Project build gradle to\n buildscript {\n ext.kotlin_version = '1.7.20'\n repositories {\n google()\n mavenCentral()\n }\n\n dependencies {\n classpath 'com.android.tools.build:gradle:7.2.0'\n classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\"\n }\n}\n\n",
"Although this question has been answered, I think it's worth explaining what is happening\nFor the example:\nThe binary version of its metadata is 1.7.1, expected version is 1.5.1.\n\nThe expected version is the Kotlin for kotlin-gradle-plugin\nThe binary version is the what is downloaded (or previously compiled)\nfor com.android.tools.build:gradle\n<project_dir>/android/build.gradle\nbuildscript {\n ext.kotlin_version = '1.5.20' // <= expected version is 1.5.1\n}\ndependencies {\n classpath 'com.android.tools.build:gradle:7.3.1' // downloads 1.7.1 Metadata\n classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\" // <= 1.5.20 used here\n\nWhy is this Happening So Much?\n\nThe user updates the Kotlin version of the plugin to match the IDE version per the warning.\n\n\n\nThe user updates the android build tools gradle plugin per the warning\n\n\nThis is the WRONG version!\nNow you don't have any warnings, but the version suggested is 7.1.3 which is not the latest. (I don't know why it suggests this older version) 7.3.1 is currently the latest and is meta data 1.7.1, so it will match the Kotlin version of 1.7.20 (which is also metadata 1.7.1)\nWhat else could be wrong?\nDue to caching, gradle may be using an older dependency before you updated. To start clean:\n\ndelete the ~/.gradle/cache directory\ndelete the android/.gradle directory\ndelete the project_dir/build dir\nensure the android/gradle/gradle-wrapper.properies has the correct distributionUrl (currently distributionUrl=https\\://services.gradle.org/distributions/gradle-7.4-bin.zip)\nfrom project_dir do flutter build apk\n\nNOTE: your dependencies may need to be updated if their com.android.tools.build:gradle version is too old. Alternatively, both the kotlin and tools:gradle versions can be downgraded to compatible version that match metadata (although Android Studio will warn for that not matching the IDE Kotlin version)\nHow to Prevent this from happening Again?\n\nUse the same Kotlin version as the IDE normally for ext.kotlin_version. see https://kotlinlang.org/docs/releases.html#release-details\n\nDouble check the com.android.tools.build:gradle version. See https://developer.android.com/studio/releases/gradle-plugin#updating-gradle and https://mvnrepository.com/artifact/com.android.tools.build/gradle?repo=google\n\n\n",
"in my case for\n\nThe binary version of its metadata is 1.7.1, expected version is 1.5.1\n\ngot to (dependencies) inside build.gradle(project) convert from 1.5.x (x) in my case is (20)\nclasspath \"org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.20\"\n\nto 1.7.10\n classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10\"\n\n",
"Another solution is to downgrade androidx.core:core-ktx library to any compatible version. This one worked for kotlin_version = '1.3.31':\ndependencies {\n implementation \"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version\"\n implementation 'androidx.appcompat:appcompat:1.3.1' // The only working for this version (sdk/gradle)\n implementation 'androidx.core:core-ktx:1.0.2' // The only working for this version (sdk/gradle)\n implementation 'androidx.constraintlayout:constraintlayout:1.1.2' // higher versions require min-sdk >= 26\n ...\n}\n\nAndroid SDK: compileSdkVersion 30 and minSdkVersion 19.\nGradle build Tool: com.android.tools.build:gradle:3.3.1.\n",
"Just go to file build.gradle (Project: yourProjectName).\nChange\nplugins {\n ...\n\n id 'org.jetbrains.kotlin.android' version '1.5.x' apply false\n\n ...\n}\n\n(1.5.x means x version number at your case, such as 1.5.1.)\nTo\nplugins {\n ...\n\n id 'org.jetbrains.kotlin.android' version '1.7.10' apply false\n\n ...\n}\n\nIt works in my case...\n",
"Most of the answers here seem to revolve around projects that use Gradle.\nI randomly encountered this problem in IntelliJ IDEA that that was compiling and running a Maven project just fine 5 minutes before - no configuration changes. I introduced a new exception class and this problem popped up.\nI tried invalidating caches and restarting, which didn't resolve the issue - however, disabling and re-enabling the Kotlin plugin resolved the issue.\n",
"Using Flutter, it was fixed by:\n\nUpdating Android Studio packages, specially the Kotlin plugin.\n\nGet the last Kotlin plugin version Nbr from Gradle - Plugin and versions. For now it's 1.6.10.\n\nUpdate <Your_project_name_folder>\\android\\build.gradle file by replacing the old Kotlin version by the new one you got from the web site above.\next.kotlin_version = '<The_new_version_Nbr>' in my case ext.kotlin_version = '1.6.10'\n\nRestart Visual Studio Code.\n\n\nYou're done.\n",
"I faced the same problem in Flutter and I fixed it by going to:\nFile > Settings > Plugins as @Muzzamil said and I checked for the version of Kotlin in my IDE and simply replaced the value in ext.kotlin_version (that is 1.6.10) by that value\next.kotlin_version = '1.6.10'\n\n",
"I have faced this error in IntelliJ IDEA with a Maven project.\nThe solution is about to turn off Kotlin plugin in IntelliJ IDEA if you are not using Kotlin in your project.\nGo to:\nMenu File → Settings → Plugins\nAnd turn off the Kotlin plugin by click on the checkbox. See here:\n\n",
"I have the set minsdk 24 and restart the Android Studio, its working fine.\n",
"project build.gradle:\next.kotlin_version = '1.6.10'\n\napp/build.gradle:\n dependencies {\n // classpath 'com.android.tools.build:gradle:7.1.2'\n // classpath \"org.jetbrains.kotlin:kotlin-gradle- plugin:$kotlin_version\"\n }\n\nBut after changes ext.kotlin_version to lower this warning stay but the red warning is gone\n\n",
"This works for me\n\nbuildscript {\n ext.kotlin_version = '1.7.20'\n repositories {\n google()\n mavenCentral()\n }\n\n dependencies {\n classpath 'com.android.tools.build:gradle:7.2.0'\n classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\"\n }\n}\n\n",
"Go to the file build.gradle, change the version of kotlin.\nIn case in my flutter project I opened build.gradle and changed\n`ext.kotlin_version = '1.5.30'` \n\nto\next.kotlin_version = '1.6.0'\nHere\nbuildscript {\next.kotlin_version = '1.6.0'\n\nrepositories {\n google()\n jcenter()\n}\n\ndependencies {\n classpath 'com.android.tools.build:gradle:4.1.0'\n classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\"\n \n}\n\n}\n\nThen save and do\nflutter clean and flutter run.\nWorks fine for me.\n",
"For macOS you can\nrm -r $HOME/.gradle/caches/\n\nor you can invalidate caches\nFile >> Invalidate caches\n\n"
] | [
423,
44,
29,
21,
16,
13,
9,
9,
9,
7,
4,
4,
2,
2,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"android",
"android_studio",
"kotlin",
"stripe_payments"
] | stackoverflow_0067699823_android_android_studio_kotlin_stripe_payments.txt |
Q:
TypeError: unsupported type for timedelta microseconds component: InstrumentedAttribute
i am also getting error while doing this task.
Models.py
CloudImageMaster
created_tmstmp = Column(DateTime(), default = datetime.now(timezone.utc))
ClientMaster
ttl = Column(BigInteger, nullable=False)
QUERY:-
db.query(CloudImageMaster).join(ClientMaster).filter(
(
CloudImageMaster.created_tmstmp + timedelta(microseconds=ClientMaster.ttl)
) < today
).all()
ERROR MESSAGE :-
TypeError: unsupported type for timedelta microseconds component: InstrumentedAttribute
I tried above. It should work as per the code. What i am doing wrong in this.
A:
Given a filter expression like MyMode.attr == something, the left hand side (LHS) can be thought of as belonging to the database side, the right hand side (RHS) as belonging to the application. What this means is that the RHS must be expressed in what SQLAlchemy regards as database constructs (ORM entities, tables, columns, database functions) while the LHS is expressed as normal Python code.
This means that we can't subtract a timedelta (a Python construct) from a Datetime column (a database construct); we have to convert the timedelta to a database construct - a PostgreSQL interval. We can do this by using the make_interval function, dividing ttl by 1000 as make_interval does not accept a microsecond argument.
from sqlalchemy import func
db.query(CloudImageMaster)
.join(ClientMaster)
.filter(
(
CloudImageMaster.created_tmstmp
+ func.make_interval(0, 0, 0, 0, 0, 0, ClientMaster.ttl /1000)
) < today
).all()
| TypeError: unsupported type for timedelta microseconds component: InstrumentedAttribute | i am also getting error while doing this task.
Models.py
CloudImageMaster
created_tmstmp = Column(DateTime(), default = datetime.now(timezone.utc))
ClientMaster
ttl = Column(BigInteger, nullable=False)
QUERY:-
db.query(CloudImageMaster).join(ClientMaster).filter(
(
CloudImageMaster.created_tmstmp + timedelta(microseconds=ClientMaster.ttl)
) < today
).all()
ERROR MESSAGE :-
TypeError: unsupported type for timedelta microseconds component: InstrumentedAttribute
I tried above. It should work as per the code. What i am doing wrong in this.
| [
"Given a filter expression like MyMode.attr == something, the left hand side (LHS) can be thought of as belonging to the database side, the right hand side (RHS) as belonging to the application. What this means is that the RHS must be expressed in what SQLAlchemy regards as database constructs (ORM entities, tables, columns, database functions) while the LHS is expressed as normal Python code.\nThis means that we can't subtract a timedelta (a Python construct) from a Datetime column (a database construct); we have to convert the timedelta to a database construct - a PostgreSQL interval. We can do this by using the make_interval function, dividing ttl by 1000 as make_interval does not accept a microsecond argument.\nfrom sqlalchemy import func\n\ndb.query(CloudImageMaster)\n .join(ClientMaster)\n .filter(\n (\n CloudImageMaster.created_tmstmp\n + func.make_interval(0, 0, 0, 0, 0, 0, ClientMaster.ttl /1000)\n ) < today\n ).all()\n\n"
] | [
2
] | [] | [] | [
"fastapi",
"postgresql",
"python",
"python_3.x",
"sqlalchemy"
] | stackoverflow_0074623642_fastapi_postgresql_python_python_3.x_sqlalchemy.txt |
Q:
how can I find the gaps between overlapping or non overlapping date ranges in one day?
I have a table that shows the date and time whenever an issuer has called the service. I want to write a query to show in a specific day the requests of an specific issuer has not covered the 24 hours. I will be appreciated if someone can guide me. I am beginner at SQL.
i tried to partition by issuerid and order by startdate and use the lag to compare startdate and enddate with previous record and add a new start and end date but i think i cant get the answer this way.
select r.*,
case
when r.startdate > lag(r.enddate) over(partition by r.issuerid order by r.startdate) then r.startdate
else min(r.startdate) over(partition by r.issuerid order by r.startdate)
end startdate_new,
case
when lag(r.enddate) over(partition by r.issuerid order by r.startdate) is null then r.enddate
when r.enddate <= lag(r.enddate) over(partition by r.issuerid order by r.startdate) then lag(r.enddate) over(partition by r.issuerid order by r.startdate)
when r.enddate > lag(r.enddate) over(partition by r.issuerid order by r.startdate) then r.enddate
end enddate_new
from mht_issuer_revoked_call r
A:
Not quite sure what you are trying to get exactly (there is no expected outcome), but maybe something like this could help:
Sample data
WITH
tbl AS
(
Select 4 "ID", To_Date('25.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 12:00:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 4 "ID", To_Date('25.11.2022 12:00:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('26.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 40 "ID", To_Date('25.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 06:00:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 40 "ID", To_Date('25.11.2022 06:00:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 12:00:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 40 "ID", To_Date('25.11.2022 11:30:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 18:00:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 40 "ID", To_Date('25.11.2022 18:30:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 19:30:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 40 "ID", To_Date('25.11.2022 19:31:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('26.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 50 "ID", To_Date('25.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 12:00:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 50 "ID", To_Date('25.11.2022 11:00:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('26.11.2022 01:30:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 50 "ID", To_Date('25.11.2022 23:10:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 23:30:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 50 "ID", To_Date('25.11.2022 23:30:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 23:45:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 50 "ID", To_Date('25.11.2022 23:50:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 23:55:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual
),
Create CTE (day_tbl) transforming your dates and times to get you dayly events and to record possible extension to next day:
day_tbl AS
( Select
ID,
START_DATE "START_DATE",
ROW_NUMBER() OVER(Partition By ID Order By START_DATE) "CALL_NO",
To_Char(START_DATE, 'hh24:mi:ss') "START_TIME",
END_DATE "END_DATE",
To_Char(END_DATE, 'hh24:mi:ss') "END_TIME",
--
CASE
WHEN (TRUNC(START_DATE) = TRUNC(END_DATE) And To_Char(END_DATE, 'hh24:mi:ss') = '00:00:00')
OR
(TRUNC(END_DATE) - TRUNC(START_DATE) = 1 AND To_Char(END_DATE, 'hh24:mi:ss') = '00:00:00')
THEN TRUNC(START_DATE)
ELSE END_DATE
END "NEW_END_DATE",
CASE
WHEN (TRUNC(START_DATE) = TRUNC(END_DATE) And To_Char(END_DATE, 'hh24:mi:ss') = '00:00:00')
OR
(TRUNC(END_DATE) - TRUNC(START_DATE) = 1 AND To_Char(END_DATE, 'hh24:mi:ss') = '00:00:00')
THEN '24:00:00'
ELSE To_Char(END_DATE, 'hh24:mi:ss')
END "NEW_END_TIME",
--
CASE
WHEN (TRUNC(END_DATE) - TRUNC(START_DATE) = 1 AND To_Char(END_DATE, 'hh24:mi:ss') != '00:00:00')
THEN '00:00:00'
END "NEXT_DAY_TIME_FROM",
CASE
WHEN (TRUNC(END_DATE) - TRUNC(START_DATE) = 1 AND To_Char(END_DATE, 'hh24:mi:ss') != '00:00:00')
THEN To_Char(END_DATE, 'hh24:mi:ss')
END "NEXT_DAY_TIME_UNTIL"
From
tbl
)
Main SQL resulting with events per DAY/ID with information about first and last event times (00 - 24), continuity and extention;
SELECT
ID,
START_DATE,
CALL_NO,
START_TIME "CALL_START_TIME",
NEW_END_TIME "CALL_END_TIME",
MIN(START_TIME) OVER(Partition By ID) "DAY_FIRST_TIME",
MAX(NEW_END_TIME) OVER(Partition By ID) "DAY_LAST_TIME",
CASE
WHEN LAG(NEW_END_TIME, 1, START_TIME) OVER(Partition By ID Order By START_DATE) > START_TIME THEN 'OVERLAP'
WHEN LAG(NEW_END_TIME, 1, START_TIME) OVER(Partition By ID Order By START_DATE) < START_TIME THEN 'GAP'
END "CONTINUITY",
NEXT_DAY_TIME_UNTIL "EXTENDS_TO_NEXT_DAY_TILL"
FROM
day_tbl
ORDER BY
ID,
START_DATE
Result:
ID
START_DATE
CALL_NO
CALL_START_TIME
CALL_END_TIME
DAY_FIRST_TIME
DAY_LAST_TIME
CONTINUITY
EXTENDS_TO_NEXT_DAY_TILL
4
25-NOV-22
1
00:00:00
12:00:00
00:00:00
24:00:00
4
25-NOV-22
2
12:00:00
24:00:00
00:00:00
24:00:00
40
25-NOV-22
1
00:00:00
06:00:00
00:00:00
24:00:00
40
25-NOV-22
2
06:00:00
12:00:00
00:00:00
24:00:00
40
25-NOV-22
3
11:30:00
18:00:00
00:00:00
24:00:00
OVERLAP
40
25-NOV-22
4
18:30:00
19:30:00
00:00:00
24:00:00
GAP
40
25-NOV-22
5
19:31:00
24:00:00
00:00:00
24:00:00
GAP
50
25-NOV-22
1
00:00:00
12:00:00
00:00:00
23:55:00
50
25-NOV-22
2
11:00:00
01:30:00
00:00:00
23:55:00
OVERLAP
01:30:00
50
25-NOV-22
3
23:10:00
23:30:00
00:00:00
23:55:00
GAP
50
25-NOV-22
4
23:30:00
23:45:00
00:00:00
23:55:00
50
25-NOV-22
5
23:50:00
23:55:00
00:00:00
23:55:00
GAP
A:
It's a typical job for MATCH_RECOGNIZE:
WITH tbl(id, start_date, end_date) AS
(
Select 4 "ID", To_Date('25.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 12:00:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 4 "ID", To_Date('25.11.2022 12:00:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('26.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 40 "ID", To_Date('25.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 06:00:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 40 "ID", To_Date('25.11.2022 06:00:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 12:00:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 40 "ID", To_Date('25.11.2022 11:30:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 18:00:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 40 "ID", To_Date('25.11.2022 18:30:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 19:30:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 40 "ID", To_Date('25.11.2022 19:31:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('26.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 50 "ID", To_Date('25.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 12:00:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 50 "ID", To_Date('25.11.2022 11:00:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('26.11.2022 01:30:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 50 "ID", To_Date('25.11.2022 23:10:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 23:30:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 50 "ID", To_Date('25.11.2022 23:30:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 23:45:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual Union All
Select 50 "ID", To_Date('25.11.2022 23:50:00', 'dd.mm.yyyy hh24:mi:ss') "START_DATE", To_Date('25.11.2022 23:55:00', 'dd.mm.yyyy hh24:mi:ss') "END_DATE" From Dual
),
merged_tbl(id,start_date,end_date) AS (
SELECT * FROM (
SELECT t.*, TRUNC(start_date) as sd FROM tbl t
)
MATCH_RECOGNIZE (
PARTITION BY ID
ORDER BY start_date, end_date
MEASURES FIRST(start_date) AS start_date, MAX(end_date)-1/(24*3600) AS end_date
PATTERN( merged* strt )
DEFINE
merged AS MAX(end_date) >= NEXT(start_date)
)
),
alldates(dat) as (
select start_date+level-1
from (select min(trunc(start_date)) as start_date, max(trunc(end_date)) as end_date from merged_tbl)
connect by start_date+level-1 <= end_date
)
select a.*, t.id
from alldates a
join merged_tbl t on dat between start_date and end_date
where end_date < dat+1-1/(24*3600)
;
DAT ID
------------------- ----------
25-11-2022 00:00:00 40
26-11-2022 00:00:00 50
| how can I find the gaps between overlapping or non overlapping date ranges in one day? | I have a table that shows the date and time whenever an issuer has called the service. I want to write a query to show in a specific day the requests of an specific issuer has not covered the 24 hours. I will be appreciated if someone can guide me. I am beginner at SQL.
i tried to partition by issuerid and order by startdate and use the lag to compare startdate and enddate with previous record and add a new start and end date but i think i cant get the answer this way.
select r.*,
case
when r.startdate > lag(r.enddate) over(partition by r.issuerid order by r.startdate) then r.startdate
else min(r.startdate) over(partition by r.issuerid order by r.startdate)
end startdate_new,
case
when lag(r.enddate) over(partition by r.issuerid order by r.startdate) is null then r.enddate
when r.enddate <= lag(r.enddate) over(partition by r.issuerid order by r.startdate) then lag(r.enddate) over(partition by r.issuerid order by r.startdate)
when r.enddate > lag(r.enddate) over(partition by r.issuerid order by r.startdate) then r.enddate
end enddate_new
from mht_issuer_revoked_call r
| [
"Not quite sure what you are trying to get exactly (there is no expected outcome), but maybe something like this could help:\n\nSample data\n\nWITH \n tbl AS\n (\n Select 4 \"ID\", To_Date('25.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 12:00:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 4 \"ID\", To_Date('25.11.2022 12:00:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('26.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 40 \"ID\", To_Date('25.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 06:00:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 40 \"ID\", To_Date('25.11.2022 06:00:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 12:00:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 40 \"ID\", To_Date('25.11.2022 11:30:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 18:00:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 40 \"ID\", To_Date('25.11.2022 18:30:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 19:30:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 40 \"ID\", To_Date('25.11.2022 19:31:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('26.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 50 \"ID\", To_Date('25.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 12:00:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 50 \"ID\", To_Date('25.11.2022 11:00:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('26.11.2022 01:30:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 50 \"ID\", To_Date('25.11.2022 23:10:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 23:30:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 50 \"ID\", To_Date('25.11.2022 23:30:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 23:45:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 50 \"ID\", To_Date('25.11.2022 23:50:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 23:55:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual \n ), \n\n\nCreate CTE (day_tbl) transforming your dates and times to get you dayly events and to record possible extension to next day:\n\n day_tbl AS\n ( Select \n ID,\n START_DATE \"START_DATE\", \n ROW_NUMBER() OVER(Partition By ID Order By START_DATE) \"CALL_NO\",\n To_Char(START_DATE, 'hh24:mi:ss') \"START_TIME\",\n END_DATE \"END_DATE\", \n To_Char(END_DATE, 'hh24:mi:ss') \"END_TIME\",\n --\n CASE \n WHEN (TRUNC(START_DATE) = TRUNC(END_DATE) And To_Char(END_DATE, 'hh24:mi:ss') = '00:00:00') \n OR \n (TRUNC(END_DATE) - TRUNC(START_DATE) = 1 AND To_Char(END_DATE, 'hh24:mi:ss') = '00:00:00')\n THEN TRUNC(START_DATE)\n ELSE END_DATE\n END \"NEW_END_DATE\",\n CASE \n WHEN (TRUNC(START_DATE) = TRUNC(END_DATE) And To_Char(END_DATE, 'hh24:mi:ss') = '00:00:00') \n OR \n (TRUNC(END_DATE) - TRUNC(START_DATE) = 1 AND To_Char(END_DATE, 'hh24:mi:ss') = '00:00:00')\n THEN '24:00:00'\n ELSE To_Char(END_DATE, 'hh24:mi:ss')\n END \"NEW_END_TIME\",\n --\n CASE \n WHEN (TRUNC(END_DATE) - TRUNC(START_DATE) = 1 AND To_Char(END_DATE, 'hh24:mi:ss') != '00:00:00')\n THEN '00:00:00'\n END \"NEXT_DAY_TIME_FROM\",\n CASE \n WHEN (TRUNC(END_DATE) - TRUNC(START_DATE) = 1 AND To_Char(END_DATE, 'hh24:mi:ss') != '00:00:00')\n THEN To_Char(END_DATE, 'hh24:mi:ss')\n END \"NEXT_DAY_TIME_UNTIL\"\n From \n tbl \n )\n\n\nMain SQL resulting with events per DAY/ID with information about first and last event times (00 - 24), continuity and extention;\n\nSELECT\n ID, \n START_DATE,\n CALL_NO,\n START_TIME \"CALL_START_TIME\", \n NEW_END_TIME \"CALL_END_TIME\",\n MIN(START_TIME) OVER(Partition By ID) \"DAY_FIRST_TIME\",\n MAX(NEW_END_TIME) OVER(Partition By ID) \"DAY_LAST_TIME\",\n CASE \n WHEN LAG(NEW_END_TIME, 1, START_TIME) OVER(Partition By ID Order By START_DATE) > START_TIME THEN 'OVERLAP'\n WHEN LAG(NEW_END_TIME, 1, START_TIME) OVER(Partition By ID Order By START_DATE) < START_TIME THEN 'GAP'\n END \"CONTINUITY\",\n NEXT_DAY_TIME_UNTIL \"EXTENDS_TO_NEXT_DAY_TILL\"\nFROM\n day_tbl\nORDER BY\n ID,\n START_DATE\n\nResult:\n\n\n\n\nID\nSTART_DATE\nCALL_NO\nCALL_START_TIME\nCALL_END_TIME\nDAY_FIRST_TIME\nDAY_LAST_TIME\nCONTINUITY\nEXTENDS_TO_NEXT_DAY_TILL\n\n\n\n\n4\n25-NOV-22\n1\n00:00:00\n12:00:00\n00:00:00\n24:00:00\n\n\n\n\n4\n25-NOV-22\n2\n12:00:00\n24:00:00\n00:00:00\n24:00:00\n\n\n\n\n40\n25-NOV-22\n1\n00:00:00\n06:00:00\n00:00:00\n24:00:00\n\n\n\n\n40\n25-NOV-22\n2\n06:00:00\n12:00:00\n00:00:00\n24:00:00\n\n\n\n\n40\n25-NOV-22\n3\n11:30:00\n18:00:00\n00:00:00\n24:00:00\nOVERLAP\n\n\n\n40\n25-NOV-22\n4\n18:30:00\n19:30:00\n00:00:00\n24:00:00\nGAP\n\n\n\n40\n25-NOV-22\n5\n19:31:00\n24:00:00\n00:00:00\n24:00:00\nGAP\n\n\n\n50\n25-NOV-22\n1\n00:00:00\n12:00:00\n00:00:00\n23:55:00\n\n\n\n\n50\n25-NOV-22\n2\n11:00:00\n01:30:00\n00:00:00\n23:55:00\nOVERLAP\n01:30:00\n\n\n50\n25-NOV-22\n3\n23:10:00\n23:30:00\n00:00:00\n23:55:00\nGAP\n\n\n\n50\n25-NOV-22\n4\n23:30:00\n23:45:00\n00:00:00\n23:55:00\n\n\n\n\n50\n25-NOV-22\n5\n23:50:00\n23:55:00\n00:00:00\n23:55:00\nGAP\n\n\n\n\n",
"It's a typical job for MATCH_RECOGNIZE:\nWITH tbl(id, start_date, end_date) AS\n(\n Select 4 \"ID\", To_Date('25.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 12:00:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 4 \"ID\", To_Date('25.11.2022 12:00:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('26.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 40 \"ID\", To_Date('25.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 06:00:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 40 \"ID\", To_Date('25.11.2022 06:00:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 12:00:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 40 \"ID\", To_Date('25.11.2022 11:30:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 18:00:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 40 \"ID\", To_Date('25.11.2022 18:30:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 19:30:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 40 \"ID\", To_Date('25.11.2022 19:31:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('26.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 50 \"ID\", To_Date('25.11.2022 00:00:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 12:00:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 50 \"ID\", To_Date('25.11.2022 11:00:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('26.11.2022 01:30:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 50 \"ID\", To_Date('25.11.2022 23:10:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 23:30:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 50 \"ID\", To_Date('25.11.2022 23:30:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 23:45:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual Union All\n Select 50 \"ID\", To_Date('25.11.2022 23:50:00', 'dd.mm.yyyy hh24:mi:ss') \"START_DATE\", To_Date('25.11.2022 23:55:00', 'dd.mm.yyyy hh24:mi:ss') \"END_DATE\" From Dual \n),\nmerged_tbl(id,start_date,end_date) AS (\n SELECT * FROM (\n SELECT t.*, TRUNC(start_date) as sd FROM tbl t\n ) \n MATCH_RECOGNIZE (\n PARTITION BY ID\n ORDER BY start_date, end_date\n MEASURES FIRST(start_date) AS start_date, MAX(end_date)-1/(24*3600) AS end_date\n PATTERN( merged* strt )\n DEFINE\n merged AS MAX(end_date) >= NEXT(start_date)\n ) \n),\nalldates(dat) as (\n select start_date+level-1 \n from (select min(trunc(start_date)) as start_date, max(trunc(end_date)) as end_date from merged_tbl)\n connect by start_date+level-1 <= end_date\n)\nselect a.*, t.id \nfrom alldates a\njoin merged_tbl t on dat between start_date and end_date\nwhere end_date < dat+1-1/(24*3600)\n ;\n\n\nDAT ID\n------------------- ----------\n25-11-2022 00:00:00 40\n26-11-2022 00:00:00 50\n\n"
] | [
0,
0
] | [] | [] | [
"oracle",
"sql"
] | stackoverflow_0074667324_oracle_sql.txt |
Q:
What's the fastest way to recursively search for files in python?
I need to generate a list of files with paths that contain a certain string by recursively searching. I'm doing this currently like this:
for i in iglob(starting_directory+'/**/*', recursive=True):
if filemask in i.split('\\')[-1]: # ignore directories that contain the filemask
filelist.append(i)
This works, but when crawling a large directory tree, it's woefully slow (~10 minutes). We're on Windows, so doing an external call to the unix find command isn't an option. My understanding is that glob is faster than os.walk.
Is there a faster way of doing this?
A:
Maybe not the answer you were hoping for, but I think these timings are useful. Run on a directory with 15,424 directories totalling 102,799 files (of which 3059 are .py files).
Python 3.6:
import os
import glob
def walk():
pys = []
for p, d, f in os.walk('.'):
for file in f:
if file.endswith('.py'):
pys.append(file)
return pys
def iglob():
pys = []
for file in glob.iglob('**/*', recursive=True):
if file.endswith('.py'):
pys.append(file)
return pys
def iglob2():
pys = []
for file in glob.iglob('**/*.py', recursive=True):
pys.append(file)
return pys
# I also tried pathlib.Path.glob but it was slow and error prone, sadly
%timeit walk()
3.95 s ± 13 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit iglob()
5.01 s ± 19.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit iglob2()
4.36 s ± 34 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Using GNU find (4.6.0) on cygwin (4.6.0-1)
Edit: The below is on WINDOWS, on LINUX I found find to be about 25% faster
$ time find . -name '*.py' > /dev/null
real 0m8.827s
user 0m1.482s
sys 0m7.284s
Seems like os.walk is as good as you can get on windows.
A:
os.walk() uses scandir which is the fastest and we get the file object that can be used for many other purposes as well like, below I am getting the modified time. Below code implement recursive serach using os.scandir()
import os
import time
def scantree(path):
"""Recursively yield DirEntry objects for given directory."""
for entry in os.scandir(path):
if entry.is_dir(follow_symlinks=False):
yield from scantree(entry.path)
else:
yield entry
for entry in scantree('/home/'):
if entry.is_file():
print(entry.path,time.ctime(entry.stat().st_mtime))
| What's the fastest way to recursively search for files in python? | I need to generate a list of files with paths that contain a certain string by recursively searching. I'm doing this currently like this:
for i in iglob(starting_directory+'/**/*', recursive=True):
if filemask in i.split('\\')[-1]: # ignore directories that contain the filemask
filelist.append(i)
This works, but when crawling a large directory tree, it's woefully slow (~10 minutes). We're on Windows, so doing an external call to the unix find command isn't an option. My understanding is that glob is faster than os.walk.
Is there a faster way of doing this?
| [
"Maybe not the answer you were hoping for, but I think these timings are useful. Run on a directory with 15,424 directories totalling 102,799 files (of which 3059 are .py files).\nPython 3.6:\nimport os\nimport glob\n\ndef walk():\n pys = []\n for p, d, f in os.walk('.'):\n for file in f:\n if file.endswith('.py'):\n pys.append(file)\n return pys\n\ndef iglob():\n pys = []\n for file in glob.iglob('**/*', recursive=True):\n if file.endswith('.py'):\n pys.append(file)\n return pys\n\ndef iglob2():\n pys = []\n for file in glob.iglob('**/*.py', recursive=True):\n pys.append(file)\n return pys\n\n# I also tried pathlib.Path.glob but it was slow and error prone, sadly\n\n%timeit walk()\n3.95 s ± 13 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\n%timeit iglob()\n5.01 s ± 19.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\n%timeit iglob2()\n4.36 s ± 34 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\nUsing GNU find (4.6.0) on cygwin (4.6.0-1)\nEdit: The below is on WINDOWS, on LINUX I found find to be about 25% faster\n$ time find . -name '*.py' > /dev/null\n\nreal 0m8.827s\nuser 0m1.482s\nsys 0m7.284s\n\n\nSeems like os.walk is as good as you can get on windows.\n",
"os.walk() uses scandir which is the fastest and we get the file object that can be used for many other purposes as well like, below I am getting the modified time. Below code implement recursive serach using os.scandir()\nimport os\nimport time\ndef scantree(path):\n \"\"\"Recursively yield DirEntry objects for given directory.\"\"\"\n for entry in os.scandir(path):\n if entry.is_dir(follow_symlinks=False):\n yield from scantree(entry.path) \n else:\n yield entry\n \nfor entry in scantree('/home/'):\n if entry.is_file():\n print(entry.path,time.ctime(entry.stat().st_mtime))\n\n"
] | [
27,
0
] | [] | [] | [
"glob",
"python",
"search"
] | stackoverflow_0050948391_glob_python_search.txt |
Q:
printing values django templates using for loop
I have two models interrelated items and broken :
class Items(models.Model):
id = models.AutoField(primary_key=True)
item_name = models.CharField(max_length=50, blank=False)
item_price = models.IntegerField(blank=True)
item_quantity_received = models.IntegerField(blank=False)
item_quantity_available = models.IntegerField(blank=True)
item_purchased_date = models.DateField(auto_now_add=True, blank=False)
item_units = models.CharField(max_length=50, blank=False)
def __str__(self):
return self.item_name
class Broken(models.Model):
item = models.ForeignKey(Items, default=1, on_delete=models.CASCADE)
item_quantity_broken = models.IntegerField(blank=True)
item_broken_date = models.DateField(auto_now_add=True, blank=False)
item_is_broken = models.BooleanField(default=True)
date_repaired = models.DateField(auto_now=True, blank=True)
def __str__(self):
return self.item.item_name
I wrote this view function to retrieve data to a table into a template:
def broken_items(request):
br = Broken.objects.select_related('item').all()
print(br.values_list())
context = {
'title': 'broken',
'items': br,
}
return render(request, 'store/broken.html', context)
this is the executing query:
SELECT "store_broken"."id",
"store_broken"."item_id",
"store_broken"."item_quantity_broken",
"store_broken"."item_broken_date",
"store_broken"."item_is_broken",
"store_broken"."date_repaired",
"store_items"."id",
"store_items"."item_name",
"store_items"."item_price",
"store_items"."item_quantity_received",
"store_items"."item_quantity_available",
"store_items"."item_purchased_date",
"store_items"."item_units"
FROM "store_broken"
INNER JOIN "store_items"
ON ("store_broken"."item_id" = "store_items"."id")
looks like it gives me all the fields I want. In debugger it shows data from both tables,
so I wrote for loop in template,
{% for item in items %}
<tr>
<td>{{item.id}}</td>
<td>{{item.item_id}}</td>
<td>{{item.item_quantity_broken}}</td>
<td>{{item.item_broken_date}}</td>
<td>{{item.item_is_broken}}</td>
<td>{{item.date_repaired}}</td>
<td>{{item.item_name }}</td>
<td>{{item.item_item_quantity_received}}</td>
<td>{{item.item_quantity_available}}</td>
<td>{{item.item_purchased_date}}</td>
<td>{{item.items_item_units}}</td>
</tr>
{% endfor %}
The thing is this loop only gives me data from broken table only. I can't see data from Items table.
can someone help me to find the reason why other details are not showing?
A:
you loop over a List of Broken objects
to access the related item objects
item.item.item_name
A:
Your items query is of Broken objects. So in order to access the Items values you need to change your table. For better understanding change your view like this:
brokens = Broken.objects.select_related('item').all()
context = {
'title': 'broken',
'brokens ': brokens,
}
and then your table:
{% for broken in brokens %}
<tr>
<td>{{broken.id}}</td>
<td>{{broken.item.pk}}</td> # This is the item id
<td>{{broken.item_quantity_broken}}</td>
<td>{{broken.item_broken_date}}</td>
<td>{{broken.item_is_broken}}</td>
<td>{{broken.date_repaired}}</td>
<td>{{broken.item.item_name}}</td>
<td>{{broken.item.item_quantity_received }}</td>
<td>{{broken.item.item_quantity_available}}</td>
<td>{{broken.item.item_purchased_date}}</td>
<td>{{broken.item.items_item_units}}</td>
</tr>
{% endfor %}
| printing values django templates using for loop | I have two models interrelated items and broken :
class Items(models.Model):
id = models.AutoField(primary_key=True)
item_name = models.CharField(max_length=50, blank=False)
item_price = models.IntegerField(blank=True)
item_quantity_received = models.IntegerField(blank=False)
item_quantity_available = models.IntegerField(blank=True)
item_purchased_date = models.DateField(auto_now_add=True, blank=False)
item_units = models.CharField(max_length=50, blank=False)
def __str__(self):
return self.item_name
class Broken(models.Model):
item = models.ForeignKey(Items, default=1, on_delete=models.CASCADE)
item_quantity_broken = models.IntegerField(blank=True)
item_broken_date = models.DateField(auto_now_add=True, blank=False)
item_is_broken = models.BooleanField(default=True)
date_repaired = models.DateField(auto_now=True, blank=True)
def __str__(self):
return self.item.item_name
I wrote this view function to retrieve data to a table into a template:
def broken_items(request):
br = Broken.objects.select_related('item').all()
print(br.values_list())
context = {
'title': 'broken',
'items': br,
}
return render(request, 'store/broken.html', context)
this is the executing query:
SELECT "store_broken"."id",
"store_broken"."item_id",
"store_broken"."item_quantity_broken",
"store_broken"."item_broken_date",
"store_broken"."item_is_broken",
"store_broken"."date_repaired",
"store_items"."id",
"store_items"."item_name",
"store_items"."item_price",
"store_items"."item_quantity_received",
"store_items"."item_quantity_available",
"store_items"."item_purchased_date",
"store_items"."item_units"
FROM "store_broken"
INNER JOIN "store_items"
ON ("store_broken"."item_id" = "store_items"."id")
looks like it gives me all the fields I want. In debugger it shows data from both tables,
so I wrote for loop in template,
{% for item in items %}
<tr>
<td>{{item.id}}</td>
<td>{{item.item_id}}</td>
<td>{{item.item_quantity_broken}}</td>
<td>{{item.item_broken_date}}</td>
<td>{{item.item_is_broken}}</td>
<td>{{item.date_repaired}}</td>
<td>{{item.item_name }}</td>
<td>{{item.item_item_quantity_received}}</td>
<td>{{item.item_quantity_available}}</td>
<td>{{item.item_purchased_date}}</td>
<td>{{item.items_item_units}}</td>
</tr>
{% endfor %}
The thing is this loop only gives me data from broken table only. I can't see data from Items table.
can someone help me to find the reason why other details are not showing?
| [
"you loop over a List of Broken objects\nto access the related item objects\nitem.item.item_name\n",
"Your items query is of Broken objects. So in order to access the Items values you need to change your table. For better understanding change your view like this:\nbrokens = Broken.objects.select_related('item').all()\ncontext = {\n 'title': 'broken',\n 'brokens ': brokens,\n}\n\nand then your table:\n{% for broken in brokens %}\n <tr>\n <td>{{broken.id}}</td>\n <td>{{broken.item.pk}}</td> # This is the item id \n <td>{{broken.item_quantity_broken}}</td>\n <td>{{broken.item_broken_date}}</td>\n <td>{{broken.item_is_broken}}</td>\n <td>{{broken.date_repaired}}</td>\n <td>{{broken.item.item_name}}</td>\n <td>{{broken.item.item_quantity_received }}</td>\n <td>{{broken.item.item_quantity_available}}</td>\n <td>{{broken.item.item_purchased_date}}</td>\n <td>{{broken.item.items_item_units}}</td>\n </tr>\n {% endfor %}\n\n"
] | [
1,
1
] | [] | [] | [
"django",
"django_models",
"django_queryset",
"django_templates",
"python"
] | stackoverflow_0074677397_django_django_models_django_queryset_django_templates_python.txt |
Q:
java.lang.IllegalArgumentException: Not a managed type: @Entity
I am currently testing Kotlin and Gradle for a small API. I want the API to be connected to a local MySQL database and use GraphQL. I am running into a problem right now, which is when I start the application it says java.lang.IllegalArgumentException: Not a managed type: class de.wi2020sebgroup1.nachhilfe.gamification.Stats
I've tried using @EntityScan and @ComponentScan, tried refactoring the packages and I added @javax.persistence.Entity to my Entity. Still, the error persists. Can anyone find something that I am missing?
All the following .kt files lie in the same package
Error Log:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'statsResolver': Unsatisfied dependency expressed through field 'repo': Error creating bean with name 'statsRepository' defined in de.wi2020sebgroup1.nachhilfe.gamification.StatsRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration:
Not a managed type: class de.wi2020sebgroup1.nachhilfe.gamification.Stats
[...]
Caused by: java.lang.IllegalArgumentException: Not a managed type: class de.wi2020sebgroup1.nachhilfe.gamification.Stats
at org.hibernate.metamodel.model.domain.internal.JpaMetamodelImpl.managedType(JpaMetamodelImpl.java:181) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl.managedType(MappingMetamodelImpl.java:496) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl.managedType(MappingMetamodelImpl.java:99) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:77) ~[spring-data-jpa-3.0.0.jar:3.0.0]
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:69) ~[spring-data-jpa-3.0.0.jar:3.0.0]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:246) ~[spring-data-jpa-3.0.0.jar:3.0.0]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:211) ~[spring-data-jpa-3.0.0.jar:3.0.0]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:194) ~[spring-data-jpa-3.0.0.jar:3.0.0]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:81) ~[spring-data-jpa-3.0.0.jar:3.0.0]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:317) ~[spring-data-commons-3.0.0.jar:3.0.0]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:279) ~[spring-data-commons-3.0.0.jar:3.0.0]
at org.springframework.data.util.Lazy.getNullable(Lazy.java:229) ~[spring-data-commons-3.0.0.jar:3.0.0]
at org.springframework.data.util.Lazy.get(Lazy.java:113) ~[spring-data-commons-3.0.0.jar:3.0.0]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:285) ~[spring-data-commons-3.0.0.jar:3.0.0]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:132) ~[spring-data-jpa-3.0.0.jar:3.0.0]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1797) ~[spring-beans-6.0.2.jar:6.0.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1747) ~[spring-beans-6.0.2.jar:6.0.2]
... 35 common frames omitted
build.gradle.kts:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "3.0.0"
id("io.spring.dependency-management") version "1.1.0"
id("org.jetbrains.kotlin.plugin.allopen") version "1.7.21"
kotlin("jvm") version "1.7.21"
kotlin("plugin.spring") version "1.7.21"
kotlin("plugin.jpa") version "1.7.21"
}
allOpen {
annotation("javax.persistence.Entity")
annotation("org.springframework.stereotype.Repository")
annotation("org.springframework.stereotype.Component")
}
group = "de.wi2020sebgroup1.nachhilfe"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_17
repositories {
mavenCentral()
}
dependencies {
implementation("javax:javaee-api:8.0")
implementation("com.graphql-java:graphql-spring-boot-starter:5.0.2")
implementation("com.graphql-java:graphiql-spring-boot-starter:5.0.2")
implementation("com.graphql-java:voyager-spring-boot-starter:5.0.2")
implementation("com.graphql-java:graphql-java-tools:5.2.4")
implementation("org.springframework.data:spring-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-graphql")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.hibernate:hibernate-core:6.1.5.Final")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
developmentOnly("org.springframework.boot:spring-boot-devtools")
runtimeOnly("com.mysql:mysql-connector-j")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.springframework:spring-webflux")
testImplementation("org.springframework.graphql:spring-graphql-test")
testImplementation("org.hibernate:hibernate-testing:6.1.5.Final")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "17"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
Entity that is not a managed type:
package de.wi2020sebgroup1.nachhilfe.gamification
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@Entity
@Table(name="stats")
class Stats(
val userId: String,
val registerDate: String,
val learningPoints: Int,
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
val id: String
)
Main App:
package de.wi2020sebgroup1.nachhilfe.gamification
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.domain.EntityScan
import org.springframework.boot.runApplication
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
@SpringBootApplication
class GamificationApplication
fun main(args: Array<String>) {
runApplication<GamificationApplication>(*args)
}
JPA Repo
package de.wi2020sebgroup1.nachhilfe.gamification
import org.springframework.stereotype.Repository
import org.springframework.data.jpa.repository.JpaRepository
import com.coxautodev.graphql.tools.GraphQLQueryResolver
import de.wi2020sebgroup1.nachhilfe.gamification.Stats
@Repository
interface StatsRepository: JpaRepository < Stats, String > {
fun findByuserId(userId: String): MutableList < Stats >
fun findByid(id: String): MutableList < Stats >
}
GraphQL Resolver
package de.wi2020sebgroup1.nachhilfe.gamification
import org.springframework.stereotype.Component
import org.springframework.beans.factory.annotation.Autowired
import com.coxautodev.graphql.tools.GraphQLQueryResolver
import de.wi2020sebgroup1.nachhilfe.gamification.Stats
import de.wi2020sebgroup1.nachhilfe.gamification.StatsRepository
@Component
class StatsResolver() : GraphQLQueryResolver {
@Autowired
lateinit var repo: StatsRepository
fun stats() = repo.findAll()
fun stat(id: String) = repo.findByid(id)
fun statByUser(userId: String) = repo.findByuserId(userId)
fun add(stats: Stats): Stats {
repo.save(stats)
return stats
}
}
Have a nice weekend! :)
A:
Spring 3.0 works with Jakarta EE 9 instead of Javax EE 8. In order to get the application running I had to include implementation("jakarta.platform:jakarta.jakartaee-web-api:9.0.0") in my build.gradle.kt instead of javax. After changing the imports from javax.persistence to jakarta.persistence it worked fine :)
| java.lang.IllegalArgumentException: Not a managed type: @Entity | I am currently testing Kotlin and Gradle for a small API. I want the API to be connected to a local MySQL database and use GraphQL. I am running into a problem right now, which is when I start the application it says java.lang.IllegalArgumentException: Not a managed type: class de.wi2020sebgroup1.nachhilfe.gamification.Stats
I've tried using @EntityScan and @ComponentScan, tried refactoring the packages and I added @javax.persistence.Entity to my Entity. Still, the error persists. Can anyone find something that I am missing?
All the following .kt files lie in the same package
Error Log:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'statsResolver': Unsatisfied dependency expressed through field 'repo': Error creating bean with name 'statsRepository' defined in de.wi2020sebgroup1.nachhilfe.gamification.StatsRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration:
Not a managed type: class de.wi2020sebgroup1.nachhilfe.gamification.Stats
[...]
Caused by: java.lang.IllegalArgumentException: Not a managed type: class de.wi2020sebgroup1.nachhilfe.gamification.Stats
at org.hibernate.metamodel.model.domain.internal.JpaMetamodelImpl.managedType(JpaMetamodelImpl.java:181) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl.managedType(MappingMetamodelImpl.java:496) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl.managedType(MappingMetamodelImpl.java:99) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:77) ~[spring-data-jpa-3.0.0.jar:3.0.0]
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:69) ~[spring-data-jpa-3.0.0.jar:3.0.0]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:246) ~[spring-data-jpa-3.0.0.jar:3.0.0]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:211) ~[spring-data-jpa-3.0.0.jar:3.0.0]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:194) ~[spring-data-jpa-3.0.0.jar:3.0.0]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:81) ~[spring-data-jpa-3.0.0.jar:3.0.0]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:317) ~[spring-data-commons-3.0.0.jar:3.0.0]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:279) ~[spring-data-commons-3.0.0.jar:3.0.0]
at org.springframework.data.util.Lazy.getNullable(Lazy.java:229) ~[spring-data-commons-3.0.0.jar:3.0.0]
at org.springframework.data.util.Lazy.get(Lazy.java:113) ~[spring-data-commons-3.0.0.jar:3.0.0]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:285) ~[spring-data-commons-3.0.0.jar:3.0.0]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:132) ~[spring-data-jpa-3.0.0.jar:3.0.0]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1797) ~[spring-beans-6.0.2.jar:6.0.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1747) ~[spring-beans-6.0.2.jar:6.0.2]
... 35 common frames omitted
build.gradle.kts:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "3.0.0"
id("io.spring.dependency-management") version "1.1.0"
id("org.jetbrains.kotlin.plugin.allopen") version "1.7.21"
kotlin("jvm") version "1.7.21"
kotlin("plugin.spring") version "1.7.21"
kotlin("plugin.jpa") version "1.7.21"
}
allOpen {
annotation("javax.persistence.Entity")
annotation("org.springframework.stereotype.Repository")
annotation("org.springframework.stereotype.Component")
}
group = "de.wi2020sebgroup1.nachhilfe"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_17
repositories {
mavenCentral()
}
dependencies {
implementation("javax:javaee-api:8.0")
implementation("com.graphql-java:graphql-spring-boot-starter:5.0.2")
implementation("com.graphql-java:graphiql-spring-boot-starter:5.0.2")
implementation("com.graphql-java:voyager-spring-boot-starter:5.0.2")
implementation("com.graphql-java:graphql-java-tools:5.2.4")
implementation("org.springframework.data:spring-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-graphql")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.hibernate:hibernate-core:6.1.5.Final")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
developmentOnly("org.springframework.boot:spring-boot-devtools")
runtimeOnly("com.mysql:mysql-connector-j")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.springframework:spring-webflux")
testImplementation("org.springframework.graphql:spring-graphql-test")
testImplementation("org.hibernate:hibernate-testing:6.1.5.Final")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "17"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
Entity that is not a managed type:
package de.wi2020sebgroup1.nachhilfe.gamification
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@Entity
@Table(name="stats")
class Stats(
val userId: String,
val registerDate: String,
val learningPoints: Int,
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
val id: String
)
Main App:
package de.wi2020sebgroup1.nachhilfe.gamification
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.domain.EntityScan
import org.springframework.boot.runApplication
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
@SpringBootApplication
class GamificationApplication
fun main(args: Array<String>) {
runApplication<GamificationApplication>(*args)
}
JPA Repo
package de.wi2020sebgroup1.nachhilfe.gamification
import org.springframework.stereotype.Repository
import org.springframework.data.jpa.repository.JpaRepository
import com.coxautodev.graphql.tools.GraphQLQueryResolver
import de.wi2020sebgroup1.nachhilfe.gamification.Stats
@Repository
interface StatsRepository: JpaRepository < Stats, String > {
fun findByuserId(userId: String): MutableList < Stats >
fun findByid(id: String): MutableList < Stats >
}
GraphQL Resolver
package de.wi2020sebgroup1.nachhilfe.gamification
import org.springframework.stereotype.Component
import org.springframework.beans.factory.annotation.Autowired
import com.coxautodev.graphql.tools.GraphQLQueryResolver
import de.wi2020sebgroup1.nachhilfe.gamification.Stats
import de.wi2020sebgroup1.nachhilfe.gamification.StatsRepository
@Component
class StatsResolver() : GraphQLQueryResolver {
@Autowired
lateinit var repo: StatsRepository
fun stats() = repo.findAll()
fun stat(id: String) = repo.findByid(id)
fun statByUser(userId: String) = repo.findByuserId(userId)
fun add(stats: Stats): Stats {
repo.save(stats)
return stats
}
}
Have a nice weekend! :)
| [
"Spring 3.0 works with Jakarta EE 9 instead of Javax EE 8. In order to get the application running I had to include implementation(\"jakarta.platform:jakarta.jakartaee-web-api:9.0.0\") in my build.gradle.kt instead of javax. After changing the imports from javax.persistence to jakarta.persistence it worked fine :)\n"
] | [
0
] | [] | [] | [
"gradle",
"kotlin",
"spring",
"spring_boot",
"spring_data_jpa"
] | stackoverflow_0074674544_gradle_kotlin_spring_spring_boot_spring_data_jpa.txt |
Q:
How can I assign and call window variable on Qwik?
I declared the window as global variable on the root file but when I call/assign on that variable, it gives me an error "window is not defined"
I should be able to declare the global window variable, assign any value to it, and call it wherever on the project.
A:
It sounds like you're trying to use the window object in a JavaScript file in a project that is running on Qwiklabs. The window object is a global object in web browsers that represents the browser window. It's not available in Qwiklabs, so you won't be able to use it in your JavaScript code.
If you want to create a global variable in your JavaScript code, you can use the global object. To create a global variable, you can do something like this:
global.myGlobalVariable = 'Hello, world!';
You can then access the value of this global variable from anywhere in your code by using the global object, like this:
console.log(global.myGlobalVariable); // Output: "Hello, world!"
Keep in mind that global variables should be used with caution, as they can make your code difficult to maintain and debug. It's generally a better idea to use more modular, self-contained code that doesn't rely on global variables.
| How can I assign and call window variable on Qwik? | I declared the window as global variable on the root file but when I call/assign on that variable, it gives me an error "window is not defined"
I should be able to declare the global window variable, assign any value to it, and call it wherever on the project.
| [
"It sounds like you're trying to use the window object in a JavaScript file in a project that is running on Qwiklabs. The window object is a global object in web browsers that represents the browser window. It's not available in Qwiklabs, so you won't be able to use it in your JavaScript code.\nIf you want to create a global variable in your JavaScript code, you can use the global object. To create a global variable, you can do something like this:\nglobal.myGlobalVariable = 'Hello, world!';\n\nYou can then access the value of this global variable from anywhere in your code by using the global object, like this:\nconsole.log(global.myGlobalVariable); // Output: \"Hello, world!\"\n\nKeep in mind that global variables should be used with caution, as they can make your code difficult to maintain and debug. It's generally a better idea to use more modular, self-contained code that doesn't rely on global variables.\n"
] | [
0
] | [] | [] | [
"qwik",
"typescript"
] | stackoverflow_0074677709_qwik_typescript.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.