content
stringlengths 86
88.9k
| title
stringlengths 0
150
| question
stringlengths 1
35.8k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 30
130
|
---|---|---|---|---|---|---|---|---|
Q:
When writing a Prediction Equation, can the natural log of the dependent variable be used as a significant predictor?
I am meant to find the the variable that accounts for the highest percentage of variance in dependent variable SalePrice. I use the following code to find that the natural log of the SalePrice had the highest r-square value of over 90%:
proc reg data = proj.team4;
model SalePrice = Log_Price;
title "Regression of SalePrice and Log_Price";
run;
The varaible that came in second was Overall_Qual with a r-square value of about 50%.
I must write a prediction equation that will predict the value of SalePrice given the best significant predictor. Even though the Log_price r-square is much higher, am I right to think that the Overall_Qual variable should be used in the prediction equation instead?
My reasoning being that an equation that looks like this:
SalePrice = m(ln(SalePrice)) + b
would never predict the value of SalePrice since the value of SalePrice is needed in order to carry out the equation.
A:
Though this mathematically makes some sense to try and fit any function over a domain by a linear function, this is statistical nonsense, because it is not telling anything about what determines SalesPrice.
|
When writing a Prediction Equation, can the natural log of the dependent variable be used as a significant predictor?
|
I am meant to find the the variable that accounts for the highest percentage of variance in dependent variable SalePrice. I use the following code to find that the natural log of the SalePrice had the highest r-square value of over 90%:
proc reg data = proj.team4;
model SalePrice = Log_Price;
title "Regression of SalePrice and Log_Price";
run;
The varaible that came in second was Overall_Qual with a r-square value of about 50%.
I must write a prediction equation that will predict the value of SalePrice given the best significant predictor. Even though the Log_price r-square is much higher, am I right to think that the Overall_Qual variable should be used in the prediction equation instead?
My reasoning being that an equation that looks like this:
SalePrice = m(ln(SalePrice)) + b
would never predict the value of SalePrice since the value of SalePrice is needed in order to carry out the equation.
|
[
"Though this mathematically makes some sense to try and fit any function over a domain by a linear function, this is statistical nonsense, because it is not telling anything about what determines SalesPrice.\n"
] |
[
0
] |
[] |
[] |
[
"linear_regression",
"sas"
] |
stackoverflow_0074663504_linear_regression_sas.txt
|
Q:
Iterate over list selecting multiple elements at a time in Python
I have a list, from which I would like to iterate over slices of a certain length, overlapping each other by the largest amount possible, for example:
>>> seq = 'ABCDEF'
>>> [''.join(x) for x in zip(seq, seq[1:], seq[2:])]
['ABC', 'BCD', 'CDE', 'DEF']
In other words, is there a shorthand for zip(seq, seq[1:], seq[2:]) where you can specify the length of each sub-sequence?
A:
Not an elegant solution, but this works:
seq = 'ABCDEF'
n=3
[seq[i:i+n] for i in range(0, len(seq)+1-n)]
A:
[seq[i:i+3] for i in range(len(seq)-2)] is the Python code for something similar.
The far more elegant and recommended version of this is to use the itertools library from Python (seriously, why do they not just include this function in the library?).
In this case, you would instead use something similar to the pairwise function provided in the documentation.
from itertools import tee
def tripletWise(iterable):
"s -> (s0,s1,s2), (s1,s2,s3), (s2,s3,s4), ..."
a, b, c = tee(iterable, 3)
next(b, None)
next(c, None)
next(c, None)
return zip(a, b)
[''.join(i) for i in tripletWise('ABCDEF')]
> ['ABC', 'BCD', 'CDE', 'DEF']
You can also create a more general function to chunk the list into however many elements you want to select at a time.
def nWise(iterable, n=2):
iterableList = tee(iterable, n)
for i in range(len(iterableList)):
for j in range(i):
next(iterableList[i], None)
return zip(*iterableList)
[''.join(i) for i in nWise('ABCDEF', 4)]
> ['ABCD', 'BCDE', 'CDEF']
A:
Use grouper() in the itertools examples. Specifically grouper(<iter>,3).
https://docs.python.org/3/library/itertools.html#itertools-recipes
Or, from the same page, another recommendation is installing more-itertools. Then you can use ichunked() or chunked().
https://pypi.org/project/more-itertools/
|
Iterate over list selecting multiple elements at a time in Python
|
I have a list, from which I would like to iterate over slices of a certain length, overlapping each other by the largest amount possible, for example:
>>> seq = 'ABCDEF'
>>> [''.join(x) for x in zip(seq, seq[1:], seq[2:])]
['ABC', 'BCD', 'CDE', 'DEF']
In other words, is there a shorthand for zip(seq, seq[1:], seq[2:]) where you can specify the length of each sub-sequence?
|
[
"Not an elegant solution, but this works:\nseq = 'ABCDEF'\nn=3\n[seq[i:i+n] for i in range(0, len(seq)+1-n)]\n\n",
"[seq[i:i+3] for i in range(len(seq)-2)] is the Python code for something similar.\nThe far more elegant and recommended version of this is to use the itertools library from Python (seriously, why do they not just include this function in the library?).\nIn this case, you would instead use something similar to the pairwise function provided in the documentation.\nfrom itertools import tee\ndef tripletWise(iterable):\n \"s -> (s0,s1,s2), (s1,s2,s3), (s2,s3,s4), ...\"\n a, b, c = tee(iterable, 3)\n next(b, None)\n next(c, None)\n next(c, None)\n return zip(a, b)\n\n[''.join(i) for i in tripletWise('ABCDEF')]\n> ['ABC', 'BCD', 'CDE', 'DEF']\n\nYou can also create a more general function to chunk the list into however many elements you want to select at a time.\ndef nWise(iterable, n=2):\n iterableList = tee(iterable, n)\n for i in range(len(iterableList)):\n for j in range(i):\n next(iterableList[i], None)\n return zip(*iterableList)\n\n[''.join(i) for i in nWise('ABCDEF', 4)]\n> ['ABCD', 'BCDE', 'CDEF']\n\n",
"Use grouper() in the itertools examples. Specifically grouper(<iter>,3).\nhttps://docs.python.org/3/library/itertools.html#itertools-recipes\nOr, from the same page, another recommendation is installing more-itertools. Then you can use ichunked() or chunked().\nhttps://pypi.org/project/more-itertools/\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"iteration",
"list",
"python",
"python_3.x",
"sequence"
] |
stackoverflow_0044765896_iteration_list_python_python_3.x_sequence.txt
|
Q:
How to run a cron-job/worker every hour on a next js app serverside?
I'm building multiple Nextjs apps for different subdomains of the same site. We have a REST API backend which has an app-info endpoint that gives me some important info about SEO and some more stuff. So I have to render these data on server side. The thing is these data won't change often (they are updated by an admin if needed) so There is no need to use getServerSideProps on every page or App.getInitialProps. I just need to call this endpoint every hour and create/update a json file based on these data. How can I achieve such behavior? By the way I am not deploying these sites using Vercel and we use our own servers.
I also tried this tutorial but it didn't work properly. It did run the worker.js file successfully but I couldn't open website within browser. After adding webpack part in next.config.js the website stopped working.
Note: I need to have access to env variables so I can't use this solution. And since we have multiple subdomains and every one of them has a test and production server, it will be so hard for me to use cron-job.org or similar solutions. I want to be able d to have the cron job alongside Next js and run it using a single command (npm start for example to run both the job and Next js server)
A:
You are looking for a way to run a server-side process that can update a JSON file without using a third-party service.
So to achieve this use Node.js's built-in setInterval function to schedule a task to run every hour.
You can create a separate file, that exports a function that calls your app-info endpoint and saves the data to a JSON file.
Then, in your main server file you can import this function and use setInterval to run it every hour.
So think like you have 1 json and 1 server.js, this is the update-json.js :
const axios = require("axios");
const fs = require("fs");
const updateJson = async () => {
// Call your app-info endpoint and save the data to a variable
const { data } = await axios.get("http://your-api-endpoint/app-info");
// Write the data to a JSON file
fs.writeFile("app-info.json", JSON.stringify(data), (err) => {
if (err) {
console.error("Error writing JSON file", err);
}
});
};
module.exports = updateJson;
server.js
const next = require("next");
const http = require("http");
const { updateJson } = require("./update-json");
|
How to run a cron-job/worker every hour on a next js app serverside?
|
I'm building multiple Nextjs apps for different subdomains of the same site. We have a REST API backend which has an app-info endpoint that gives me some important info about SEO and some more stuff. So I have to render these data on server side. The thing is these data won't change often (they are updated by an admin if needed) so There is no need to use getServerSideProps on every page or App.getInitialProps. I just need to call this endpoint every hour and create/update a json file based on these data. How can I achieve such behavior? By the way I am not deploying these sites using Vercel and we use our own servers.
I also tried this tutorial but it didn't work properly. It did run the worker.js file successfully but I couldn't open website within browser. After adding webpack part in next.config.js the website stopped working.
Note: I need to have access to env variables so I can't use this solution. And since we have multiple subdomains and every one of them has a test and production server, it will be so hard for me to use cron-job.org or similar solutions. I want to be able d to have the cron job alongside Next js and run it using a single command (npm start for example to run both the job and Next js server)
|
[
"You are looking for a way to run a server-side process that can update a JSON file without using a third-party service.\nSo to achieve this use Node.js's built-in setInterval function to schedule a task to run every hour.\nYou can create a separate file, that exports a function that calls your app-info endpoint and saves the data to a JSON file.\nThen, in your main server file you can import this function and use setInterval to run it every hour.\nSo think like you have 1 json and 1 server.js, this is the update-json.js :\nconst axios = require(\"axios\");\nconst fs = require(\"fs\");\n\nconst updateJson = async () => {\n // Call your app-info endpoint and save the data to a variable\n const { data } = await axios.get(\"http://your-api-endpoint/app-info\");\n\n // Write the data to a JSON file\n fs.writeFile(\"app-info.json\", JSON.stringify(data), (err) => {\n if (err) {\n console.error(\"Error writing JSON file\", err);\n }\n });\n};\n\nmodule.exports = updateJson;\n\nserver.js\nconst next = require(\"next\");\nconst http = require(\"http\");\nconst { updateJson } = require(\"./update-json\");\n\n"
] |
[
0
] |
[] |
[] |
[
"cron",
"next.js",
"node.js",
"reactjs"
] |
stackoverflow_0074670550_cron_next.js_node.js_reactjs.txt
|
Q:
What is the difference between multidimensional knapsack problem and 0/1 multidimensional knapsack problem?
What is different between multidimensional knapsack algorithm (MKP) and 0/1 multidimensional knapsack (0/1 KP) algorithm? And what is goal in MKP? And how can I solve it?
A:
In the multidimensional knapsack problem, each item can be taken multiple times, whereas in the 0/1 multidimensional knapsack problem, each item can only be taken once. This means that in the 0/1 version of the problem, the goal is to maximize the total value of items that can be included in the knapsack without exceeding the capacity of any of its dimensions, whereas in the regular multidimensional knapsack problem, the goal is to maximize the total value of items that can be included in the knapsack, subject to the constraint that the total number of each item taken must not exceed a specified quantity. The 0/1 version of the problem is typically considered to be a harder variant of the problem, because it requires a more careful and precise optimization of the items that are included in the knapsack.
There are several approaches that can be used to solve the multidimensional knapsack problem. One common approach is to use a dynamic programming algorithm, in which the solution is built up incrementally by considering the items one at a time and deciding whether or not to include each one in the knapsack. Another approach is to use a branch and bound algorithm, in which the search space is explored by considering all possible combinations of items and pruning branches of the search tree that cannot lead to a better solution. Other methods that can be used to solve the problem include heuristic algorithms, local search algorithms, and approximation algorithms. The choice of solution approach will depend on the specific characteristics of the problem instance, such as the number of items, the number of dimensions, and the capacity of each dimension.
N = 5, Weights = [4, 6, 8, 9, 10], Profits = [20, 30, 70, 98, 30], Capacity = [17, 30, 8]
We can use a dynamic programming algorithm to solve this problem. The algorithm would work by considering the items one at a time, and at each step, it would decide whether or not to include the current item in the knapsack. It would keep track of the maximum total value that can be achieved for each combination of items and capacities, and it would use this information to make decisions about which items to include in the knapsack.
To implement the algorithm, we would need to create a 3-dimensional array to store the maximum total value that can be achieved for each combination of items and capacities. The array would have five rows (one for each item), three columns (one for each dimension), and 31 entries in each column (corresponding to the maximum capacity of each dimension). We would initialize the array with zeros, and then we would iterate over the items, starting with the first one. At each step, we would consider all possible combinations of items and capacities, and we would update the array with the maximum total value that can be achieved by including the current item in the knapsack.
Once we have completed the iteration over all items, we would have the solution to the problem, which would be the maximum total value that can be achieved for the given items and capacities. We could then use this solution to determine which items to include in the knapsack in order to maximize its value.
Of course, this is just one possible approach to solving the problem using the multidimensional knapsack algorithm. There may be other solutions that use different algorithms or data structures, and the specific approach that you choose will depend on the characteristics of the problem and your own preferences and design choices.
|
What is the difference between multidimensional knapsack problem and 0/1 multidimensional knapsack problem?
|
What is different between multidimensional knapsack algorithm (MKP) and 0/1 multidimensional knapsack (0/1 KP) algorithm? And what is goal in MKP? And how can I solve it?
|
[
"In the multidimensional knapsack problem, each item can be taken multiple times, whereas in the 0/1 multidimensional knapsack problem, each item can only be taken once. This means that in the 0/1 version of the problem, the goal is to maximize the total value of items that can be included in the knapsack without exceeding the capacity of any of its dimensions, whereas in the regular multidimensional knapsack problem, the goal is to maximize the total value of items that can be included in the knapsack, subject to the constraint that the total number of each item taken must not exceed a specified quantity. The 0/1 version of the problem is typically considered to be a harder variant of the problem, because it requires a more careful and precise optimization of the items that are included in the knapsack.\nThere are several approaches that can be used to solve the multidimensional knapsack problem. One common approach is to use a dynamic programming algorithm, in which the solution is built up incrementally by considering the items one at a time and deciding whether or not to include each one in the knapsack. Another approach is to use a branch and bound algorithm, in which the search space is explored by considering all possible combinations of items and pruning branches of the search tree that cannot lead to a better solution. Other methods that can be used to solve the problem include heuristic algorithms, local search algorithms, and approximation algorithms. The choice of solution approach will depend on the specific characteristics of the problem instance, such as the number of items, the number of dimensions, and the capacity of each dimension.\n\nN = 5, Weights = [4, 6, 8, 9, 10], Profits = [20, 30, 70, 98, 30], Capacity = [17, 30, 8]\n\nWe can use a dynamic programming algorithm to solve this problem. The algorithm would work by considering the items one at a time, and at each step, it would decide whether or not to include the current item in the knapsack. It would keep track of the maximum total value that can be achieved for each combination of items and capacities, and it would use this information to make decisions about which items to include in the knapsack.\nTo implement the algorithm, we would need to create a 3-dimensional array to store the maximum total value that can be achieved for each combination of items and capacities. The array would have five rows (one for each item), three columns (one for each dimension), and 31 entries in each column (corresponding to the maximum capacity of each dimension). We would initialize the array with zeros, and then we would iterate over the items, starting with the first one. At each step, we would consider all possible combinations of items and capacities, and we would update the array with the maximum total value that can be achieved by including the current item in the knapsack.\nOnce we have completed the iteration over all items, we would have the solution to the problem, which would be the maximum total value that can be achieved for the given items and capacities. We could then use this solution to determine which items to include in the knapsack in order to maximize its value.\nOf course, this is just one possible approach to solving the problem using the multidimensional knapsack algorithm. There may be other solutions that use different algorithms or data structures, and the specific approach that you choose will depend on the characteristics of the problem and your own preferences and design choices.\n"
] |
[
1
] |
[] |
[] |
[
"algorithm",
"knapsack_problem"
] |
stackoverflow_0074670501_algorithm_knapsack_problem.txt
|
Q:
Move and resize XMonad window - RationalRect call compiler error
to send the focused window to the center of the screen I have the following configuration
main = do
xmonad $ docks def
{ manageHook = myManageHook <+> manageHook def
, layoutHook = avoidStruts $ layoutHook def
, logHook = dynamicLogWithPP xmobarPP
, terminal = myTerminal
} `additionalKeys`
[ ((myModkey , xK_space), spawn myTerminal )
, ((myModkey , xK_0), withFocused (keysMoveWindowTo (512,384) (0, 0)))
]
I would remove the call to keysMoveWindowTo because it does not allow to set the window size (...) but only specify dx and dy; than I would like to use:
((myModkey , xK_0), withFocused (doRectFloat (RationalRect (1 % 4) (1 % 4) (1 % 2) (1 % 2))))
but the compiler says:
xmonad.hs:87:58: error:
Data constructor not in scope:
RationalRect
:: Ratio a0
87 |, ((myModkey , xK_0), withFocused (doRectFloat (RationalRect (1 % 4) (1 % 4) (1 % 2) (1 % 2))))
What is the correct way to bind keys with doRectFloat function?
Thanks
Nello
A:
doRectFloat does not provide an X operation needed by withFocused.
Enhancing your previous solution, you could add keysResizeWindow to do the resizing, e.g.
, ((myModkey , xK_0), withFocused (
keysMoveWindowTo (512,384) (1%2, 1%2) >> keysResizeWindow (512, 384) (1%2, 1%2)
))
|
Move and resize XMonad window - RationalRect call compiler error
|
to send the focused window to the center of the screen I have the following configuration
main = do
xmonad $ docks def
{ manageHook = myManageHook <+> manageHook def
, layoutHook = avoidStruts $ layoutHook def
, logHook = dynamicLogWithPP xmobarPP
, terminal = myTerminal
} `additionalKeys`
[ ((myModkey , xK_space), spawn myTerminal )
, ((myModkey , xK_0), withFocused (keysMoveWindowTo (512,384) (0, 0)))
]
I would remove the call to keysMoveWindowTo because it does not allow to set the window size (...) but only specify dx and dy; than I would like to use:
((myModkey , xK_0), withFocused (doRectFloat (RationalRect (1 % 4) (1 % 4) (1 % 2) (1 % 2))))
but the compiler says:
xmonad.hs:87:58: error:
Data constructor not in scope:
RationalRect
:: Ratio a0
87 |, ((myModkey , xK_0), withFocused (doRectFloat (RationalRect (1 % 4) (1 % 4) (1 % 2) (1 % 2))))
What is the correct way to bind keys with doRectFloat function?
Thanks
Nello
|
[
"doRectFloat does not provide an X operation needed by withFocused.\nEnhancing your previous solution, you could add keysResizeWindow to do the resizing, e.g.\n, ((myModkey , xK_0), withFocused (\n keysMoveWindowTo (512,384) (1%2, 1%2) >> keysResizeWindow (512, 384) (1%2, 1%2)\n ))\n\n"
] |
[
0
] |
[] |
[] |
[
"compiler_errors",
"haskell",
"xmonad"
] |
stackoverflow_0074670390_compiler_errors_haskell_xmonad.txt
|
Q:
“Illegal type synonym family application in instance” with functional dependency
I have a multi-parameter typeclass with a functional dependency:
class Multi a b | a -> b
I also have a simple, non-injective type synonym family:
type family Fam a
I want to write an instance of Multi that uses Fam in the second parameter, like this:
instance Multi (Maybe a) (Fam a)
However, this instance is not accepted. GHC complains with the following error message:
error:
• Illegal type synonym family application in instance: Fam a
• In the instance declaration for ‘Multi (Maybe a) (Fam a)’
Fortunately, there is a workaround. I can perform a usual trick for moving a type out of the instance head and into an equality constraint:
instance (b ~ Fam a) => Multi (Maybe a) b
This instance is accepted! However, I got to thinking, and I started to wonder why this transformation could not be applied to all instances of Multi. After all, doesn’t the functional dependency imply that there can only be one b per a, anyway? In this situation, it seems like there is no reason that GHC should reject my first instance.
I found GHC Trac ticket #3485, which describes a similar situation, but that typeclass did not involve a functional dependency, so the ticket was (rightfully) closed as invalid. In my situation, however, I think the functional dependency avoids the problem described in the ticket. Is there anything I’m overlooking, or is this really an oversight/missing feature in GHC?
A:
Currently, GHC does not support type synonym families in the second parameter of an instance declaration if there is a functional dependency in the typeclass. This is because type synonym families are not fully expanded when they appear in instance heads, so GHC cannot guarantee that there is only one possible type for the second parameter.
As a workaround, you can use an equality constraint as you have done in your example, which allows you to move the type synonym family outside of the instance head and into the constraint. This will allow the instance to be accepted by GHC.
|
“Illegal type synonym family application in instance” with functional dependency
|
I have a multi-parameter typeclass with a functional dependency:
class Multi a b | a -> b
I also have a simple, non-injective type synonym family:
type family Fam a
I want to write an instance of Multi that uses Fam in the second parameter, like this:
instance Multi (Maybe a) (Fam a)
However, this instance is not accepted. GHC complains with the following error message:
error:
• Illegal type synonym family application in instance: Fam a
• In the instance declaration for ‘Multi (Maybe a) (Fam a)’
Fortunately, there is a workaround. I can perform a usual trick for moving a type out of the instance head and into an equality constraint:
instance (b ~ Fam a) => Multi (Maybe a) b
This instance is accepted! However, I got to thinking, and I started to wonder why this transformation could not be applied to all instances of Multi. After all, doesn’t the functional dependency imply that there can only be one b per a, anyway? In this situation, it seems like there is no reason that GHC should reject my first instance.
I found GHC Trac ticket #3485, which describes a similar situation, but that typeclass did not involve a functional dependency, so the ticket was (rightfully) closed as invalid. In my situation, however, I think the functional dependency avoids the problem described in the ticket. Is there anything I’m overlooking, or is this really an oversight/missing feature in GHC?
|
[
"Currently, GHC does not support type synonym families in the second parameter of an instance declaration if there is a functional dependency in the typeclass. This is because type synonym families are not fully expanded when they appear in instance heads, so GHC cannot guarantee that there is only one possible type for the second parameter.\nAs a workaround, you can use an equality constraint as you have done in your example, which allows you to move the type synonym family outside of the instance head and into the constraint. This will allow the instance to be accepted by GHC.\n"
] |
[
0
] |
[] |
[] |
[
"functional_dependencies",
"haskell",
"type_families"
] |
stackoverflow_0045360959_functional_dependencies_haskell_type_families.txt
|
Q:
Cannot load Pinia in Nuxt3
I am trying to set up Nuxt3 to work with Pinia.
Steps Taken:
Started with an active nuxt3 project
ran npm install @pinia/nuxt
this failed, with a dependency error, so re-ran with npm install @pinia/nuxt --legacy-peer-deps, which worked fine
added pinia to my nuxt.config.ts, which now looks like:
import { defineNuxtConfig } from 'nuxt'
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
meta: {
link: [
{
rel: "stylesheet",
href:"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
}
],
script: [
{ src: 'https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js', integrity: 'sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2', crossorigin: 'anonymous' }
]
},
ssr: false,
buildModules: ['@pinia/nuxt'],
base: '/',
})
restarted the server
got the following error:
GET http://localhost:3000/_nuxt/@id/pinia/dist/pinia.mjs net::ERR_ABORTED 404 (Not Found)
I've been googling around, and can't figure out what's broken here... I tried taking out the 'base' argument in nuxt.config.ts, and that didn't help either. If I take out the pinia declaration everything works fine.
A:
Resolved by running:
npm install pinia @pinia/nuxt @nuxtjs/composition-api --legacy-peer-deps
I guess I was missing the actual pinia library
A:
i had a same problem and solve it install with
yarn add @pinia/nuxt
instead npm
|
Cannot load Pinia in Nuxt3
|
I am trying to set up Nuxt3 to work with Pinia.
Steps Taken:
Started with an active nuxt3 project
ran npm install @pinia/nuxt
this failed, with a dependency error, so re-ran with npm install @pinia/nuxt --legacy-peer-deps, which worked fine
added pinia to my nuxt.config.ts, which now looks like:
import { defineNuxtConfig } from 'nuxt'
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
meta: {
link: [
{
rel: "stylesheet",
href:"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
}
],
script: [
{ src: 'https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js', integrity: 'sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2', crossorigin: 'anonymous' }
]
},
ssr: false,
buildModules: ['@pinia/nuxt'],
base: '/',
})
restarted the server
got the following error:
GET http://localhost:3000/_nuxt/@id/pinia/dist/pinia.mjs net::ERR_ABORTED 404 (Not Found)
I've been googling around, and can't figure out what's broken here... I tried taking out the 'base' argument in nuxt.config.ts, and that didn't help either. If I take out the pinia declaration everything works fine.
|
[
"Resolved by running:\nnpm install pinia @pinia/nuxt @nuxtjs/composition-api --legacy-peer-deps\nI guess I was missing the actual pinia library\n",
"i had a same problem and solve it install with\nyarn add @pinia/nuxt\ninstead npm\n"
] |
[
10,
0
] |
[] |
[] |
[
"nuxtjs3",
"pinia",
"vuejs3"
] |
stackoverflow_0072778412_nuxtjs3_pinia_vuejs3.txt
|
Q:
Java Reactive Way to read lines of a File
So I started to play with the Advent of Code and I would like to use the project reactor for this to find the solutions in a reactive way.
I have implemented a solutions that works partially but not quite how I want it. Because it can also read lines partially if there is no more space in the buffer.
The Input to run the following function you can find here: https://adventofcode.com/2022/day/1/input
public static Flux<String> getLocalInputForStackOverflow(String filePath) throws IOException {
Path dayPath = Path.of(filePath);
FileOutputStream resultDay = new FileOutputStream(basePath.resolve("result_day.txt").toFile());
return DataBufferUtils
.readAsynchronousFileChannel(
() -> AsynchronousFileChannel.open(dayPath),
new DefaultDataBufferFactory(),
64)
.map(DataBuffer::asInputStream)
.map(db -> {
try {
resultDay.write(db.readAllBytes());
resultDay.write("\n".getBytes());
return db;
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.map(InputStreamReader::new)
.map(is ->new BufferedReader(is).lines())
.flatMap(Flux::fromStream);
}
The point of this function is to read the lines of the files in a reactive way.
I used the FileOutputStream to write what I read into another file and the compare the resulted file with the original, because I noticed that some lines are only partially read if there is no more space in the buffer. So the try-catch .map() can be ignored
My questions here would:
Is there a more optimal way to read files asynchronously in a Reactive way?
Is there a more optimal way to read a file asyncronously line by line with a limited buffer and make sure that only whole lines are read?
Workarounds that I've found are:
Increased the buffer to read the whole file in 1 run -> Not optimal solution
Use the following functions, but this raise a warning:
Possibly blocking call in non-blocking context could lead to thread starvation
public static Flux<String> getLocalInput1(int day ) throws IOException {
Path dayPath = getFilePath(day);
return Flux.using(() -> Files.lines(dayPath),
Flux::fromStream,
BaseStream::close);
}
A:
You're almost there. Just use BufferedReader instead of Files.lines.
In Spring Webflux, the optimal way to read files asynchronously in a reactive way is to use the Reactor Core library's Flux.using method. It creates a Flux that consumes a resource, performs some operations on it, and then cleans up the resource when the Flux is complete.
Example of reading a file asynchronously and reactively:
Flux<String> flux = Flux.using(
// resource factory creates FileReader instance
() -> new FileReader("/path/to/file.txt"),
// transformer function turns the FileReader into a Flux
reader -> Flux.fromStream(new BufferedReader(reader).lines()),
// resource cleanup function closes the FileReader when the Flux is complete
reader -> reader.close()
);
Subscribe to the Flux and consume the lines of the file as they are emitted; this will print each line of the file to the console as it is read from the file.
flux.subscribe(line -> System.out.println(line));
In similar way we can solve it controlling each line explicitly:
Flux<String> flux = Flux.generate(
() -> new BufferedReader(new FileReader("/path/to/file.txt")),
// generator function reads a line from the file and emits it
(bufferedReader, sink) -> {
String line = bufferedReader.readLine();
if (line != null) {
sink.next(line);
} else {
sink.complete();
}
},
reader -> Mono.fromRunnable(() -> {
try {
reader.close();
} catch (IOException e) {
// Handle exception
}
})
);
|
Java Reactive Way to read lines of a File
|
So I started to play with the Advent of Code and I would like to use the project reactor for this to find the solutions in a reactive way.
I have implemented a solutions that works partially but not quite how I want it. Because it can also read lines partially if there is no more space in the buffer.
The Input to run the following function you can find here: https://adventofcode.com/2022/day/1/input
public static Flux<String> getLocalInputForStackOverflow(String filePath) throws IOException {
Path dayPath = Path.of(filePath);
FileOutputStream resultDay = new FileOutputStream(basePath.resolve("result_day.txt").toFile());
return DataBufferUtils
.readAsynchronousFileChannel(
() -> AsynchronousFileChannel.open(dayPath),
new DefaultDataBufferFactory(),
64)
.map(DataBuffer::asInputStream)
.map(db -> {
try {
resultDay.write(db.readAllBytes());
resultDay.write("\n".getBytes());
return db;
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.map(InputStreamReader::new)
.map(is ->new BufferedReader(is).lines())
.flatMap(Flux::fromStream);
}
The point of this function is to read the lines of the files in a reactive way.
I used the FileOutputStream to write what I read into another file and the compare the resulted file with the original, because I noticed that some lines are only partially read if there is no more space in the buffer. So the try-catch .map() can be ignored
My questions here would:
Is there a more optimal way to read files asynchronously in a Reactive way?
Is there a more optimal way to read a file asyncronously line by line with a limited buffer and make sure that only whole lines are read?
Workarounds that I've found are:
Increased the buffer to read the whole file in 1 run -> Not optimal solution
Use the following functions, but this raise a warning:
Possibly blocking call in non-blocking context could lead to thread starvation
public static Flux<String> getLocalInput1(int day ) throws IOException {
Path dayPath = getFilePath(day);
return Flux.using(() -> Files.lines(dayPath),
Flux::fromStream,
BaseStream::close);
}
|
[
"You're almost there. Just use BufferedReader instead of Files.lines.\nIn Spring Webflux, the optimal way to read files asynchronously in a reactive way is to use the Reactor Core library's Flux.using method. It creates a Flux that consumes a resource, performs some operations on it, and then cleans up the resource when the Flux is complete.\nExample of reading a file asynchronously and reactively:\nFlux<String> flux = Flux.using(\n\n // resource factory creates FileReader instance\n () -> new FileReader(\"/path/to/file.txt\"),\n\n // transformer function turns the FileReader into a Flux\n reader -> Flux.fromStream(new BufferedReader(reader).lines()),\n\n // resource cleanup function closes the FileReader when the Flux is complete\n reader -> reader.close()\n);\n\nSubscribe to the Flux and consume the lines of the file as they are emitted; this will print each line of the file to the console as it is read from the file.\nflux.subscribe(line -> System.out.println(line));\n\n\nIn similar way we can solve it controlling each line explicitly:\nFlux<String> flux = Flux.generate( \n\n () -> new BufferedReader(new FileReader(\"/path/to/file.txt\")),\n\n // generator function reads a line from the file and emits it\n (bufferedReader, sink) -> {\n String line = bufferedReader.readLine();\n if (line != null) {\n sink.next(line);\n } else {\n sink.complete();\n }\n },\n \n reader -> Mono.fromRunnable(() -> {\n try {\n reader.close();\n } catch (IOException e) {\n // Handle exception\n }\n })\n);\n\n"
] |
[
1
] |
[] |
[] |
[
"java",
"project_reactor",
"spring_webflux"
] |
stackoverflow_0074664924_java_project_reactor_spring_webflux.txt
|
Q:
Python how to read N number of lines at a time
I am writing a code to take an enormous textfile (several GB) N lines at a time, process that batch, and move onto the next N lines until I have completed the entire file. (I don't care if the last batch isn't the perfect size).
I have been reading about using itertools islice for this operation. I think I am halfway there:
from itertools import islice
N = 16
infile = open("my_very_large_text_file", "r")
lines_gen = islice(infile, N)
for lines in lines_gen:
...process my lines...
The trouble is that I would like to process the next batch of 16 lines, but I am missing something
A:
islice() can be used to get the next n items of an iterator. Thus, list(islice(f, n)) will return a list of the next n lines of the file f. Using this inside a loop will give you the file in chunks of n lines. At the end of the file, the list might be shorter, and finally the call will return an empty list.
from itertools import islice
with open(...) as f:
while True:
next_n_lines = list(islice(f, n))
if not next_n_lines:
break
# process next_n_lines
An alternative is to use the grouper pattern:
from itertools import zip_longest
with open(...) as f:
for next_n_lines in zip_longest(*[f] * n):
# process next_n_lines
A:
The question appears to presume that there is efficiency to be gained by reading an "enormous textfile" in blocks of N lines at a time. This adds an application layer of buffering over the already highly optimized stdio library, adds complexity, and probably buys you absolutely nothing.
Thus:
with open('my_very_large_text_file') as f:
for line in f:
process(line)
is probably superior to any alternative in time, space, complexity and readability.
See also Rob Pike's first two rules, Jackson's Two Rules, and PEP-20 The Zen of Python. If you really just wanted to play with islice you should have left out the large file stuff.
A:
Here is another way using groupby:
from itertools import count, groupby
N = 16
with open('test') as f:
for g, group in groupby(f, key=lambda _, c=count(): c.next()/N):
print list(group)
How it works:
Basically groupby() will group the lines by the return value of the key parameter and the key parameter is the lambda function lambda _, c=count(): c.next()/N and using the fact that the c argument will be bound to count() when the function will be defined so each time groupby() will call the lambda function and evaluate the return value to determine the grouper that will group the lines so :
# 1 iteration.
c.next() => 0
0 / 16 => 0
# 2 iteration.
c.next() => 1
1 / 16 => 0
...
# Start of the second grouper.
c.next() => 16
16/16 => 1
...
A:
Since the requirement was added that there be statistically uniform distribution of the lines selected from the file, I offer this simple approach.
"""randsamp - extract a random subset of n lines from a large file"""
import random
def scan_linepos(path):
"""return a list of seek offsets of the beginning of each line"""
linepos = []
offset = 0
with open(path) as inf:
# WARNING: CPython 2.7 file.tell() is not accurate on file.next()
for line in inf:
linepos.append(offset)
offset += len(line)
return linepos
def sample_lines(path, linepos, nsamp):
"""return nsamp lines from path where line offsets are in linepos"""
offsets = random.sample(linepos, nsamp)
offsets.sort() # this may make file reads more efficient
lines = []
with open(path) as inf:
for offset in offsets:
inf.seek(offset)
lines.append(inf.readline())
return lines
dataset = 'big_data.txt'
nsamp = 5
linepos = scan_linepos(dataset) # the scan only need be done once
lines = sample_lines(dataset, linepos, nsamp)
print 'selecting %d lines from a file of %d' % (nsamp, len(linepos))
print ''.join(lines)
I tested it on a mock data file of 3 million lines comprising 1.7GB on disk. The scan_linepos dominated the runtime taking about 20 seconds on my not-so-hot desktop.
Just to check the performance of sample_lines I used the timeit module as so
import timeit
t = timeit.Timer('sample_lines(dataset, linepos, nsamp)',
'from __main__ import sample_lines, dataset, linepos, nsamp')
trials = 10 ** 4
elapsed = t.timeit(number=trials)
print u'%dk trials in %.2f seconds, %.2fµs per trial' % (trials/1000,
elapsed, (elapsed/trials) * (10 ** 6))
For various values of nsamp; when nsamp was 100, a single sample_lines completed in 460µs and scaled linearly up to 10k samples at 47ms per call.
The natural next question is Random is barely random at all?, and the answer is "sub-cryptographic but certainly fine for bioinformatics".
A:
Used chunker function from What is the most “pythonic” way to iterate over a list in chunks?:
from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(*args, fillvalue=fillvalue)
with open(filename) as f:
for lines in grouper(f, chunk_size, ""): #for every chunk_sized chunk
"""process lines like
lines[0], lines[1] , ... , lines[chunk_size-1]"""
A:
Assuming "batch" means to want to process all 16 recs at one time instead of individually, read the file one record at a time and update a counter; when the counter hits 16, process that group. interim_list = []
infile = open("my_very_large_text_file", "r")
ctr = 0
for rec in infile:
interim_list.append(rec)
ctr += 1
if ctr > 15:
process_list(interim_list)
interim_list = []
ctr = 0
the final group
process_list(interim_list)
A:
Another solution might be to create an iterator that yields lists of n elements:
def n_elements(n, it):
try:
while True:
yield [next(it) for j in range(0, n)]
except StopIteration:
return
with open(filename, 'rt') as f:
for n_lines in n_elements(n, f):
do_stuff(n_lines)
|
Python how to read N number of lines at a time
|
I am writing a code to take an enormous textfile (several GB) N lines at a time, process that batch, and move onto the next N lines until I have completed the entire file. (I don't care if the last batch isn't the perfect size).
I have been reading about using itertools islice for this operation. I think I am halfway there:
from itertools import islice
N = 16
infile = open("my_very_large_text_file", "r")
lines_gen = islice(infile, N)
for lines in lines_gen:
...process my lines...
The trouble is that I would like to process the next batch of 16 lines, but I am missing something
|
[
"islice() can be used to get the next n items of an iterator. Thus, list(islice(f, n)) will return a list of the next n lines of the file f. Using this inside a loop will give you the file in chunks of n lines. At the end of the file, the list might be shorter, and finally the call will return an empty list.\nfrom itertools import islice\nwith open(...) as f:\n while True:\n next_n_lines = list(islice(f, n))\n if not next_n_lines:\n break\n # process next_n_lines\n\nAn alternative is to use the grouper pattern:\nfrom itertools import zip_longest\nwith open(...) as f:\n for next_n_lines in zip_longest(*[f] * n):\n # process next_n_lines\n\n",
"The question appears to presume that there is efficiency to be gained by reading an \"enormous textfile\" in blocks of N lines at a time. This adds an application layer of buffering over the already highly optimized stdio library, adds complexity, and probably buys you absolutely nothing.\nThus:\nwith open('my_very_large_text_file') as f:\n for line in f:\n process(line)\n\nis probably superior to any alternative in time, space, complexity and readability.\nSee also Rob Pike's first two rules, Jackson's Two Rules, and PEP-20 The Zen of Python. If you really just wanted to play with islice you should have left out the large file stuff.\n",
"Here is another way using groupby:\nfrom itertools import count, groupby\n\nN = 16\nwith open('test') as f:\n for g, group in groupby(f, key=lambda _, c=count(): c.next()/N):\n print list(group)\n\nHow it works:\nBasically groupby() will group the lines by the return value of the key parameter and the key parameter is the lambda function lambda _, c=count(): c.next()/N and using the fact that the c argument will be bound to count() when the function will be defined so each time groupby() will call the lambda function and evaluate the return value to determine the grouper that will group the lines so :\n# 1 iteration.\nc.next() => 0\n0 / 16 => 0\n# 2 iteration.\nc.next() => 1\n1 / 16 => 0\n...\n# Start of the second grouper.\nc.next() => 16\n16/16 => 1 \n...\n\n",
"Since the requirement was added that there be statistically uniform distribution of the lines selected from the file, I offer this simple approach.\n\"\"\"randsamp - extract a random subset of n lines from a large file\"\"\"\n\nimport random\n\ndef scan_linepos(path):\n \"\"\"return a list of seek offsets of the beginning of each line\"\"\"\n linepos = []\n offset = 0\n with open(path) as inf: \n # WARNING: CPython 2.7 file.tell() is not accurate on file.next()\n for line in inf:\n linepos.append(offset)\n offset += len(line)\n return linepos\n\ndef sample_lines(path, linepos, nsamp):\n \"\"\"return nsamp lines from path where line offsets are in linepos\"\"\"\n offsets = random.sample(linepos, nsamp)\n offsets.sort() # this may make file reads more efficient\n\n lines = []\n with open(path) as inf:\n for offset in offsets:\n inf.seek(offset)\n lines.append(inf.readline())\n return lines\n\ndataset = 'big_data.txt'\nnsamp = 5\nlinepos = scan_linepos(dataset) # the scan only need be done once\n\nlines = sample_lines(dataset, linepos, nsamp)\nprint 'selecting %d lines from a file of %d' % (nsamp, len(linepos))\nprint ''.join(lines)\n\nI tested it on a mock data file of 3 million lines comprising 1.7GB on disk. The scan_linepos dominated the runtime taking about 20 seconds on my not-so-hot desktop. \nJust to check the performance of sample_lines I used the timeit module as so\nimport timeit\nt = timeit.Timer('sample_lines(dataset, linepos, nsamp)', \n 'from __main__ import sample_lines, dataset, linepos, nsamp')\ntrials = 10 ** 4\nelapsed = t.timeit(number=trials)\nprint u'%dk trials in %.2f seconds, %.2fµs per trial' % (trials/1000,\n elapsed, (elapsed/trials) * (10 ** 6))\n\nFor various values of nsamp; when nsamp was 100, a single sample_lines completed in 460µs and scaled linearly up to 10k samples at 47ms per call.\nThe natural next question is Random is barely random at all?, and the answer is \"sub-cryptographic but certainly fine for bioinformatics\".\n",
"Used chunker function from What is the most “pythonic” way to iterate over a list in chunks?:\nfrom itertools import izip_longest\n\ndef grouper(iterable, n, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return izip_longest(*args, fillvalue=fillvalue)\n\n\nwith open(filename) as f:\n for lines in grouper(f, chunk_size, \"\"): #for every chunk_sized chunk\n \"\"\"process lines like \n lines[0], lines[1] , ... , lines[chunk_size-1]\"\"\"\n\n",
"Assuming \"batch\" means to want to process all 16 recs at one time instead of individually, read the file one record at a time and update a counter; when the counter hits 16, process that group. interim_list = []\ninfile = open(\"my_very_large_text_file\", \"r\")\nctr = 0\nfor rec in infile:\n interim_list.append(rec)\n ctr += 1\n if ctr > 15:\n process_list(interim_list)\n interim_list = []\n ctr = 0\nthe final group\nprocess_list(interim_list)\n\n",
"Another solution might be to create an iterator that yields lists of n elements:\ndef n_elements(n, it):\n try:\n while True:\n yield [next(it) for j in range(0, n)]\n except StopIteration:\n return\n\nwith open(filename, 'rt') as f:\n for n_lines in n_elements(n, f):\n do_stuff(n_lines)\n\n\n"
] |
[
76,
9,
3,
2,
1,
0,
0
] |
[] |
[] |
[
"lines",
"python",
"python_itertools"
] |
stackoverflow_0006335839_lines_python_python_itertools.txt
|
Q:
How to do reverse parallax for background image in Flutter?
I saw this parallax animation on Far Cry 6 website and wanted to recreate it in Flutter. I read the docs and watched some tutorials but I am not able to achieve this design accurately. I want to make a mobile version like the website shows on Mobile Browser like this - https://imgur.com/a/RGdspxa
The image needs to be on top of one another and when I scroll, the bottom image should come from bottom to top in a reversed manner as the website. I am not able to figure out how to do this.
Please tell me how I can achieve this?
My Code -
import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
return Scaffold(
body: Material(
child: Stack(
children: [
Image.network(
"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg",
height: height,
// width: width,
fit: BoxFit.fitHeight,
),
SingleChildScrollView(
child: Column(
children: [
SizedBox(height: height),
Image.network(
"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg",
height: height,
width: width,
fit: BoxFit.cover,
),
],
),
)
],
),
),
);
}
}
A:
basic idea is to use ScrollMetrics from ScrollNotification :
parallax.dart:
class Parallax extends StatefulWidget {
const Parallax({Key? key, required this.childreen}) : super(key: key);
final List<Widget> childreen;
@override
State<Parallax> createState() => _ParallaxState();
}
class _ParallaxState extends State<Parallax> {
late double _pixel;
@override
void initState() {
// TODO: implement initState
super.initState();
_pixel = 0;
}
@override
Widget build(BuildContext context) {
return NotificationListener<ScrollNotification>(
onNotification: (notif) {
setState(() {
_pixel = notif.metrics.pixels;
});
return true;
},
child: SingleChildScrollView(
child: Column(
children: List.generate(
widget.childreen.length,
(index) => _ParalaxChild(
index: index,
pixel: _pixel,
childreenLenght: widget.childreen.length,
child: widget.childreen[index])),
),
),
);
}
}
class _ParalaxChild extends StatelessWidget {
final int index;
final Widget child;
final double pixel;
final int childreenLenght;
const _ParalaxChild(
{Key? key,
required this.child,
required this.index,
required this.pixel,
required this.childreenLenght})
: super(key: key);
@override
Widget build(BuildContext context) {
return ClipRect(
child: SizedBox(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(
fit: StackFit.expand,
children: [
FractionalTranslation(
translation: Offset(0.0, -_calculateParallax(context)),
child: child),
const Positioned(
bottom: 200,
right: 20,
child: Text(
"Parallax",
style: TextStyle(
color: Colors.white,
fontSize: 30,
fontWeight: FontWeight.bold),
)),
const Positioned(
bottom: 12,
right: 20,
left: 20,
child: Padding(
padding: EdgeInsets.all(20.0),
child: Text(
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.",
style: TextStyle(
color: Colors.white,
fontSize: 16,
),
),
))
],
)),
);
}
double _calculateParallax(BuildContext context) {
final double height = MediaQuery.of(context).size.height;
final double pageHeight = height * index;
final double childPosition = (pageHeight - pixel) / height;
return childPosition.isNaN ? 0.0 : childPosition;
}
}
use it or you can customize :
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: Parallax(childreen: [
Image.network(
"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg",
height: height,
// width: width,
fit: BoxFit.fitHeight,
),
Image.network(
"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg",
height: height,
width: width,
fit: BoxFit.fitHeight,
),
Image.network(
"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg",
height: height,
// width: width,
fit: BoxFit.fitHeight,
),
Image.network(
"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg",
height: height,
width: width,
fit: BoxFit.fitHeight,
),
]),
);
}
}
edit
For torn effect :
i create clipper for your reference you can always customize later:
class TornEffect extends CustomClipper<Path>{
///how much the torn effect will be
final int intensity;
TornEffect({required this.intensity});
@override
ui.Path getClip(ui.Size size) {
var path = Path();
//make sure path on left top corner
path.moveTo(0.0, 0.0);
var random = math.Random();
//to prevent blankSpace, move y to top (must always negative):
double ybase = -20.0;
//top:
double topProgress = 0.0;
while(topProgress < size.width){
bool curve = random.nextBool();
if(curve){
double cpx = topProgress + random.nextInt(intensity) * 0.5 * negativePositive();
double cpy = ybase + (random.nextInt(intensity) * 0.25 * negativePositive());
double x = topProgress + random.nextInt(intensity)* 1.0 * negativePositive();
double y = ybase + (random.nextInt(intensity) * 0.5 * negativePositive());
path.quadraticBezierTo(
cpx,
cpy,
x,
y
);
topProgress += x.abs();
}
else {
double x = topProgress + random.nextInt(intensity) * 1.0 * negativePositive();
double y = ybase + (random.nextInt(intensity) * 0.5 * negativePositive());
path.lineTo(x, y);
topProgress += x.abs();
}
}
//make sure top right corner got shape
path.lineTo(size.width, 0.0);
// line to bottom right corner
path.lineTo(size.width, size.height);
// you can build bottom rip effect later:
//double bottomProgress = 0.0;
//while(){}
// bottom left
path.lineTo(0.0, size.height);
//close it with another line
path.close();
return path;
}
double negativePositive(){
var random = math.Random();
bool negativePositive = random.nextBool();
double result = negativePositive ? 1.0: -1.0;
return result;
}
@override
bool shouldReclip(covariant CustomClipper<ui.Path> oldClipper) {
// TODO: implement shouldReclip
//return this != oldClipper;
// return false for performance, or rebuilt every scroll
return false;
}
}
on parallax.dart:
return ClipPath(
clipper: TornEffect(intensity: 21),
child: SizedBox(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(
fit: StackFit.expand,
children: [
A:
To create a parallax scrolling effect like the one on the Far Cry 6 website in Flutter, you can use a Stack widget and animate the position of the background images using a ScrollController and a Tween animation.
First, create a Stack widget and place the two background images inside it. Then, create a SingleChildScrollView widget and wrap the Stack inside it. This will allow the user to scroll the background images vertically.
Next, create a ScrollController and use it to retrieve the current scroll position of the SingleChildScrollView. You can then use this scroll position to animate the position of the background images using a Tween animation.
Here's an example of how you could do this:
// Create the ScrollController
final scrollController = ScrollController();
// Retrieve the current scroll position
final scrollPosition = scrollController.position.pixels;
// Define the range of the animation (in this case, from 0.0 to 1.0)
final animationRange = Tween(begin: 0.0, end: 1.0);
// Calculate the animation value based on the current scroll position
final animationValue = animationRange.transform(scrollPosition);
// Use the animation value to animate the position of the background images
return SingleChildScrollView(
controller: scrollController,
child: Stack(
children: [
// Background image 1
Positioned(
top: animationValue * 100.0, // This will move the image 100 pixels downwards as the user scrolls
child: Image.asset("image1.png"),
),
// Background image 2
Positioned(
top: -animationValue * 100.0, // This will move the image 100 pixels upwards as the user scrolls
child: Image.asset("image2.png"),
),
],
),
);
In this example, the animationValue is calculated based on the current scroll position of the SingleChildScrollView. The animationValue is used to animate the position of the background images by moving them 100 pixels in opposite directions as the user scrolls.
You can adjust the animation range and the movement distance to fine-tune the parallax scrolling effect to your liking. You can also use different interpolation curves to control the rate of the animation, such as Curves.easeInOut or Curves.elasticInOut.
|
How to do reverse parallax for background image in Flutter?
|
I saw this parallax animation on Far Cry 6 website and wanted to recreate it in Flutter. I read the docs and watched some tutorials but I am not able to achieve this design accurately. I want to make a mobile version like the website shows on Mobile Browser like this - https://imgur.com/a/RGdspxa
The image needs to be on top of one another and when I scroll, the bottom image should come from bottom to top in a reversed manner as the website. I am not able to figure out how to do this.
Please tell me how I can achieve this?
My Code -
import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
return Scaffold(
body: Material(
child: Stack(
children: [
Image.network(
"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg",
height: height,
// width: width,
fit: BoxFit.fitHeight,
),
SingleChildScrollView(
child: Column(
children: [
SizedBox(height: height),
Image.network(
"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg",
height: height,
width: width,
fit: BoxFit.cover,
),
],
),
)
],
),
),
);
}
}
|
[
"\nbasic idea is to use ScrollMetrics from ScrollNotification :\nparallax.dart:\nclass Parallax extends StatefulWidget {\n const Parallax({Key? key, required this.childreen}) : super(key: key);\n final List<Widget> childreen;\n\n @override\n State<Parallax> createState() => _ParallaxState();\n}\n\nclass _ParallaxState extends State<Parallax> {\n late double _pixel;\n\n @override\n void initState() {\n // TODO: implement initState\n super.initState();\n _pixel = 0;\n }\n\n @override\n Widget build(BuildContext context) {\n return NotificationListener<ScrollNotification>(\n onNotification: (notif) {\n setState(() {\n _pixel = notif.metrics.pixels;\n });\n return true;\n },\n child: SingleChildScrollView(\n child: Column(\n children: List.generate(\n widget.childreen.length,\n (index) => _ParalaxChild(\n index: index,\n pixel: _pixel,\n childreenLenght: widget.childreen.length,\n child: widget.childreen[index])),\n ),\n ),\n );\n }\n}\n\nclass _ParalaxChild extends StatelessWidget {\n final int index;\n final Widget child;\n final double pixel;\n final int childreenLenght;\n const _ParalaxChild(\n {Key? key,\n required this.child,\n required this.index,\n required this.pixel,\n required this.childreenLenght})\n : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n return ClipRect(\n child: SizedBox(\n height: MediaQuery.of(context).size.height,\n width: MediaQuery.of(context).size.width,\n child: Stack(\n fit: StackFit.expand,\n children: [\n FractionalTranslation(\n translation: Offset(0.0, -_calculateParallax(context)),\n child: child),\n const Positioned(\n bottom: 200,\n right: 20,\n child: Text(\n \"Parallax\",\n style: TextStyle(\n color: Colors.white,\n fontSize: 30,\n fontWeight: FontWeight.bold),\n )),\n const Positioned(\n bottom: 12,\n right: 20,\n left: 20,\n child: Padding(\n padding: EdgeInsets.all(20.0),\n child: Text(\n \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.\",\n style: TextStyle(\n color: Colors.white,\n fontSize: 16,\n ),\n ),\n ))\n ],\n )),\n );\n }\n\n double _calculateParallax(BuildContext context) {\n final double height = MediaQuery.of(context).size.height;\n final double pageHeight = height * index;\n final double childPosition = (pageHeight - pixel) / height;\n return childPosition.isNaN ? 0.0 : childPosition;\n }\n}\n\nuse it or you can customize :\nclass MyApp extends StatelessWidget {\n const MyApp({Key? key}) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n double height = MediaQuery.of(context).size.height;\n double width = MediaQuery.of(context).size.width;\n return Scaffold(\n body: Parallax(childreen: [\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg\",\n height: height,\n // width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg\",\n height: height,\n width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/1mP5aHQYJI5xw08eD2eV0W/7bc890d58c6bcf5efbe8713f147828ae/banner-webasset.jpg\",\n height: height,\n // width: width,\n fit: BoxFit.fitHeight,\n ),\n Image.network(\n \"https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7ad5MGeYDCekqMiS5qRZuK/1005c73ea409e895058d4273d93dcb1a/banner-background_alt.jpg\",\n height: height,\n width: width,\n fit: BoxFit.fitHeight,\n ),\n ]),\n );\n }\n}\n\nedit\nFor torn effect :\n\ni create clipper for your reference you can always customize later:\nclass TornEffect extends CustomClipper<Path>{\n ///how much the torn effect will be\n final int intensity;\n\n TornEffect({required this.intensity});\n\n @override\n ui.Path getClip(ui.Size size) {\n\n var path = Path();\n //make sure path on left top corner\n path.moveTo(0.0, 0.0);\n\n var random = math.Random();\n \n //to prevent blankSpace, move y to top (must always negative):\n double ybase = -20.0;\n\n //top:\n double topProgress = 0.0;\n while(topProgress < size.width){\n bool curve = random.nextBool();\n if(curve){\n \n double cpx = topProgress + random.nextInt(intensity) * 0.5 * negativePositive();\n double cpy = ybase + (random.nextInt(intensity) * 0.25 * negativePositive());\n\n double x = topProgress + random.nextInt(intensity)* 1.0 * negativePositive();\n double y = ybase + (random.nextInt(intensity) * 0.5 * negativePositive());\n\n path.quadraticBezierTo(\n cpx,\n cpy,\n x,\n y\n );\n topProgress += x.abs();\n }\n else {\n \n double x = topProgress + random.nextInt(intensity) * 1.0 * negativePositive();\n double y = ybase + (random.nextInt(intensity) * 0.5 * negativePositive());\n path.lineTo(x, y);\n topProgress += x.abs();\n }\n }\n //make sure top right corner got shape\n path.lineTo(size.width, 0.0);\n\n // line to bottom right corner\n path.lineTo(size.width, size.height);\n\n // you can build bottom rip effect later:\n //double bottomProgress = 0.0;\n //while(){}\n\n // bottom left\n path.lineTo(0.0, size.height);\n\n //close it with another line\n path.close();\n return path;\n\n }\n\n double negativePositive(){\n var random = math.Random();\n bool negativePositive = random.nextBool();\n double result = negativePositive ? 1.0: -1.0;\n return result;\n }\n\n @override\n bool shouldReclip(covariant CustomClipper<ui.Path> oldClipper) {\n // TODO: implement shouldReclip\n //return this != oldClipper;\n // return false for performance, or rebuilt every scroll\n return false;\n }\n\n}\n\non parallax.dart:\nreturn ClipPath(\n clipper: TornEffect(intensity: 21),\n child: SizedBox(\n height: MediaQuery.of(context).size.height,\n width: MediaQuery.of(context).size.width,\n child: Stack(\n fit: StackFit.expand,\n children: [\n\n",
"To create a parallax scrolling effect like the one on the Far Cry 6 website in Flutter, you can use a Stack widget and animate the position of the background images using a ScrollController and a Tween animation.\nFirst, create a Stack widget and place the two background images inside it. Then, create a SingleChildScrollView widget and wrap the Stack inside it. This will allow the user to scroll the background images vertically.\nNext, create a ScrollController and use it to retrieve the current scroll position of the SingleChildScrollView. You can then use this scroll position to animate the position of the background images using a Tween animation.\nHere's an example of how you could do this:\n// Create the ScrollController\nfinal scrollController = ScrollController();\n\n// Retrieve the current scroll position\nfinal scrollPosition = scrollController.position.pixels;\n\n// Define the range of the animation (in this case, from 0.0 to 1.0)\nfinal animationRange = Tween(begin: 0.0, end: 1.0);\n\n// Calculate the animation value based on the current scroll position\nfinal animationValue = animationRange.transform(scrollPosition);\n\n// Use the animation value to animate the position of the background images\nreturn SingleChildScrollView(\n controller: scrollController,\n child: Stack(\n children: [\n // Background image 1\n Positioned(\n top: animationValue * 100.0, // This will move the image 100 pixels downwards as the user scrolls\n child: Image.asset(\"image1.png\"),\n ),\n // Background image 2\n Positioned(\n top: -animationValue * 100.0, // This will move the image 100 pixels upwards as the user scrolls\n child: Image.asset(\"image2.png\"),\n ),\n ],\n ),\n);\n\nIn this example, the animationValue is calculated based on the current scroll position of the SingleChildScrollView. The animationValue is used to animate the position of the background images by moving them 100 pixels in opposite directions as the user scrolls.\nYou can adjust the animation range and the movement distance to fine-tune the parallax scrolling effect to your liking. You can also use different interpolation curves to control the rate of the animation, such as Curves.easeInOut or Curves.elasticInOut.\n"
] |
[
3,
0
] |
[] |
[] |
[
"dart",
"flutter",
"flutter_layout"
] |
stackoverflow_0074499635_dart_flutter_flutter_layout.txt
|
Q:
fatal: Not a git repository (or any of the parent directories): .git
I got the following when I try to git push to heroku
fatal: Not a git repository (or any of the parent directories): .git
I try to follow ruby on rail tutorial book.
I think I installed the client heroku package(by downloading from heroku website and follow their instruction to install, GUI format installation). So my client side heroku should be ok (I am new to programming , so not sure if saying by this term is correct or not).
Then I open a new terminal and key in
git push heroku master
I got
fatal: Not a git repository (or any of the parent directories): .git
Can anyone good at this explain which part I missed? i.e. have to move to some directory first?
Please show me the command since I might still have no idea without command.
PS: I think I have repository in my github already.
A:
You aren't on a git repository directory.
Yype pwd and make sure it's where you think you should be. Chances are you are in ~/ or something just before the directory you think you are in.
Or maybe you are in C:/ drive instead of the one you are. To change your directory from drive c to d use this command cd D:/ then figure out your files with this command ls.
A:
Have you created a git repository? Create it using git init and then commit some files.
http://git-scm.com/book/en/Git-Basics-Getting-a-Git-Repository
A:
update sep 2020
first, you have git repo required to create a heroku app
git init
git add .
git commit -m "initial commit"
heroku create
git push heroku master
how your code uploading to Heroku
A:
Make sure you have followed all the steps in the Installation and setup section of the Rails Tutorial book.
The error message you are getting is indicating that you have missed the git init step.
A:
It is possible to encounter this error despite being within a git repository.
The answer at https://stackoverflow.com/a/60114649/3753318 has it exactly right:
In my case a system crash had caused the HEAD file to become corrupted. This guide shows how to fix that and other problems you may encounter.
https://git.seveas.net/repairing-and-recovering-broken-git-repositories.html
If the .git/HEAD file is messed up in some way, this will also lead to the "not a git repository error"
A:
This error comes because you are trying to push the changes from a non-cloned working copy of your git repository. have you initialized git repo on the dir that you are working?? if not so initialize git repo by using git init and then either do a git clone or add a remote by using git remote add origin [email protected]:repourl.git for more detail refer this
A:
This can happen if you mean to do git clone but instead do git checkout.
A:
If you previously had an initial commit from local to GitHub remote, or if you previously pulled from remote to local, then you have set up your remote. What worked for me is signing into my remote GitHub repo, and then this error went away and able to push/pull changes from local to remote, and vice versa.
|
fatal: Not a git repository (or any of the parent directories): .git
|
I got the following when I try to git push to heroku
fatal: Not a git repository (or any of the parent directories): .git
I try to follow ruby on rail tutorial book.
I think I installed the client heroku package(by downloading from heroku website and follow their instruction to install, GUI format installation). So my client side heroku should be ok (I am new to programming , so not sure if saying by this term is correct or not).
Then I open a new terminal and key in
git push heroku master
I got
fatal: Not a git repository (or any of the parent directories): .git
Can anyone good at this explain which part I missed? i.e. have to move to some directory first?
Please show me the command since I might still have no idea without command.
PS: I think I have repository in my github already.
|
[
"You aren't on a git repository directory.\nYype pwd and make sure it's where you think you should be. Chances are you are in ~/ or something just before the directory you think you are in.\nOr maybe you are in C:/ drive instead of the one you are. To change your directory from drive c to d use this command cd D:/ then figure out your files with this command ls.\n",
"Have you created a git repository? Create it using git init and then commit some files. \nhttp://git-scm.com/book/en/Git-Basics-Getting-a-Git-Repository\n",
"update sep 2020\nfirst, you have git repo required to create a heroku app\ngit init\ngit add .\ngit commit -m \"initial commit\"\nheroku create\ngit push heroku master\n\n\nhow your code uploading to Heroku\n",
"Make sure you have followed all the steps in the Installation and setup section of the Rails Tutorial book. \nThe error message you are getting is indicating that you have missed the git init step. \n",
"It is possible to encounter this error despite being within a git repository.\nThe answer at https://stackoverflow.com/a/60114649/3753318 has it exactly right:\n\nIn my case a system crash had caused the HEAD file to become corrupted. This guide shows how to fix that and other problems you may encounter.\nhttps://git.seveas.net/repairing-and-recovering-broken-git-repositories.html\n\nIf the .git/HEAD file is messed up in some way, this will also lead to the \"not a git repository error\"\n",
"This error comes because you are trying to push the changes from a non-cloned working copy of your git repository. have you initialized git repo on the dir that you are working?? if not so initialize git repo by using git init and then either do a git clone or add a remote by using git remote add origin [email protected]:repourl.git for more detail refer this\n",
"This can happen if you mean to do git clone but instead do git checkout.\n",
"If you previously had an initial commit from local to GitHub remote, or if you previously pulled from remote to local, then you have set up your remote. What worked for me is signing into my remote GitHub repo, and then this error went away and able to push/pull changes from local to remote, and vice versa.\n"
] |
[
16,
13,
5,
3,
1,
0,
0,
0
] |
[] |
[] |
[
"git",
"repository"
] |
stackoverflow_0013888972_git_repository.txt
|
Q:
NextJS middleware function is not triggered in zone
I have an application reachable via the following http://localhost (this is the url of the main application) and another one reachable via http://localhost/subapp (this is the url of a sub-application), I am using nginx and docker to run both apps in two different containers on the same port (3000).
The subapplication is a subzone and I am having troubles setting up a middleware function to check if the user is authenticated, preventing the user to reach certain pages if it is not authenticated.
To achieve this I have an authentication system (build with next-auth) in the main application (running on http://localhost).
In the subapplication I have checked that the cookie is correctly set when the user is authenticated and it is not set when the user access the page without being authenticated, however the middleware function is not getting called for some reason.
Below is the implementation of the middleware function in the subapp (running on http://localhost/subapp):
export { default } from "next-auth/middleware";
import { NextRequest, NextResponse } from 'next/server';
export async function middleware(req: NextRequest, res: NextResponse) {
console.log("TEST"); // this is never printed
const session = req.cookies.get('next-auth.session-token');
if(session)
return NextResponse.next();
else
return NextResponse.redirect(new URL('/signin', req.url)); // this should send the user back to http://localhost/sign-in in case the user is not authenticated
}
export const config = {
matcher: [
"/",
"/subapp/play",
"/subapp/api/:path*",
],
pages: {
signIn: '/signin'
}
}
I have also tried using the middleware function of the main app (running on http://localhost) to prevent the user to reach the protected pages but it is not working.
A:
When you set basePath: '/subapp', in next.config.js your matcher in middleware.js is "/play" not "/subapp/play". If you include subapp in your matcher the middleware will never be called.
So try:
export const config = {
matcher: [
"/",
"/play",
"/api/:path*",
],
pages: {
signIn: '/signin'
}
}
|
NextJS middleware function is not triggered in zone
|
I have an application reachable via the following http://localhost (this is the url of the main application) and another one reachable via http://localhost/subapp (this is the url of a sub-application), I am using nginx and docker to run both apps in two different containers on the same port (3000).
The subapplication is a subzone and I am having troubles setting up a middleware function to check if the user is authenticated, preventing the user to reach certain pages if it is not authenticated.
To achieve this I have an authentication system (build with next-auth) in the main application (running on http://localhost).
In the subapplication I have checked that the cookie is correctly set when the user is authenticated and it is not set when the user access the page without being authenticated, however the middleware function is not getting called for some reason.
Below is the implementation of the middleware function in the subapp (running on http://localhost/subapp):
export { default } from "next-auth/middleware";
import { NextRequest, NextResponse } from 'next/server';
export async function middleware(req: NextRequest, res: NextResponse) {
console.log("TEST"); // this is never printed
const session = req.cookies.get('next-auth.session-token');
if(session)
return NextResponse.next();
else
return NextResponse.redirect(new URL('/signin', req.url)); // this should send the user back to http://localhost/sign-in in case the user is not authenticated
}
export const config = {
matcher: [
"/",
"/subapp/play",
"/subapp/api/:path*",
],
pages: {
signIn: '/signin'
}
}
I have also tried using the middleware function of the main app (running on http://localhost) to prevent the user to reach the protected pages but it is not working.
|
[
"When you set basePath: '/subapp', in next.config.js your matcher in middleware.js is \"/play\" not \"/subapp/play\". If you include subapp in your matcher the middleware will never be called.\nSo try:\nexport const config = {\n matcher: [\n \"/\",\n \"/play\",\n \"/api/:path*\",\n ],\n pages: {\n signIn: '/signin'\n }\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"authentication",
"next.js",
"next_auth",
"reactjs",
"typescript"
] |
stackoverflow_0074415201_authentication_next.js_next_auth_reactjs_typescript.txt
|
Q:
How to print a std::map after throwing a runTime error
I would like to throw and runTime error in a function and afterwards print a map.
I have the following code:
#include <iostream>
#include <string>
#include <map>
class myClass
{
public:
static bool storeInMap(const std::string& name, int value)
{
if(myMap.find(name) == myMap.end())
{
myMap[name] = value;
return true;
}
return false;
}
static void lookup(const std::string& name)
{
auto it = myMap.find(name);
if (it != myMap.end())
{
std::cout << "Found " << std::endl;
}
else
{
std::cout << "Not found. \n \
Available are: \n " << std::endl;
}
}
private:
static std::map<std::string, int> myMap;
};
std::map<std::string, int> myClass::myMap;
int main()
{
myClass::storeInMap("one", 1);
myClass::storeInMap("two", 2);
myClass::lookup("one");
myClass::lookup("three");
return 0;
}
The first 2 lines in main will store the entry for "one" and "two".
The third line is going to lookup in the map the entry "one" and print "Found".
The forth line will should throw a runTime error and print all entries in myMap.
In the case:
Not found
Available are:
"one"
"two"
However I do not know how to put the map in a runTime error, and would appreciate the help!
Best regards
A:
I think this is what you're going for
else
{
std::string error_msg = "\n\nNot found!\nAvailable are:\n";
for(auto& n : myMap)
{
error_msg += n.first + "\n";
}
throw std::runtime_error(error_msg.c_str());
}
|
How to print a std::map after throwing a runTime error
|
I would like to throw and runTime error in a function and afterwards print a map.
I have the following code:
#include <iostream>
#include <string>
#include <map>
class myClass
{
public:
static bool storeInMap(const std::string& name, int value)
{
if(myMap.find(name) == myMap.end())
{
myMap[name] = value;
return true;
}
return false;
}
static void lookup(const std::string& name)
{
auto it = myMap.find(name);
if (it != myMap.end())
{
std::cout << "Found " << std::endl;
}
else
{
std::cout << "Not found. \n \
Available are: \n " << std::endl;
}
}
private:
static std::map<std::string, int> myMap;
};
std::map<std::string, int> myClass::myMap;
int main()
{
myClass::storeInMap("one", 1);
myClass::storeInMap("two", 2);
myClass::lookup("one");
myClass::lookup("three");
return 0;
}
The first 2 lines in main will store the entry for "one" and "two".
The third line is going to lookup in the map the entry "one" and print "Found".
The forth line will should throw a runTime error and print all entries in myMap.
In the case:
Not found
Available are:
"one"
"two"
However I do not know how to put the map in a runTime error, and would appreciate the help!
Best regards
|
[
"I think this is what you're going for\nelse\n{\n std::string error_msg = \"\\n\\nNot found!\\nAvailable are:\\n\";\n for(auto& n : myMap)\n {\n error_msg += n.first + \"\\n\";\n }\n throw std::runtime_error(error_msg.c_str());\n}\n\n\n"
] |
[
0
] |
[] |
[] |
[
"c++",
"c++11"
] |
stackoverflow_0074669825_c++_c++11.txt
|
Q:
How to re-apply all previous calculations in a pandas data frame on append
Let's say I have this data frame:
df = pd.DataFrame({"A":[1,2,3],"B":[4,5,6]})
And let's say I define a new column like this:
df["C"] = df["A"] + df["B"]
then the C column will have the values [5, 7, 9].
However, let's say I append a new row with the values 4 for A and 7 for B, then the C column will have the values [5, 7, 9, NaN].
How can I define the columns that the calculation rule is automatically applied when something is added to the data frame? Or is there a "recalculate all" function of some sort?
A:
What distinguish Python from other programming languages is that it is interpreted rather than compiled. It means that the code is executed line by line.
So, in your case when you'll add a row at the end of the df, there will be no re-calculation.
df["C"] = df["A"] + df["B"] #executed firstly
df.loc[len(df.index)] = [4, 7, np.NaN] #executed secondly
print(df)
A B C
0 1.0 4.0 5.0
1 2.0 5.0 7.0
2 3.0 6.0 9.0
3 4.0 7.0 NaN
Unless you force the re-calculation yourself by adding the same line as before :
df["C"] = df["A"] + df["B"]
df.loc[len(df.index)] = [4, 7, np.NaN]
df["C"] = df["A"] + df["B"] # <------added here to re-calculate
print(df)
A B C
0 1.0 4.0 5.0
1 2.0 5.0 7.0
2 3.0 6.0 9.0
3 4.0 7.0 11.0
If you're using a notebook like Jupyter, you'll need to put df["C"] = df["A"] + df["B"] in a separate cell and re-run it after each row appended/added.
|
How to re-apply all previous calculations in a pandas data frame on append
|
Let's say I have this data frame:
df = pd.DataFrame({"A":[1,2,3],"B":[4,5,6]})
And let's say I define a new column like this:
df["C"] = df["A"] + df["B"]
then the C column will have the values [5, 7, 9].
However, let's say I append a new row with the values 4 for A and 7 for B, then the C column will have the values [5, 7, 9, NaN].
How can I define the columns that the calculation rule is automatically applied when something is added to the data frame? Or is there a "recalculate all" function of some sort?
|
[
"What distinguish Python from other programming languages is that it is interpreted rather than compiled. It means that the code is executed line by line.\nSo, in your case when you'll add a row at the end of the df, there will be no re-calculation.\ndf[\"C\"] = df[\"A\"] + df[\"B\"] #executed firstly\n\ndf.loc[len(df.index)] = [4, 7, np.NaN] #executed secondly\n\nprint(df)\n A B C\n0 1.0 4.0 5.0\n1 2.0 5.0 7.0\n2 3.0 6.0 9.0\n3 4.0 7.0 NaN\n\nUnless you force the re-calculation yourself by adding the same line as before :\ndf[\"C\"] = df[\"A\"] + df[\"B\"]\n\ndf.loc[len(df.index)] = [4, 7, np.NaN]\n\ndf[\"C\"] = df[\"A\"] + df[\"B\"] # <------added here to re-calculate\n\nprint(df)\n A B C\n0 1.0 4.0 5.0\n1 2.0 5.0 7.0\n2 3.0 6.0 9.0\n3 4.0 7.0 11.0\n\nIf you're using a notebook like Jupyter, you'll need to put df[\"C\"] = df[\"A\"] + df[\"B\"] in a separate cell and re-run it after each row appended/added.\n"
] |
[
0
] |
[] |
[] |
[
"append",
"apply",
"pandas",
"python"
] |
stackoverflow_0074670547_append_apply_pandas_python.txt
|
Q:
C++ Client-server (FIFOs, pipes, forks)
I' ll attach here the code I wrote, it doesn't work the way it should, it doesn't read properly from fifo. It was sending the username correctly before adding more code, it makes me think I wrote the code bad from beginning. If it's helpful I'll post the client code too, but I think the problem is here. When I run the program it prints the length correctly, but it doesn't print the username at all.
//SERVER
void copyUsername(int fd, char *&username, int &length)
{
printf("Waiting for client login...\n");
if (read(fd, &length, sizeof(int)) == -1)
{
printf("Could not read in the fifo 1\n");
return;
}
printf("Client wrote an username\n");
printf("%d\n", length);
if (read((char)fd, &username, sizeof(char)* length) == -1)
{
printf("Could not read in the fifo 2\n");
return;
}
printf("%s\n", username);
username[strlen(username)] = '\0';
printf("Copied successfully from FIFO %s\n", username);
}
int main()
{
if (mkfifo("fifo1", 0666) == -1)
{
if (errno != EEXIST)
{
printf("Could not create fifo file\n");
return 1;
}
}
int fd = open("fifo1", O_RDWR);
if (fd == -1)
{
printf("Could not open fifo file\n");
return 2;
}
char *username;
int length;
bool connected;
int pfd[2];
if(pipe(pfd) == -1)
{
printf("Could not open the pipe\n");
return 3;
}
int id = fork();
if(id == -1)
{
printf("Could not execute the fork\n");
return 4;
}
if(id == 0)
{
// child process
close(pfd[0]);
copyUsername(fd, username, length);
bool match = matchUsername(username, length);
write(pfd[1], &match, sizeof(match));
close(pfd[1]);
exit(0);
}
else
{
// parent process
close(pfd[1]);
read(pfd[0], &connected, sizeof(connected));
close(pfd[0]);
wait(NULL);
}
A:
A few issues ...
Doing printf for debug can interfere with the pipe data. Better to use stderr. A macro (e.g. prte and dbgprt) can help
In copyUsername, doing char *&username is overly complicated. It can/should be char *username.
Also, doing int &length is also complicated. Just pass back length as a return value.
In copyUsername, doing username[strlen(username)] = '\0'; is broken. It is a no-op.
It is broken because it assumes the buffer is already 0 terminated.
It is misplaced after the printf
Replace with username[length] = 0;
matchUsername not provided. I had to synthesize this.
client code not provided. It would have helped to show it, so the server can be tested. I've synthesized one in the code below.
Here is the corrected code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#define prte(_fmt...) \
fprintf(stderr,_fmt)
#if DEBUG
#define dbgprt(_fmt...) \
prte(_fmt)
#else
#define dbgprt(_fmt...) \
do { } while (0)
#endif
bool
matchUsername(const char *username, int length)
{
// NOTE: we can ignore the length because copyUsername has 0 terminated the
// string
bool match = strcmp(username,"neo") == 0;
return match;
}
int
copyUsername(int fd, char *username)
{
int length;
dbgprt("Waiting for client login...\n");
if (read(fd, &length, sizeof(int)) == -1) {
prte("Could not read in the fifo 1\n");
return -1;
}
dbgprt("Client wrote an username\n");
dbgprt("%d\n", length);
if (read(fd, username, length) == -1) {
dbgprt("Could not read in the fifo 2\n");
return -1;
}
#if 0
username[strlen(username)] = '\0';
#else
username[length] = '\0';
#endif
dbgprt("%s\n", username);
dbgprt("Copied successfully from FIFO %s\n", username);
return length;
}
int
main(void)
{
if (mkfifo("fifo1", 0666) == -1) {
if (errno != EEXIST) {
printf("Could not create fifo file\n");
return 1;
}
}
int fd = open("fifo1", O_RDWR);
if (fd == -1) {
prte("Could not open fifo file\n");
return 2;
}
char *username;
int length;
bool connected;
int pfd[2];
if (pipe(pfd) == -1) {
prte("Could not open the pipe\n");
return 3;
}
int id = fork();
if (id == -1) {
prte("Could not execute the fork\n");
return 4;
}
if (id == 0) {
// child process
close(pfd[0]);
length = copyUsername(fd, username);
bool match = 0;
if (length > 0)
length = matchUsername(username, length);
write(pfd[1], &match, sizeof(match));
close(pfd[1]);
exit(0);
}
else {
// parent process
close(pfd[1]);
read(pfd[0], &connected, sizeof(connected));
close(pfd[0]);
wait(NULL);
prte("main: connected=%d\n",connected);
}
return 0;
}
In the code above, I've used cpp conditionals to denote old vs. new code:
#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif
Note: this can be cleaned up by running the file through unifdef -k
Here is the client code I synthesized to test the program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
int
main(int argc,char **argv)
{
--argc;
++argv;
if (argc != 1) {
fprintf(stderr,"no name specified\n");
exit(1);
}
int fd = open("fifo1",O_RDWR);
if (fd < 0) {
perror("open");
exit(1);
}
int length = strlen(*argv);
write(fd,&length,sizeof(length));
write(fd,*argv,length);
close(fd);
return 0;
}
Here is the server output with the command: ./client bork:
main: connected=0
Here is the server output with the command: ./client neo:
main: connected=1
|
C++ Client-server (FIFOs, pipes, forks)
|
I' ll attach here the code I wrote, it doesn't work the way it should, it doesn't read properly from fifo. It was sending the username correctly before adding more code, it makes me think I wrote the code bad from beginning. If it's helpful I'll post the client code too, but I think the problem is here. When I run the program it prints the length correctly, but it doesn't print the username at all.
//SERVER
void copyUsername(int fd, char *&username, int &length)
{
printf("Waiting for client login...\n");
if (read(fd, &length, sizeof(int)) == -1)
{
printf("Could not read in the fifo 1\n");
return;
}
printf("Client wrote an username\n");
printf("%d\n", length);
if (read((char)fd, &username, sizeof(char)* length) == -1)
{
printf("Could not read in the fifo 2\n");
return;
}
printf("%s\n", username);
username[strlen(username)] = '\0';
printf("Copied successfully from FIFO %s\n", username);
}
int main()
{
if (mkfifo("fifo1", 0666) == -1)
{
if (errno != EEXIST)
{
printf("Could not create fifo file\n");
return 1;
}
}
int fd = open("fifo1", O_RDWR);
if (fd == -1)
{
printf("Could not open fifo file\n");
return 2;
}
char *username;
int length;
bool connected;
int pfd[2];
if(pipe(pfd) == -1)
{
printf("Could not open the pipe\n");
return 3;
}
int id = fork();
if(id == -1)
{
printf("Could not execute the fork\n");
return 4;
}
if(id == 0)
{
// child process
close(pfd[0]);
copyUsername(fd, username, length);
bool match = matchUsername(username, length);
write(pfd[1], &match, sizeof(match));
close(pfd[1]);
exit(0);
}
else
{
// parent process
close(pfd[1]);
read(pfd[0], &connected, sizeof(connected));
close(pfd[0]);
wait(NULL);
}
|
[
"A few issues ...\n\nDoing printf for debug can interfere with the pipe data. Better to use stderr. A macro (e.g. prte and dbgprt) can help\nIn copyUsername, doing char *&username is overly complicated. It can/should be char *username.\nAlso, doing int &length is also complicated. Just pass back length as a return value.\nIn copyUsername, doing username[strlen(username)] = '\\0'; is broken. It is a no-op.\nIt is broken because it assumes the buffer is already 0 terminated.\nIt is misplaced after the printf\nReplace with username[length] = 0;\nmatchUsername not provided. I had to synthesize this.\nclient code not provided. It would have helped to show it, so the server can be tested. I've synthesized one in the code below.\n\n\nHere is the corrected code:\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sys/stat.h>\n#include <sys/wait.h>\n\n#define prte(_fmt...) \\\n fprintf(stderr,_fmt)\n\n#if DEBUG\n#define dbgprt(_fmt...) \\\n prte(_fmt)\n#else\n#define dbgprt(_fmt...) \\\n do { } while (0)\n#endif\n\nbool\nmatchUsername(const char *username, int length)\n{\n // NOTE: we can ignore the length because copyUsername has 0 terminated the\n // string\n bool match = strcmp(username,\"neo\") == 0;\n\n return match;\n}\n\nint\ncopyUsername(int fd, char *username)\n{\n int length;\n\n dbgprt(\"Waiting for client login...\\n\");\n\n if (read(fd, &length, sizeof(int)) == -1) {\n prte(\"Could not read in the fifo 1\\n\");\n return -1;\n }\n dbgprt(\"Client wrote an username\\n\");\n\n dbgprt(\"%d\\n\", length);\n if (read(fd, username, length) == -1) {\n dbgprt(\"Could not read in the fifo 2\\n\");\n return -1;\n }\n#if 0\n username[strlen(username)] = '\\0';\n#else\n username[length] = '\\0';\n#endif\n dbgprt(\"%s\\n\", username);\n dbgprt(\"Copied successfully from FIFO %s\\n\", username);\n\n return length;\n}\n\nint\nmain(void)\n{\n if (mkfifo(\"fifo1\", 0666) == -1) {\n if (errno != EEXIST) {\n printf(\"Could not create fifo file\\n\");\n return 1;\n }\n }\n\n int fd = open(\"fifo1\", O_RDWR);\n\n if (fd == -1) {\n prte(\"Could not open fifo file\\n\");\n return 2;\n }\n\n char *username;\n int length;\n bool connected;\n\n int pfd[2];\n\n if (pipe(pfd) == -1) {\n prte(\"Could not open the pipe\\n\");\n return 3;\n }\n\n int id = fork();\n if (id == -1) {\n prte(\"Could not execute the fork\\n\");\n return 4;\n }\n\n if (id == 0) {\n // child process\n close(pfd[0]);\n length = copyUsername(fd, username);\n\n bool match = 0;\n if (length > 0)\n length = matchUsername(username, length);\n\n write(pfd[1], &match, sizeof(match));\n close(pfd[1]);\n exit(0);\n }\n else {\n // parent process\n close(pfd[1]);\n read(pfd[0], &connected, sizeof(connected));\n close(pfd[0]);\n wait(NULL);\n prte(\"main: connected=%d\\n\",connected);\n }\n\n return 0;\n}\n\n\nIn the code above, I've used cpp conditionals to denote old vs. new code:\n#if 0\n// old code\n#else\n// new code\n#endif\n\n#if 1\n// new code\n#endif\n\nNote: this can be cleaned up by running the file through unifdef -k\n\nHere is the client code I synthesized to test the program:\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n#include <fcntl.h>\n\nint\nmain(int argc,char **argv)\n{\n\n --argc;\n ++argv;\n\n if (argc != 1) {\n fprintf(stderr,\"no name specified\\n\");\n exit(1);\n }\n\n int fd = open(\"fifo1\",O_RDWR);\n if (fd < 0) {\n perror(\"open\");\n exit(1);\n }\n\n int length = strlen(*argv);\n write(fd,&length,sizeof(length));\n\n write(fd,*argv,length);\n\n close(fd);\n\n return 0;\n}\n\n\nHere is the server output with the command: ./client bork:\nmain: connected=0\n\nHere is the server output with the command: ./client neo:\nmain: connected=1\n\n"
] |
[
0
] |
[] |
[] |
[
"c++",
"fifo",
"fork",
"mkfifo",
"pipe"
] |
stackoverflow_0074669777_c++_fifo_fork_mkfifo_pipe.txt
|
Q:
Swift update deployment target to match package requirement
I'm new to swift development, so excuse the basic question, but when I import a package called SwiftHttp in a local package, I get this error:
Compiling for macOS 10.13, but module 'SwiftHttp' has a minimum deployment target of macOS 10.15:
So I've gone in to my project's setting, and changed the minimum deployments to macOS 11.0, both in the "project" section, and for all targets, but that error remains in the file. Is there anywhere else I need to update that setting? Or is there something I need to do to "propagate" that setting to the local package?
Images of what I have...
Project settings:
Target settings
Error:
A:
In order to use a package with a higher deployment target than your project, you need to change the deployment target of your project to match the deployment target of the package. In your case, you will need to change the deployment target of your project to macOS 10.15 in order for the SwiftHttp package to be compatible.
To change the deployment target of your project, go to the project settings and select the "General" tab. There should be a setting called "Deployment Target" where you can select the minimum version of macOS that your project supports. Once you have updated this setting, the error should disappear.
It's also worth noting that changing the deployment target of your project will affect all of the packages and dependencies that are included in your project, so you should make sure that all of the packages you are using are compatible with the new deployment target before you make the change.
|
Swift update deployment target to match package requirement
|
I'm new to swift development, so excuse the basic question, but when I import a package called SwiftHttp in a local package, I get this error:
Compiling for macOS 10.13, but module 'SwiftHttp' has a minimum deployment target of macOS 10.15:
So I've gone in to my project's setting, and changed the minimum deployments to macOS 11.0, both in the "project" section, and for all targets, but that error remains in the file. Is there anywhere else I need to update that setting? Or is there something I need to do to "propagate" that setting to the local package?
Images of what I have...
Project settings:
Target settings
Error:
|
[
"In order to use a package with a higher deployment target than your project, you need to change the deployment target of your project to match the deployment target of the package. In your case, you will need to change the deployment target of your project to macOS 10.15 in order for the SwiftHttp package to be compatible.\nTo change the deployment target of your project, go to the project settings and select the \"General\" tab. There should be a setting called \"Deployment Target\" where you can select the minimum version of macOS that your project supports. Once you have updated this setting, the error should disappear.\nIt's also worth noting that changing the deployment target of your project will affect all of the packages and dependencies that are included in your project, so you should make sure that all of the packages you are using are compatible with the new deployment target before you make the change.\n"
] |
[
1
] |
[] |
[] |
[
"macos",
"swift",
"xcode"
] |
stackoverflow_0074670346_macos_swift_xcode.txt
|
Q:
How to convert map to url query string?
Do you know of any utility class/library, that can convert Map into URL-friendly query string?
Example:
I have a map:
"param1"=12,
"param2"="cat"
I want to get:
param1=12¶m2=cat
final output
relativeUrl+param1=12¶m2=cat
A:
The most robust one I saw off-the-shelf is the URLEncodedUtils class from Apache Http Compoments (HttpClient 4.0).
The method URLEncodedUtils.format() is what you need.
It doesn't use map so you can have duplicate parameter names, like,
a=1&a=2&b=3
Not that I recommend this kind of use of parameter names.
A:
Here's something that I quickly wrote; I'm sure it can be improved upon.
import java.util.*;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class MapQuery {
static String urlEncodeUTF8(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new UnsupportedOperationException(e);
}
}
static String urlEncodeUTF8(Map<?,?> map) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<?,?> entry : map.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(String.format("%s=%s",
urlEncodeUTF8(entry.getKey().toString()),
urlEncodeUTF8(entry.getValue().toString())
));
}
return sb.toString();
}
public static void main(String[] args) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("p1", 12);
map.put("p2", "cat");
map.put("p3", "a & b");
System.out.println(urlEncodeUTF8(map));
// prints "p3=a+%26+b&p2=cat&p1=12"
}
}
A:
I found a smooth solution using java 8 and polygenelubricants' solution.
parameters.entrySet().stream()
.map(p -> urlEncodeUTF8(p.getKey()) + "=" + urlEncodeUTF8(p.getValue()))
.reduce((p1, p2) -> p1 + "&" + p2)
.orElse("");
A:
In Spring Util, there is a better way..,
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("key", key);
params.add("storeId", storeId);
params.add("orderId", orderId);
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl("http://spsenthil.com/order").queryParams(params).build();
ListenableFuture<ResponseEntity<String>> responseFuture = restTemplate.getForEntity(uriComponents.toUriString(), String.class);
A:
Update June 2016
Felt compelled to add an answer having seen far too many SOF answers with dated or inadequate answers to very common problem - a good library and some solid example usage for both parse and format operations.
Use org.apache.httpcomponents.httpclient library. The library contains this org.apache.http.client.utils.URLEncodedUtils class utility.
For example, it is easy to download this dependency from Maven:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
For my purposes I only needed to parse (read from query string to name-value pairs) and format (read from name-value pairs to query string) query strings. However, there are equivalents for doing the same with a URI (see commented out line below).
// Required imports
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
// code snippet
public static void parseAndFormatExample() throws UnsupportedEncodingException {
final String queryString = "nonce=12345&redirectCallbackUrl=http://www.bbc.co.uk";
System.out.println(queryString);
// => nonce=12345&redirectCallbackUrl=http://www.bbc.co.uk
final List<NameValuePair> params =
URLEncodedUtils.parse(queryString, StandardCharsets.UTF_8);
// List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), "UTF-8");
for (final NameValuePair param : params) {
System.out.println(param.getName() + " : " + param.getValue());
// => nonce : 12345
// => redirectCallbackUrl : http://www.bbc.co.uk
}
final String newQueryStringEncoded =
URLEncodedUtils.format(params, StandardCharsets.UTF_8);
// decode when printing to screen
final String newQueryStringDecoded =
URLDecoder.decode(newQueryStringEncoded, StandardCharsets.UTF_8.toString());
System.out.println(newQueryStringDecoded);
// => nonce=12345&redirectCallbackUrl=http://www.bbc.co.uk
}
This library did exactly what I needed and was able to replace some hacked custom code.
A:
I wanted to build on @eclipse's answer using java 8 mapping and reducing.
protected String formatQueryParams(Map<String, String> params) {
return params.entrySet().stream()
.map(p -> p.getKey() + "=" + p.getValue())
.reduce((p1, p2) -> p1 + "&" + p2)
.map(s -> "?" + s)
.orElse("");
}
The extra map operation takes the reduced string and puts a ? in front only if the string exists.
A:
If you actually want to build a complete URI, try URIBuilder from Apache Http Compoments (HttpClient 4).
This does not actually answer the question, but it answered the one I had when I found this question.
A:
Another 'one class'/no dependency way of doing it, handling single/multiple:
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class UrlQueryString {
private static final String DEFAULT_ENCODING = "UTF-8";
public static String buildQueryString(final LinkedHashMap<String, Object> map) {
try {
final Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
final StringBuilder sb = new StringBuilder(map.size() * 8);
while (it.hasNext()) {
final Map.Entry<String, Object> entry = it.next();
final String key = entry.getKey();
if (key != null) {
sb.append(URLEncoder.encode(key, DEFAULT_ENCODING));
sb.append('=');
final Object value = entry.getValue();
final String valueAsString = value != null ? URLEncoder.encode(value.toString(), DEFAULT_ENCODING) : "";
sb.append(valueAsString);
if (it.hasNext()) {
sb.append('&');
}
} else {
// Do what you want...for example:
assert false : String.format("Null key in query map: %s", map.entrySet());
}
}
return sb.toString();
} catch (final UnsupportedEncodingException e) {
throw new UnsupportedOperationException(e);
}
}
public static String buildQueryStringMulti(final LinkedHashMap<String, List<Object>> map) {
try {
final StringBuilder sb = new StringBuilder(map.size() * 8);
for (final Iterator<Entry<String, List<Object>>> mapIterator = map.entrySet().iterator(); mapIterator.hasNext();) {
final Entry<String, List<Object>> entry = mapIterator.next();
final String key = entry.getKey();
if (key != null) {
final String keyEncoded = URLEncoder.encode(key, DEFAULT_ENCODING);
final List<Object> values = entry.getValue();
sb.append(keyEncoded);
sb.append('=');
if (values != null) {
for (final Iterator<Object> listIt = values.iterator(); listIt.hasNext();) {
final Object valueObject = listIt.next();
sb.append(valueObject != null ? URLEncoder.encode(valueObject.toString(), DEFAULT_ENCODING) : "");
if (listIt.hasNext()) {
sb.append('&');
sb.append(keyEncoded);
sb.append('=');
}
}
}
if (mapIterator.hasNext()) {
sb.append('&');
}
} else {
// Do what you want...for example:
assert false : String.format("Null key in query map: %s", map.entrySet());
}
}
return sb.toString();
} catch (final UnsupportedEncodingException e) {
throw new UnsupportedOperationException(e);
}
}
public static void main(final String[] args) {
// Examples: could be turned into unit tests ...
{
final LinkedHashMap<String, Object> queryItems = new LinkedHashMap<String, Object>();
queryItems.put("brand", "C&A");
queryItems.put("count", null);
queryItems.put("misc", 42);
final String buildQueryString = buildQueryString(queryItems);
System.out.println(buildQueryString);
}
{
final LinkedHashMap<String, List<Object>> queryItems = new LinkedHashMap<String, List<Object>>();
queryItems.put("usernames", new ArrayList<Object>(Arrays.asList(new String[] { "bob", "john" })));
queryItems.put("nullValue", null);
queryItems.put("misc", new ArrayList<Object>(Arrays.asList(new Integer[] { 1, 2, 3 })));
final String buildQueryString = buildQueryStringMulti(queryItems);
System.out.println(buildQueryString);
}
}
}
You may use either simple (easier to write in most cases) or multiple when required. Note that both can be combined by adding an ampersand...
If you find any problems let me know in the comments.
A:
This is the solution I implemented, using Java 8 and org.apache.http.client.URLEncodedUtils. It maps the entries of the map into a list of BasicNameValuePair and then uses Apache's URLEncodedUtils to turn that into a query string.
List<BasicNameValuePair> nameValuePairs = params.entrySet().stream()
.map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
URLEncodedUtils.format(nameValuePairs, Charset.forName("UTF-8"));
A:
Using EntrySet and Streams:
map
.entrySet()
.stream()
.map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining("&"));
A:
There's nothing built into java to do this. But, hey, java is a programming language, so.. let's program it!
map.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&"))
This gives you "param1=12¶m2=cat". Now we need to join the URL and this bit together. You'd think you can just do: URL + "?" + theAbove but if the URL already contains a question mark, you have to join it all together with "&" instead. One way to check is to see if there's a question mark in the URL someplace already.
Also, I don't quite know what is in your map. If it's raw stuff, you probably have to safeguard the call to e.getKey() and e.getValue() with URLEncoder.encode or similar.
Yet another way to go is that you take a wider view. Are you trying to append a map's content to a URL, or... are you trying to make an HTTP(S) request from a java process with the stuff in the map as (additional) HTTP params? In the latter case, you can look into an http library like OkHttp which has some nice APIs to do this job, then you can forego any need to mess about with that URL in the first place.
A:
You can use a Stream for this, but instead of appending query parameters myself I'd use a Uri.Builder. For example:
final Map<String, String> map = new HashMap<>();
map.put("param1", "cat");
map.put("param2", "12");
final Uri uri =
map.entrySet().stream().collect(
() -> Uri.parse("relativeUrl").buildUpon(),
(builder, e) -> builder.appendQueryParameter(e.getKey(), e.getValue()),
(b1, b2) -> { throw new UnsupportedOperationException(); }
).build();
//Or, if you consider it more readable...
final Uri.Builder builder = Uri.parse("relativeUrl").buildUpon();
map.entrySet().forEach(e -> builder.appendQueryParameter(e.getKey(), e.getValue())
final Uri uri = builder.build();
//...
assertEquals(Uri.parse("relativeUrl?param1=cat¶m2=12"), uri);
A:
I think this is better for memory usage and performance, and I want to send just the property name when the value is null.
public static String toUrlEncode(Map<String, Object> map) {
StringBuilder sb = new StringBuilder();
map.entrySet().stream()
.forEach(entry
-> (entry.getValue() == null
? sb.append(entry.getKey())
: sb.append(entry.getKey())
.append('=')
.append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8)))
.append('&')
);
sb.delete(sb.length() - 1, sb.length());
return sb.toString();
}
A:
Here's a simple kotlin solution:
fun Map<String, String>.toUrlParams(): String =
entries.joinToString("&") {
it.key.toUrlEncoded() + "=" + it.value.toUrlEncoded()
}
fun String.toUrlEncoded(): String = URLEncoder.encode(
this, StandardCharsets.UTF_8
)
A:
To improve a little bit upon @eclipse's answer: In Javaland a request parameter map is usually represented as a Map<String, String[]>, a Map<String, List<String>> or possibly some kind of MultiValueMap<String, String> which is sort of the same thing. In any case: a parameter can usually have multiple values. A Java 8 solution would therefore be something along these lines:
public String getQueryString(HttpServletRequest request, String encoding) {
Map<String, String[]> parameters = request.getParameterMap();
return parameters.entrySet().stream()
.flatMap(entry -> encodeMultiParameter(entry.getKey(), entry.getValue(), encoding))
.reduce((param1, param2) -> param1 + "&" + param2)
.orElse("");
}
private Stream<String> encodeMultiParameter(String key, String[] values, String encoding) {
return Stream.of(values).map(value -> encodeSingleParameter(key, value, encoding));
}
private String encodeSingleParameter(String key, String value, String encoding) {
return urlEncode(key, encoding) + "=" + urlEncode(value, encoding);
}
private String urlEncode(String value, String encoding) {
try {
return URLEncoder.encode(value, encoding);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Cannot url encode " + value, e);
}
}
A:
Personally, I'd go for a solution like this, it's incredibly similar to the solution provided by @rzwitserloot, only subtle differences.
This solution is small, simple & clean, it requires very little in terms of dependencies, all of which are a part of the Java Util package.
Map<String, String> map = new HashMap<>();
map.put("param1", "12");
map.put("param2", "cat");
String output = "someUrl?";
output += map.entrySet()
.stream()
.map(x -> x.getKey() + "=" + x.getValue() + "&")
.collect(Collectors.joining("&"));
System.out.println(output.substring(0, output.length() -1));
A:
For multivalue map you can do like below (using java 8 stream api's)
Url encoding has been taken cared in this.
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
String urlQueryString = params.entrySet()
.stream()
.flatMap(stringListEntry -> stringListEntry.getValue()
.stream()
.map(s -> UriUtils.encode(stringListEntry.getKey(), StandardCharsets.UTF_8.toString()) + "=" +
UriUtils.encode(s, StandardCharsets.UTF_8.toString())))
.collect(Collectors.joining("&"));
A:
If you need just the query string (not the whole URL) and you are using Spring Framework, you can do this:
import org.springframework.web.util.UriComponentsBuilder;
...
final String queryString = UriComponentsBuilder.newInstance()
.queryParam("many", "7", "14", "21")
.queryParam("single", "XYZ")
.build()
.toUri()
.getQuery();
System.out.println(queryString);
the result is:
many=7&many=14&many=21&single=XYZ
A:
a very lightweight answer it works for me
public static String queryStr(Map<String, String> data) throws UnsupportedEncodingException {
String query = "";
for (String key : data.keySet()) {
query += query.length() < 1 ? "" : "&";
query += key + "=" + URLEncoder.encode(data.get(key), "UTF-8");
}
return query;
}
|
How to convert map to url query string?
|
Do you know of any utility class/library, that can convert Map into URL-friendly query string?
Example:
I have a map:
"param1"=12,
"param2"="cat"
I want to get:
param1=12¶m2=cat
final output
relativeUrl+param1=12¶m2=cat
|
[
"The most robust one I saw off-the-shelf is the URLEncodedUtils class from Apache Http Compoments (HttpClient 4.0).\nThe method URLEncodedUtils.format() is what you need.\nIt doesn't use map so you can have duplicate parameter names, like,\n a=1&a=2&b=3\n\nNot that I recommend this kind of use of parameter names.\n",
"Here's something that I quickly wrote; I'm sure it can be improved upon.\nimport java.util.*;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLEncoder;\n\npublic class MapQuery {\n static String urlEncodeUTF8(String s) {\n try {\n return URLEncoder.encode(s, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new UnsupportedOperationException(e);\n }\n }\n static String urlEncodeUTF8(Map<?,?> map) {\n StringBuilder sb = new StringBuilder();\n for (Map.Entry<?,?> entry : map.entrySet()) {\n if (sb.length() > 0) {\n sb.append(\"&\");\n }\n sb.append(String.format(\"%s=%s\",\n urlEncodeUTF8(entry.getKey().toString()),\n urlEncodeUTF8(entry.getValue().toString())\n ));\n }\n return sb.toString(); \n }\n public static void main(String[] args) {\n Map<String,Object> map = new HashMap<String,Object>();\n map.put(\"p1\", 12);\n map.put(\"p2\", \"cat\");\n map.put(\"p3\", \"a & b\"); \n System.out.println(urlEncodeUTF8(map));\n // prints \"p3=a+%26+b&p2=cat&p1=12\"\n }\n}\n\n",
"I found a smooth solution using java 8 and polygenelubricants' solution.\nparameters.entrySet().stream()\n .map(p -> urlEncodeUTF8(p.getKey()) + \"=\" + urlEncodeUTF8(p.getValue()))\n .reduce((p1, p2) -> p1 + \"&\" + p2)\n .orElse(\"\");\n\n",
"In Spring Util, there is a better way..,\nimport org.springframework.util.LinkedMultiValueMap;\nimport org.springframework.util.MultiValueMap;\nimport org.springframework.util.concurrent.ListenableFuture;\nimport org.springframework.web.util.UriComponents;\nimport org.springframework.web.util.UriComponentsBuilder;\n\nMultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();\nparams.add(\"key\", key);\nparams.add(\"storeId\", storeId);\nparams.add(\"orderId\", orderId);\nUriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(\"http://spsenthil.com/order\").queryParams(params).build();\nListenableFuture<ResponseEntity<String>> responseFuture = restTemplate.getForEntity(uriComponents.toUriString(), String.class);\n\n",
"Update June 2016\nFelt compelled to add an answer having seen far too many SOF answers with dated or inadequate answers to very common problem - a good library and some solid example usage for both parse and format operations.\nUse org.apache.httpcomponents.httpclient library. The library contains this org.apache.http.client.utils.URLEncodedUtils class utility.\nFor example, it is easy to download this dependency from Maven:\n <dependency>\n <groupId>org.apache.httpcomponents</groupId>\n <artifactId>httpclient</artifactId>\n <version>4.5</version>\n </dependency>\n\nFor my purposes I only needed to parse (read from query string to name-value pairs) and format (read from name-value pairs to query string) query strings. However, there are equivalents for doing the same with a URI (see commented out line below).\n// Required imports\nimport org.apache.http.NameValuePair;\nimport org.apache.http.client.utils.URLEncodedUtils;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLDecoder;\nimport java.nio.charset.StandardCharsets;\n\n// code snippet\npublic static void parseAndFormatExample() throws UnsupportedEncodingException {\n final String queryString = \"nonce=12345&redirectCallbackUrl=http://www.bbc.co.uk\";\n System.out.println(queryString);\n // => nonce=12345&redirectCallbackUrl=http://www.bbc.co.uk\n\n final List<NameValuePair> params =\n URLEncodedUtils.parse(queryString, StandardCharsets.UTF_8);\n // List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), \"UTF-8\");\n\n for (final NameValuePair param : params) {\n System.out.println(param.getName() + \" : \" + param.getValue());\n // => nonce : 12345\n // => redirectCallbackUrl : http://www.bbc.co.uk\n }\n\n final String newQueryStringEncoded =\n URLEncodedUtils.format(params, StandardCharsets.UTF_8);\n\n\n // decode when printing to screen\n final String newQueryStringDecoded =\n URLDecoder.decode(newQueryStringEncoded, StandardCharsets.UTF_8.toString());\n System.out.println(newQueryStringDecoded);\n // => nonce=12345&redirectCallbackUrl=http://www.bbc.co.uk\n }\n\nThis library did exactly what I needed and was able to replace some hacked custom code.\n",
"I wanted to build on @eclipse's answer using java 8 mapping and reducing.\n protected String formatQueryParams(Map<String, String> params) {\n return params.entrySet().stream()\n .map(p -> p.getKey() + \"=\" + p.getValue())\n .reduce((p1, p2) -> p1 + \"&\" + p2)\n .map(s -> \"?\" + s)\n .orElse(\"\");\n }\n\nThe extra map operation takes the reduced string and puts a ? in front only if the string exists.\n",
"If you actually want to build a complete URI, try URIBuilder from Apache Http Compoments (HttpClient 4).\nThis does not actually answer the question, but it answered the one I had when I found this question.\n",
"Another 'one class'/no dependency way of doing it, handling single/multiple:\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLEncoder;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\npublic class UrlQueryString {\n private static final String DEFAULT_ENCODING = \"UTF-8\";\n\n public static String buildQueryString(final LinkedHashMap<String, Object> map) {\n try {\n final Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();\n final StringBuilder sb = new StringBuilder(map.size() * 8);\n while (it.hasNext()) {\n final Map.Entry<String, Object> entry = it.next();\n final String key = entry.getKey();\n if (key != null) {\n sb.append(URLEncoder.encode(key, DEFAULT_ENCODING));\n sb.append('=');\n final Object value = entry.getValue();\n final String valueAsString = value != null ? URLEncoder.encode(value.toString(), DEFAULT_ENCODING) : \"\";\n sb.append(valueAsString);\n if (it.hasNext()) {\n sb.append('&');\n }\n } else {\n // Do what you want...for example:\n assert false : String.format(\"Null key in query map: %s\", map.entrySet());\n }\n }\n return sb.toString();\n } catch (final UnsupportedEncodingException e) {\n throw new UnsupportedOperationException(e);\n }\n }\n\n public static String buildQueryStringMulti(final LinkedHashMap<String, List<Object>> map) {\n try {\n final StringBuilder sb = new StringBuilder(map.size() * 8);\n for (final Iterator<Entry<String, List<Object>>> mapIterator = map.entrySet().iterator(); mapIterator.hasNext();) {\n final Entry<String, List<Object>> entry = mapIterator.next();\n final String key = entry.getKey();\n if (key != null) {\n final String keyEncoded = URLEncoder.encode(key, DEFAULT_ENCODING);\n final List<Object> values = entry.getValue();\n sb.append(keyEncoded);\n sb.append('=');\n if (values != null) {\n for (final Iterator<Object> listIt = values.iterator(); listIt.hasNext();) {\n final Object valueObject = listIt.next();\n sb.append(valueObject != null ? URLEncoder.encode(valueObject.toString(), DEFAULT_ENCODING) : \"\");\n if (listIt.hasNext()) {\n sb.append('&');\n sb.append(keyEncoded);\n sb.append('=');\n }\n }\n }\n if (mapIterator.hasNext()) {\n sb.append('&');\n }\n } else {\n // Do what you want...for example:\n assert false : String.format(\"Null key in query map: %s\", map.entrySet());\n }\n }\n return sb.toString();\n } catch (final UnsupportedEncodingException e) {\n throw new UnsupportedOperationException(e);\n }\n }\n\n public static void main(final String[] args) {\n // Examples: could be turned into unit tests ...\n {\n final LinkedHashMap<String, Object> queryItems = new LinkedHashMap<String, Object>();\n queryItems.put(\"brand\", \"C&A\");\n queryItems.put(\"count\", null);\n queryItems.put(\"misc\", 42);\n final String buildQueryString = buildQueryString(queryItems);\n System.out.println(buildQueryString);\n }\n {\n final LinkedHashMap<String, List<Object>> queryItems = new LinkedHashMap<String, List<Object>>();\n queryItems.put(\"usernames\", new ArrayList<Object>(Arrays.asList(new String[] { \"bob\", \"john\" })));\n queryItems.put(\"nullValue\", null);\n queryItems.put(\"misc\", new ArrayList<Object>(Arrays.asList(new Integer[] { 1, 2, 3 })));\n final String buildQueryString = buildQueryStringMulti(queryItems);\n System.out.println(buildQueryString);\n }\n }\n}\n\nYou may use either simple (easier to write in most cases) or multiple when required. Note that both can be combined by adding an ampersand...\nIf you find any problems let me know in the comments.\n",
"This is the solution I implemented, using Java 8 and org.apache.http.client.URLEncodedUtils. It maps the entries of the map into a list of BasicNameValuePair and then uses Apache's URLEncodedUtils to turn that into a query string.\nList<BasicNameValuePair> nameValuePairs = params.entrySet().stream()\n .map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))\n .collect(Collectors.toList());\n\nURLEncodedUtils.format(nameValuePairs, Charset.forName(\"UTF-8\"));\n\n",
"Using EntrySet and Streams: \nmap\n .entrySet()\n .stream()\n .map(e -> e.getKey() + \"=\" + e.getValue())\n .collect(Collectors.joining(\"&\"));\n\n",
"There's nothing built into java to do this. But, hey, java is a programming language, so.. let's program it!\nmap.entrySet().stream().map(e -> e.getKey() + \"=\" + e.getValue()).collect(Collectors.joining(\"&\"))\n\nThis gives you \"param1=12¶m2=cat\". Now we need to join the URL and this bit together. You'd think you can just do: URL + \"?\" + theAbove but if the URL already contains a question mark, you have to join it all together with \"&\" instead. One way to check is to see if there's a question mark in the URL someplace already.\nAlso, I don't quite know what is in your map. If it's raw stuff, you probably have to safeguard the call to e.getKey() and e.getValue() with URLEncoder.encode or similar.\nYet another way to go is that you take a wider view. Are you trying to append a map's content to a URL, or... are you trying to make an HTTP(S) request from a java process with the stuff in the map as (additional) HTTP params? In the latter case, you can look into an http library like OkHttp which has some nice APIs to do this job, then you can forego any need to mess about with that URL in the first place.\n",
"You can use a Stream for this, but instead of appending query parameters myself I'd use a Uri.Builder. For example:\nfinal Map<String, String> map = new HashMap<>();\nmap.put(\"param1\", \"cat\");\nmap.put(\"param2\", \"12\");\n\nfinal Uri uri = \n map.entrySet().stream().collect(\n () -> Uri.parse(\"relativeUrl\").buildUpon(),\n (builder, e) -> builder.appendQueryParameter(e.getKey(), e.getValue()),\n (b1, b2) -> { throw new UnsupportedOperationException(); }\n ).build();\n\n//Or, if you consider it more readable...\nfinal Uri.Builder builder = Uri.parse(\"relativeUrl\").buildUpon();\nmap.entrySet().forEach(e -> builder.appendQueryParameter(e.getKey(), e.getValue())\nfinal Uri uri = builder.build();\n\n//... \n\nassertEquals(Uri.parse(\"relativeUrl?param1=cat¶m2=12\"), uri);\n\n",
"I think this is better for memory usage and performance, and I want to send just the property name when the value is null.\npublic static String toUrlEncode(Map<String, Object> map) {\n StringBuilder sb = new StringBuilder();\n map.entrySet().stream()\n .forEach(entry\n -> (entry.getValue() == null\n ? sb.append(entry.getKey())\n : sb.append(entry.getKey())\n .append('=')\n .append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8)))\n .append('&')\n );\n sb.delete(sb.length() - 1, sb.length());\n return sb.toString();\n}\n\n",
"Here's a simple kotlin solution:\nfun Map<String, String>.toUrlParams(): String =\n entries.joinToString(\"&\") {\n it.key.toUrlEncoded() + \"=\" + it.value.toUrlEncoded()\n }\n\nfun String.toUrlEncoded(): String = URLEncoder.encode(\n this, StandardCharsets.UTF_8\n)\n\n",
"To improve a little bit upon @eclipse's answer: In Javaland a request parameter map is usually represented as a Map<String, String[]>, a Map<String, List<String>> or possibly some kind of MultiValueMap<String, String> which is sort of the same thing. In any case: a parameter can usually have multiple values. A Java 8 solution would therefore be something along these lines:\npublic String getQueryString(HttpServletRequest request, String encoding) {\n Map<String, String[]> parameters = request.getParameterMap();\n\n return parameters.entrySet().stream()\n .flatMap(entry -> encodeMultiParameter(entry.getKey(), entry.getValue(), encoding))\n .reduce((param1, param2) -> param1 + \"&\" + param2)\n .orElse(\"\");\n}\n\nprivate Stream<String> encodeMultiParameter(String key, String[] values, String encoding) {\n return Stream.of(values).map(value -> encodeSingleParameter(key, value, encoding));\n}\n\nprivate String encodeSingleParameter(String key, String value, String encoding) {\n return urlEncode(key, encoding) + \"=\" + urlEncode(value, encoding);\n}\n\nprivate String urlEncode(String value, String encoding) {\n try {\n return URLEncoder.encode(value, encoding);\n } catch (UnsupportedEncodingException e) {\n throw new IllegalArgumentException(\"Cannot url encode \" + value, e);\n }\n}\n\n",
"Personally, I'd go for a solution like this, it's incredibly similar to the solution provided by @rzwitserloot, only subtle differences. \nThis solution is small, simple & clean, it requires very little in terms of dependencies, all of which are a part of the Java Util package.\nMap<String, String> map = new HashMap<>();\n\nmap.put(\"param1\", \"12\");\nmap.put(\"param2\", \"cat\");\n\nString output = \"someUrl?\";\noutput += map.entrySet()\n .stream()\n .map(x -> x.getKey() + \"=\" + x.getValue() + \"&\")\n .collect(Collectors.joining(\"&\"));\n\nSystem.out.println(output.substring(0, output.length() -1));\n\n",
"For multivalue map you can do like below (using java 8 stream api's)\nUrl encoding has been taken cared in this.\nMultiValueMap<String, String> params = new LinkedMultiValueMap<>();\nString urlQueryString = params.entrySet()\n .stream()\n .flatMap(stringListEntry -> stringListEntry.getValue()\n .stream()\n .map(s -> UriUtils.encode(stringListEntry.getKey(), StandardCharsets.UTF_8.toString()) + \"=\" +\n UriUtils.encode(s, StandardCharsets.UTF_8.toString())))\n .collect(Collectors.joining(\"&\"));\n\n",
"If you need just the query string (not the whole URL) and you are using Spring Framework, you can do this:\nimport org.springframework.web.util.UriComponentsBuilder;\n\n...\n\nfinal String queryString = UriComponentsBuilder.newInstance()\n .queryParam(\"many\", \"7\", \"14\", \"21\")\n .queryParam(\"single\", \"XYZ\")\n .build()\n .toUri()\n .getQuery();\n\nSystem.out.println(queryString);\n\nthe result is:\nmany=7&many=14&many=21&single=XYZ\n\n",
"a very lightweight answer it works for me\npublic static String queryStr(Map<String, String> data) throws UnsupportedEncodingException {\n String query = \"\";\n for (String key : data.keySet()) {\n query += query.length() < 1 ? \"\" : \"&\";\n query += key + \"=\" + URLEncoder.encode(data.get(key), \"UTF-8\");\n }\n\n return query;\n}\n\n"
] |
[
72,
48,
44,
24,
20,
11,
10,
8,
6,
5,
4,
2,
2,
2,
1,
0,
0,
0,
0
] |
[
"Kotlin\nmapOf(\n \"param1\" to 12,\n \"param2\" to \"cat\"\n).map { \"${it.key}=${it.value}\" }\n .joinToString(\"&\")\n\n"
] |
[
-1
] |
[
"jakarta_ee",
"java",
"utilities"
] |
stackoverflow_0002809877_jakarta_ee_java_utilities.txt
|
Q:
Using lambda to define a function based on another: How do I keep my code generic?
I have some python code that defines a new function based on an old one. It looks like this
def myFunction(a: int, b: int, c: int):
# Do stuff
myNewFunction = lambda a, b: myFunction(a, b, 0)
My new function is the same as the old function, but sets the last argument to 0.
My question: Say I did not know the function took three arguments. Can I make the above solution more generic? An invalid solution with the right intention might be something like:
def myFunction(a: int, b: int, c: int):
# Do stuff
func_args = myFunction.__code__.co_varnames
func_args = func_args[:-1]
myNewFunction = lambda *func_args : myFunction(*func_args, 0)
A:
You're almost correct, you can use functools.partial this way(instead of lambda):
from functools import partial
def myFunction(a: int, b: int, c: int):
print(a, b, c)
last_param_name = myFunction.__code__.co_varnames[-1]
new_func = partial(myFunction, **{last_param_name: 0})
new_func(10, 20)
Technically partial is not a function it's a class but I don't think this is what you concern about.
A pure Python (roughly)equivalent of the original partial exists in documentation if you want it to be a function type:
def partial(func, /, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = {**keywords, **fkeywords}
return func(*args, *fargs, **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
|
Using lambda to define a function based on another: How do I keep my code generic?
|
I have some python code that defines a new function based on an old one. It looks like this
def myFunction(a: int, b: int, c: int):
# Do stuff
myNewFunction = lambda a, b: myFunction(a, b, 0)
My new function is the same as the old function, but sets the last argument to 0.
My question: Say I did not know the function took three arguments. Can I make the above solution more generic? An invalid solution with the right intention might be something like:
def myFunction(a: int, b: int, c: int):
# Do stuff
func_args = myFunction.__code__.co_varnames
func_args = func_args[:-1]
myNewFunction = lambda *func_args : myFunction(*func_args, 0)
|
[
"You're almost correct, you can use functools.partial this way(instead of lambda):\nfrom functools import partial\n\ndef myFunction(a: int, b: int, c: int):\n print(a, b, c)\n\nlast_param_name = myFunction.__code__.co_varnames[-1]\nnew_func = partial(myFunction, **{last_param_name: 0})\n\nnew_func(10, 20)\n\nTechnically partial is not a function it's a class but I don't think this is what you concern about.\nA pure Python (roughly)equivalent of the original partial exists in documentation if you want it to be a function type:\ndef partial(func, /, *args, **keywords):\n def newfunc(*fargs, **fkeywords):\n newkeywords = {**keywords, **fkeywords}\n return func(*args, *fargs, **newkeywords)\n newfunc.func = func\n newfunc.args = args\n newfunc.keywords = keywords\n return newfunc\n\n"
] |
[
1
] |
[] |
[] |
[
"lambda",
"python",
"python_3.x"
] |
stackoverflow_0074670410_lambda_python_python_3.x.txt
|
Q:
Why is Flask making me put @app.route("/interior.html") in route instead of @app.route("/interior")
I am building a website with a booking page that requires me to put the data into a database so I am using python Flask app.
I know that in the @app.route I am only supposed to put @app.route("/exterior") however, whenever I try it using this method I get 404 Page Not Found. Instead I have to put @app.route("/exterior.html"). This is the only way it will work. I believe I have all the correct libraries and I have defined everything correctly; but, it only works if I put .html in the @app.route.
I have researched @app.routes and it only tells me the correct method which I know is @app.route("/exterior"); however, the only thing that works is @app.route("/exterior.html"). If anyone can tell me why this is happening that would be appreciated.
Here is my code.
import os
from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from datetime import datetime
# Configure application - turn this file into a Flask application -
app = Flask(__name__)
# Ensure templates are auto-reloaded -
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///bookings.db")
@app.after_request
def after_request(response):
"""Ensure responses aren't cached"""
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
@app.route("/")
def index():
return render_template("/index.html")
@app.route("/index.html")
def indexpage():
return render_template("/index.html")
@app.route("/exterior.html")
def exterior():
return render_template("exterior.html")
@app.route("/interior")
def interior():
return render_template("interior.html")
if __name__ == 'main':
app.run(debug = True)
As you can see this is resulting me having to use two routes to load my index page. Once for when I initially run flask and again, so I am able to link to the pages in my navbar.
It's also not the correct method and it bothers me that I am not able to do it correctly. Please advise.
Here is my file directory:
project
static
pics
styles.css
templates
index.html
interior.html
exterior.html
about.html
gallery.html
layout.html
booknow.html
app.py
bookings.db
README.md
unsure why app.py and bookings are not before static and templates and alphabetically that would make more sense; however, this is how it is displayed.
A:
I copied your code and made some minor syntax fixes. below is working as normal. perhaps you could copy this and start adding back some of your functionality and see where it goes wrong.
here is the directory structure:
test_app/
app.py
templates/
interior.html
exterior.html
index.html
and here is app.py:
import os
# from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from datetime import datetime
# Configure application - turn this file into a Flask application -
app = Flask(__name__)
# Ensure templates are auto-reloaded -
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Configure CS50 Library to use SQLite database
# db = SQL("sqlite:///bookings.db")
@app.after_request
def after_request(response):
"""Ensure responses aren't cached"""
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
@app.route("/")
def index():
return render_template("index.html")
@app.route("/index/")
def indexpage():
return render_template("index.html")
@app.route("/exterior/")
def exterior():
return render_template("exterior.html")
@app.route("/interior/")
def interior():
return render_template("interior.html")
if __name__ == '__main__':
app.run(debug = True)
this work normally for me. what about you?
|
Why is Flask making me put @app.route("/interior.html") in route instead of @app.route("/interior")
|
I am building a website with a booking page that requires me to put the data into a database so I am using python Flask app.
I know that in the @app.route I am only supposed to put @app.route("/exterior") however, whenever I try it using this method I get 404 Page Not Found. Instead I have to put @app.route("/exterior.html"). This is the only way it will work. I believe I have all the correct libraries and I have defined everything correctly; but, it only works if I put .html in the @app.route.
I have researched @app.routes and it only tells me the correct method which I know is @app.route("/exterior"); however, the only thing that works is @app.route("/exterior.html"). If anyone can tell me why this is happening that would be appreciated.
Here is my code.
import os
from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from datetime import datetime
# Configure application - turn this file into a Flask application -
app = Flask(__name__)
# Ensure templates are auto-reloaded -
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///bookings.db")
@app.after_request
def after_request(response):
"""Ensure responses aren't cached"""
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
@app.route("/")
def index():
return render_template("/index.html")
@app.route("/index.html")
def indexpage():
return render_template("/index.html")
@app.route("/exterior.html")
def exterior():
return render_template("exterior.html")
@app.route("/interior")
def interior():
return render_template("interior.html")
if __name__ == 'main':
app.run(debug = True)
As you can see this is resulting me having to use two routes to load my index page. Once for when I initially run flask and again, so I am able to link to the pages in my navbar.
It's also not the correct method and it bothers me that I am not able to do it correctly. Please advise.
Here is my file directory:
project
static
pics
styles.css
templates
index.html
interior.html
exterior.html
about.html
gallery.html
layout.html
booknow.html
app.py
bookings.db
README.md
unsure why app.py and bookings are not before static and templates and alphabetically that would make more sense; however, this is how it is displayed.
|
[
"I copied your code and made some minor syntax fixes. below is working as normal. perhaps you could copy this and start adding back some of your functionality and see where it goes wrong.\nhere is the directory structure:\ntest_app/\n app.py\n templates/\n interior.html\n exterior.html\n index.html\n\nand here is app.py:\nimport os\n\n# from cs50 import SQL\nfrom flask import Flask, flash, jsonify, redirect, render_template, request, session\nfrom datetime import datetime\n\n# Configure application - turn this file into a Flask application -\napp = Flask(__name__)\n\n# Ensure templates are auto-reloaded -\napp.config[\"TEMPLATES_AUTO_RELOAD\"] = True\n\n# Configure CS50 Library to use SQLite database\n# db = SQL(\"sqlite:///bookings.db\")\n\n\[email protected]_request\ndef after_request(response):\n \"\"\"Ensure responses aren't cached\"\"\"\n response.headers[\"Cache-Control\"] = \"no-cache, no-store, must-revalidate\"\n response.headers[\"Expires\"] = 0\n response.headers[\"Pragma\"] = \"no-cache\"\n return response\n\[email protected](\"/\")\ndef index():\n return render_template(\"index.html\")\n\[email protected](\"/index/\")\ndef indexpage():\n return render_template(\"index.html\")\n\[email protected](\"/exterior/\")\ndef exterior():\n return render_template(\"exterior.html\")\n\n\[email protected](\"/interior/\")\ndef interior():\n return render_template(\"interior.html\")\n\nif __name__ == '__main__':\n app.run(debug = True)\n\nthis work normally for me. what about you?\n"
] |
[
0
] |
[] |
[] |
[
"flask",
"html",
"python"
] |
stackoverflow_0074499442_flask_html_python.txt
|
Q:
AndroidKeyStore KeyPairGenerator Crashes On Small Number of Devices
My application only targets Android 6.0+. In my application I generate a RSA key in the AndroidKeyStore with the following:
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
kpg.initialize(new KeyGenParameterSpec.Builder(
"myKey", KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setCertificateSubject(new X500Principal("CN=myKey"))
.setDigests("SHA-1")
.setEncryptionPaddings("OAEPPadding")
.build());
KeyPair kp = kpg.generateKeyPair();
This works well on 20+ devices that we have tested and nearly 100% percent of our users.
However, there is a small number of users that that application crashes for when kpg.generateKeyPair() is executed with the following:
java.security.ProviderException: Failed to load generated key pair from keystore
at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.loadKeystoreKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:518)
at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.generateKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:470)
at java.security.KeyPairGenerator$Delegate.generateKeyPair(KeyPairGenerator.java:699)
at md5fb78b69c5ddbc157f4db38fd738139a6.MainApplication.n_onCreate(Native Method)
at md5fb78b69c5ddbc157f4db38fd738139a6.MainApplication.onCreate(MainApplication.java:34)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1025)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5448)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1564)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Caused by: java.security.UnrecoverableKeyException: Failed to obtain X.509 form of public key
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePublicKeyFromKeystore(AndroidKeyStoreProvider.java:230)
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(AndroidKeyStoreProvider.java:259)
at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.loadKeystoreKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:509)
... 14 more
Caused by: android.security.KeyStoreException: -22
at android.security.KeyStore.getKeyStoreException(KeyStore.java:676)
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePublicKeyFromKeystore(AndroidKeyStoreProvider.java:231)
... 16 more
java.security.UnrecoverableKeyException: Failed to obtain X.509 form of public key
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePublicKeyFromKeystore(AndroidKeyStoreProvider.java:230)
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(AndroidKeyStoreProvider.java:259)
at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.loadKeystoreKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:509)
at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.generateKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:470)
at java.security.KeyPairGenerator$Delegate.generateKeyPair(KeyPairGenerator.java:699)
at md5fb78b69c5ddbc157f4db38fd738139a6.MainApplication.n_onCreate(Native Method)
at md5fb78b69c5ddbc157f4db38fd738139a6.MainApplication.onCreate(MainApplication.java:34)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1025)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5448)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1564)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Caused by: android.security.KeyStoreException: -22
at android.security.KeyStore.getKeyStoreException(KeyStore.java:676)
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePublicKeyFromKeystore(AndroidKeyStoreProvider.java:231)
... 16 more
android.security.KeyStoreException: -22
at android.security.KeyStore.getKeyStoreException(KeyStore.java:676)
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePublicKeyFromKeystore(AndroidKeyStoreProvider.java:231)
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(AndroidKeyStoreProvider.java:259)
at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.loadKeystoreKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:509)
at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.generateKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:470)
at java.security.KeyPairGenerator$Delegate.generateKeyPair(KeyPairGenerator.java:699)
at md5fb78b69c5ddbc157f4db38fd738139a6.MainApplication.n_onCreate(Native Method)
at md5fb78b69c5ddbc157f4db38fd738139a6.MainApplication.onCreate(MainApplication.java:34)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1025)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5448)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1564)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
The only things I can find on the internet about this Failed to obtain X.509 form of public key error are a few articles with no real solutions. See:
https://github.com/AzureAD/azure-activedirectory-library-for-android/issues/740
https://jira.lineageos.org/browse/BUGBASH-454
The few reports that we have received are from users with OnePlus devices on Android 7.1, which is also one of the devices mentioned in the above articles but there are definitely other devices affected as well.
Why is this happening?
Are there any workarounds?
A:
One potential solution to this issue is to catch the UnrecoverableKeyException that is thrown and handle it gracefully. For example, you could try regenerating the key pair or displaying an error message to the user. This would allow your application to continue functioning even if the key pair generation fails on some devices.
Here is an example of how this could be implemented:
try {
KeyPair kp = kpg.generateKeyPair();
} catch (UnrecoverableKeyException e) {
// Handle the exception here, for example by regenerating the key pair
// or displaying an error message to the user.
}
Alternatively, you could check if the key pair has already been generated before calling generateKeyPair(), and only generate the key pair if it does not already exist. This could prevent the exception from being thrown in the first place.
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
if (!keyStore.containsAlias("myKey")) {
KeyPair kp = kpg.generateKeyPair();
}
Note that these solutions may not work for all cases, and the root cause of the issue may need to be addressed in order to fix it completely. It is also possible that the issue is specific to certain device models or versions of Android, so further investigation may be necessary to determine the cause.
|
AndroidKeyStore KeyPairGenerator Crashes On Small Number of Devices
|
My application only targets Android 6.0+. In my application I generate a RSA key in the AndroidKeyStore with the following:
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
kpg.initialize(new KeyGenParameterSpec.Builder(
"myKey", KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setCertificateSubject(new X500Principal("CN=myKey"))
.setDigests("SHA-1")
.setEncryptionPaddings("OAEPPadding")
.build());
KeyPair kp = kpg.generateKeyPair();
This works well on 20+ devices that we have tested and nearly 100% percent of our users.
However, there is a small number of users that that application crashes for when kpg.generateKeyPair() is executed with the following:
java.security.ProviderException: Failed to load generated key pair from keystore
at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.loadKeystoreKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:518)
at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.generateKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:470)
at java.security.KeyPairGenerator$Delegate.generateKeyPair(KeyPairGenerator.java:699)
at md5fb78b69c5ddbc157f4db38fd738139a6.MainApplication.n_onCreate(Native Method)
at md5fb78b69c5ddbc157f4db38fd738139a6.MainApplication.onCreate(MainApplication.java:34)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1025)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5448)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1564)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Caused by: java.security.UnrecoverableKeyException: Failed to obtain X.509 form of public key
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePublicKeyFromKeystore(AndroidKeyStoreProvider.java:230)
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(AndroidKeyStoreProvider.java:259)
at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.loadKeystoreKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:509)
... 14 more
Caused by: android.security.KeyStoreException: -22
at android.security.KeyStore.getKeyStoreException(KeyStore.java:676)
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePublicKeyFromKeystore(AndroidKeyStoreProvider.java:231)
... 16 more
java.security.UnrecoverableKeyException: Failed to obtain X.509 form of public key
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePublicKeyFromKeystore(AndroidKeyStoreProvider.java:230)
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(AndroidKeyStoreProvider.java:259)
at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.loadKeystoreKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:509)
at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.generateKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:470)
at java.security.KeyPairGenerator$Delegate.generateKeyPair(KeyPairGenerator.java:699)
at md5fb78b69c5ddbc157f4db38fd738139a6.MainApplication.n_onCreate(Native Method)
at md5fb78b69c5ddbc157f4db38fd738139a6.MainApplication.onCreate(MainApplication.java:34)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1025)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5448)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1564)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Caused by: android.security.KeyStoreException: -22
at android.security.KeyStore.getKeyStoreException(KeyStore.java:676)
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePublicKeyFromKeystore(AndroidKeyStoreProvider.java:231)
... 16 more
android.security.KeyStoreException: -22
at android.security.KeyStore.getKeyStoreException(KeyStore.java:676)
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePublicKeyFromKeystore(AndroidKeyStoreProvider.java:231)
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(AndroidKeyStoreProvider.java:259)
at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.loadKeystoreKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:509)
at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.generateKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:470)
at java.security.KeyPairGenerator$Delegate.generateKeyPair(KeyPairGenerator.java:699)
at md5fb78b69c5ddbc157f4db38fd738139a6.MainApplication.n_onCreate(Native Method)
at md5fb78b69c5ddbc157f4db38fd738139a6.MainApplication.onCreate(MainApplication.java:34)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1025)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5448)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1564)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
The only things I can find on the internet about this Failed to obtain X.509 form of public key error are a few articles with no real solutions. See:
https://github.com/AzureAD/azure-activedirectory-library-for-android/issues/740
https://jira.lineageos.org/browse/BUGBASH-454
The few reports that we have received are from users with OnePlus devices on Android 7.1, which is also one of the devices mentioned in the above articles but there are definitely other devices affected as well.
Why is this happening?
Are there any workarounds?
|
[
"One potential solution to this issue is to catch the UnrecoverableKeyException that is thrown and handle it gracefully. For example, you could try regenerating the key pair or displaying an error message to the user. This would allow your application to continue functioning even if the key pair generation fails on some devices.\nHere is an example of how this could be implemented:\ntry {\n KeyPair kp = kpg.generateKeyPair();\n} catch (UnrecoverableKeyException e) {\n // Handle the exception here, for example by regenerating the key pair\n // or displaying an error message to the user.\n}\n\nAlternatively, you could check if the key pair has already been generated before calling generateKeyPair(), and only generate the key pair if it does not already exist. This could prevent the exception from being thrown in the first place.\nKeyStore keyStore = KeyStore.getInstance(\"AndroidKeyStore\");\nkeyStore.load(null);\nif (!keyStore.containsAlias(\"myKey\")) {\n KeyPair kp = kpg.generateKeyPair();\n}\n\nNote that these solutions may not work for all cases, and the root cause of the issue may need to be addressed in order to fix it completely. It is also possible that the issue is specific to certain device models or versions of Android, so further investigation may be necessary to determine the cause.\n"
] |
[
0
] |
[] |
[] |
[
"android",
"android_keystore",
"java",
"keystore"
] |
stackoverflow_0044469020_android_android_keystore_java_keystore.txt
|
Q:
Get all JSON responses from array of Promises
I want to make multiple calls for which I have to wait for the answer, and afterwards I want to group all responses in an array. I've not succeeded to do this.
The res constant in code below still retains the array of promises, not their results. I have no idea what else to try. No other stackoverflow answers have been helpful.
What I've tried:
const getProjectData = async (projectID) => await callAPI(`/projects/${projectID}`);
const solve = async () => {
const projects = [];
currentUserProjectIDs.forEach((project) => {
projects.push(getProjectData(project));
});
console.log("projects", projects);
const res = await Promise.all(projects);
console.log("solve res", res);
return res;
};
const res = await solve();
console.log("res", res);
Below is the result of the last console log:
res [
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: null },
[Symbol(Response internals)]: {
url: 'http://localhost:4000/projects/1',
status: 200,
statusText: 'OK',
headers: [Headers],
counter: 0
}
},
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: null },
[Symbol(Response internals)]: {
url: 'http://localhost:4000/projects/4',
status: 200,
statusText: 'OK',
headers: [Headers],
counter: 0
}
}
]
callAPI function:
export const callAPI = async (path, body, method = "GET") => {
const config = {
method: method,
headers: {
"Content-Type": "application/json",
},
};
if (body) {
config.body = JSON.stringify(body);
}
const URL = `${process.env.HOST}${path}`;
return await fetch(URL, config);
};
EDIT:
I have tried another way, but still unsuccessful. In the code below, the console.log inside the second .then() logs the correct data, but the returned prj is still an empty array...
const solve = async () => {
const projects = [];
currentUserProjectIDs.map((p) => {
callAPI(`/projects/${p}`)
.then((r) => {
return r.json();
})
.then((a) => {
console.log("a", a);
projects.push(a);
return a;
});
});
return projects;
};
const prj = await solve();
console.log("prj", prj);
A:
Your edit is almost correct, but you have to use the array returned from .map and include the Promise.all from your original post:
const solve = async () => {
const projects = currentUserProjectIDs.map((p) => {
return callAPI(`/projects/${p}`)
.then((r) => {
return r.json();
});
});
return Promise.all(projects);
};
const prj = await solve();
console.log("prj", prj);
Pushing to a separate array won’t work because the code in .then is executed asynchronously.
You will probably also want to handle errors with .catch, I assume you omitted that for brevity.
A:
This is a bit cleaner solution based on your first attempt:
export const callAPI = async (path, body, method = 'GET') => {
const config = {
method: method,
headers: {
'Content-Type': 'application/json'
}
}
if (body) {
config.body = JSON.stringify(body)
}
const URL = `${process.env.HOST}${path}`
const res = await fetch(URL, config)
if (!res.ok) throw new Error('Error fetching data')
return res.json()
}
const getProjectData = (projectID) => callAPI(`/projects/${projectID}`)
const solve = () => {
const projects = currentUserProjectIDs.map((project) => {
return getProjectData(project)
})
return Promise.all(projects)
}
solve()
.then((data) => console.log(data))
.catch((err) => console.error(err))
The problem was (before your first edit) that you never called the json() method of the response, that's why you were getting an array of Response objects.
Let me know if that helps.
A:
You can do so:
const getProjectData = async (projectID) => await callAPI(`/projects/${projectID}`);
const solve = async () => {
const res = await Promise.all(
currentUserProjectIDs
.map(id => getProjectData(id)
.then(res => res.json())
);
return res;
};
const res = await solve();
|
Get all JSON responses from array of Promises
|
I want to make multiple calls for which I have to wait for the answer, and afterwards I want to group all responses in an array. I've not succeeded to do this.
The res constant in code below still retains the array of promises, not their results. I have no idea what else to try. No other stackoverflow answers have been helpful.
What I've tried:
const getProjectData = async (projectID) => await callAPI(`/projects/${projectID}`);
const solve = async () => {
const projects = [];
currentUserProjectIDs.forEach((project) => {
projects.push(getProjectData(project));
});
console.log("projects", projects);
const res = await Promise.all(projects);
console.log("solve res", res);
return res;
};
const res = await solve();
console.log("res", res);
Below is the result of the last console log:
res [
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: null },
[Symbol(Response internals)]: {
url: 'http://localhost:4000/projects/1',
status: 200,
statusText: 'OK',
headers: [Headers],
counter: 0
}
},
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: null },
[Symbol(Response internals)]: {
url: 'http://localhost:4000/projects/4',
status: 200,
statusText: 'OK',
headers: [Headers],
counter: 0
}
}
]
callAPI function:
export const callAPI = async (path, body, method = "GET") => {
const config = {
method: method,
headers: {
"Content-Type": "application/json",
},
};
if (body) {
config.body = JSON.stringify(body);
}
const URL = `${process.env.HOST}${path}`;
return await fetch(URL, config);
};
EDIT:
I have tried another way, but still unsuccessful. In the code below, the console.log inside the second .then() logs the correct data, but the returned prj is still an empty array...
const solve = async () => {
const projects = [];
currentUserProjectIDs.map((p) => {
callAPI(`/projects/${p}`)
.then((r) => {
return r.json();
})
.then((a) => {
console.log("a", a);
projects.push(a);
return a;
});
});
return projects;
};
const prj = await solve();
console.log("prj", prj);
|
[
"Your edit is almost correct, but you have to use the array returned from .map and include the Promise.all from your original post:\nconst solve = async () => {\n const projects = currentUserProjectIDs.map((p) => {\n return callAPI(`/projects/${p}`)\n .then((r) => {\n return r.json();\n });\n });\n return Promise.all(projects);\n };\n\n const prj = await solve();\n console.log(\"prj\", prj);\n\nPushing to a separate array won’t work because the code in .then is executed asynchronously.\nYou will probably also want to handle errors with .catch, I assume you omitted that for brevity.\n",
"This is a bit cleaner solution based on your first attempt:\nexport const callAPI = async (path, body, method = 'GET') => {\n const config = {\n method: method,\n headers: {\n 'Content-Type': 'application/json'\n }\n }\n\n if (body) {\n config.body = JSON.stringify(body)\n }\n\n const URL = `${process.env.HOST}${path}`\n const res = await fetch(URL, config)\n\n if (!res.ok) throw new Error('Error fetching data')\n\n return res.json()\n}\n\nconst getProjectData = (projectID) => callAPI(`/projects/${projectID}`)\n\nconst solve = () => {\n const projects = currentUserProjectIDs.map((project) => {\n return getProjectData(project)\n })\n\n return Promise.all(projects)\n}\n\nsolve()\n .then((data) => console.log(data))\n .catch((err) => console.error(err))\n\nThe problem was (before your first edit) that you never called the json() method of the response, that's why you were getting an array of Response objects.\nLet me know if that helps.\n",
"You can do so:\n const getProjectData = async (projectID) => await callAPI(`/projects/${projectID}`);\n \n const solve = async () => {\n const res = await Promise.all(\n currentUserProjectIDs\n .map(id => getProjectData(id)\n .then(res => res.json())\n );\n return res;\n };\n const res = await solve();\n\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"async_await",
"javascript",
"promise"
] |
stackoverflow_0074669545_async_await_javascript_promise.txt
|
Q:
toString method added dynamically to project
Is there any option to add Lombok's annotation @ToString dynamically (f.e. during building the code) to all classes from the custom package, f.e. xxx.yyy.dao.* ?
I've tried with aspect approach:
declare @type : xxx.yyy.dao.* : @lombok.ToString;
but i got
AJC compiler error: org.aspectj.weaver.patterns.DeclareAnnotation -> Index 1 out of bounds for length 1
I guess it is not allowed as lombok's annotations are also loaded kinda at same compilation time.
The goal is to have toString() method applied by default to all classes from the given package (in such case a developer doesn't need to remember to add @ToString manually to each class).
A:
I just noticed that you use a Lombok annotation, but those all have SOURCE retention. It simply does not make any sense to declare a source-level annotation on woven byte code, it is paradoxical. Nevertheless, the AspectJ weaver should be improved to show a proper warning instead of a spurious weaving error.
Actually, this is a known bug since 2011, which I just commented on your behalf:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=366085
In order to solve your problem, you either need to add a source-level preprocessing step to your build which kicks in even before Lombok, or you need to develop some kind of ToStringAspect which generates or intercepts toString methods on the fly, dynamically using reflection to iterate over instance fields and creating a meaningful string representation for them.
|
toString method added dynamically to project
|
Is there any option to add Lombok's annotation @ToString dynamically (f.e. during building the code) to all classes from the custom package, f.e. xxx.yyy.dao.* ?
I've tried with aspect approach:
declare @type : xxx.yyy.dao.* : @lombok.ToString;
but i got
AJC compiler error: org.aspectj.weaver.patterns.DeclareAnnotation -> Index 1 out of bounds for length 1
I guess it is not allowed as lombok's annotations are also loaded kinda at same compilation time.
The goal is to have toString() method applied by default to all classes from the given package (in such case a developer doesn't need to remember to add @ToString manually to each class).
|
[
"I just noticed that you use a Lombok annotation, but those all have SOURCE retention. It simply does not make any sense to declare a source-level annotation on woven byte code, it is paradoxical. Nevertheless, the AspectJ weaver should be improved to show a proper warning instead of a spurious weaving error.\nActually, this is a known bug since 2011, which I just commented on your behalf:\nhttps://bugs.eclipse.org/bugs/show_bug.cgi?id=366085\nIn order to solve your problem, you either need to add a source-level preprocessing step to your build which kicks in even before Lombok, or you need to develop some kind of ToStringAspect which generates or intercepts toString methods on the fly, dynamically using reflection to iterate over instance fields and creating a meaningful string representation for them.\n"
] |
[
2
] |
[] |
[] |
[
"aspectj",
"java",
"lombok"
] |
stackoverflow_0074618269_aspectj_java_lombok.txt
|
Q:
Trying to create a circular rotating menu with 8 radials
I have tried several packages and found the following package fulfilling the purpose to some extent. https://pub.dev/packages/circle_list
One requirement missing in this package is the click-on icon and icon rotating in the center.
A:
I figured it out. With RotateMode.stopRotate everything is working as you wanted it to be, but if you plan to allow the user to rotate it, then the order of elements (indexes) becomes messed up, so in that case, you'll need to figure out how to track the latest position of the first element to know where the start is and where it should go (and I'm not sure if it's even possible with this package).
class Sample extends StatefulWidget {
const Sample({Key? key}) : super(key: key);
@override
State<Sample> createState() => _SampleState();
}
class _SampleState extends State<Sample> with SingleTickerProviderStateMixin {
late AnimationController animationController;
@override
void initState() {
animationController = AnimationController(
upperBound: pi * 2,
vsync: this,
duration: const Duration(seconds: 2),
);
super.initState();
}
@override
void dispose() {
animationController.dispose();
super.dispose();
}
List<int> elements = List.generate(10, (index) => index);
_center(int index) {
final angle = (pi * 2) * (index / 10);
animationController.animateTo(angle);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
drawer: const Drawer(),
body: Center(
child: AnimatedBuilder(
animation: animationController,
builder: ((context, child) {
return CircleList(
onDragEnd: () => {},
initialAngle: -animationController.value - pi / 2,
centerWidget: Text('center'),
rotateMode: RotateMode.stopRotate,
origin: Offset(0, 0),
children: elements
.map(
(index) => IconButton(
onPressed: () => _center(index),
icon: Icon(Icons.notifications),
color: Colors.blue.withOpacity(index * 0.05 + .3),
),
)
.toList(),
);
}),
),
),
);
}
}
A:
To create a circular rotating menu with 8 radials, you can use the Transform widget and a AnimationController to rotate the radials around a central point.
First, create a Stack widget and place the central icon and the 8 radials inside it. Then, create an AnimationController and use it to animate the rotation of the radials around the central icon.
Next, wrap each radial in a Transform widget and use the AnimationController to rotate the Transform widget. This will cause the radial to rotate around the central icon as the animation progresses.
Here's an example of how you could do this:
// Create the AnimationController
final animationController = AnimationController(
duration: const Duration(seconds: 2), // The animation will last 2 seconds
vsync: this, // Use "this" as the TickerProvider
);
// Define the animation curve
final animationCurve = CurvedAnimation(
parent: animationController,
curve: Curves.easeInOut, // Use an easing curve for a smooth animation
);
// Start the animation
animationController.repeat();
return Stack(
children: [
// Central icon
Icon(Icons.favorite),
// Radial 1
Transform.rotate(
angle: animationCurve.value * 2 * pi, // Rotate the radial by 360 degrees
child: Icon(Icons.add),
),
// Radial 2
Transform.rotate(
angle: animationCurve.value * 2 * pi + (2 * pi / 8), // Rotate the radial by 45 degrees
child: Icon(Icons.bookmark),
),
// Radial 3
Transform.rotate(
angle: animationCurve.value * 2 * pi + (2 * pi / 8 * 2), // Rotate the radial by 90 degrees
child: Icon(Icons.share),
),
// Radial 4
Transform.rotate(
angle: animationCurve.value * 2 * pi + (2 * pi / 8 * 3), // Rotate the radial by 135 degrees
child: Icon(Icons.star),
),
// Radial 5
Transform.rotate(
angle: animationCurve.value * 2 * pi + (2 * pi / 8 * 4), // Rotate the radial by 180 degrees
child: Icon(Icons.check),
),
// Radial 6
Transform.rotate(
angle: animationCurve.value * 2 * pi + (2 * pi / 8 * 5), // Rotate the radial by 225 degrees
child: Icon(Icons.print),
),
// Radial 7
Transform.rotate(
angle: animationCurve.value * 2 * pi + (2 * pi / 8 * 6), // Rotate the radial by 270 degrees
child: Icon(Icons.photo),
),
// Radial 8
Transform.rotate(
angle: animationCurve.value * 2 * pi + (2 * pi / 8 * 7), // Rotate the radial by 315 degrees
child: Icon(Icons.map),
),
],
);
In this example, the AnimationController is used to animate the rotation of the radials around the central icon.
|
Trying to create a circular rotating menu with 8 radials
|
I have tried several packages and found the following package fulfilling the purpose to some extent. https://pub.dev/packages/circle_list
One requirement missing in this package is the click-on icon and icon rotating in the center.
|
[
"I figured it out. With RotateMode.stopRotate everything is working as you wanted it to be, but if you plan to allow the user to rotate it, then the order of elements (indexes) becomes messed up, so in that case, you'll need to figure out how to track the latest position of the first element to know where the start is and where it should go (and I'm not sure if it's even possible with this package).\nclass Sample extends StatefulWidget {\n const Sample({Key? key}) : super(key: key);\n @override\n State<Sample> createState() => _SampleState();\n}\n\nclass _SampleState extends State<Sample> with SingleTickerProviderStateMixin {\n late AnimationController animationController;\n\n @override\n void initState() {\n animationController = AnimationController(\n upperBound: pi * 2,\n vsync: this,\n duration: const Duration(seconds: 2),\n );\n super.initState();\n }\n\n @override\n void dispose() {\n animationController.dispose();\n super.dispose();\n }\n\n List<int> elements = List.generate(10, (index) => index);\n\n _center(int index) {\n final angle = (pi * 2) * (index / 10);\n animationController.animateTo(angle);\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(),\n drawer: const Drawer(),\n body: Center(\n child: AnimatedBuilder(\n animation: animationController,\n builder: ((context, child) {\n return CircleList(\n onDragEnd: () => {},\n initialAngle: -animationController.value - pi / 2,\n centerWidget: Text('center'),\n rotateMode: RotateMode.stopRotate,\n origin: Offset(0, 0),\n children: elements\n .map(\n (index) => IconButton(\n onPressed: () => _center(index),\n icon: Icon(Icons.notifications),\n color: Colors.blue.withOpacity(index * 0.05 + .3),\n ),\n )\n .toList(),\n );\n }),\n ),\n ),\n );\n }\n}\n\n",
"To create a circular rotating menu with 8 radials, you can use the Transform widget and a AnimationController to rotate the radials around a central point.\nFirst, create a Stack widget and place the central icon and the 8 radials inside it. Then, create an AnimationController and use it to animate the rotation of the radials around the central icon.\nNext, wrap each radial in a Transform widget and use the AnimationController to rotate the Transform widget. This will cause the radial to rotate around the central icon as the animation progresses.\nHere's an example of how you could do this:\n// Create the AnimationController\nfinal animationController = AnimationController(\n duration: const Duration(seconds: 2), // The animation will last 2 seconds\n vsync: this, // Use \"this\" as the TickerProvider\n);\n\n// Define the animation curve\nfinal animationCurve = CurvedAnimation(\n parent: animationController,\n curve: Curves.easeInOut, // Use an easing curve for a smooth animation\n);\n\n// Start the animation\nanimationController.repeat();\n\nreturn Stack(\n children: [\n // Central icon\n Icon(Icons.favorite),\n // Radial 1\n Transform.rotate(\n angle: animationCurve.value * 2 * pi, // Rotate the radial by 360 degrees\n child: Icon(Icons.add),\n ),\n // Radial 2\n Transform.rotate(\n angle: animationCurve.value * 2 * pi + (2 * pi / 8), // Rotate the radial by 45 degrees\n child: Icon(Icons.bookmark),\n ),\n // Radial 3\n Transform.rotate(\n angle: animationCurve.value * 2 * pi + (2 * pi / 8 * 2), // Rotate the radial by 90 degrees\n child: Icon(Icons.share),\n ),\n // Radial 4\n Transform.rotate(\n angle: animationCurve.value * 2 * pi + (2 * pi / 8 * 3), // Rotate the radial by 135 degrees\n child: Icon(Icons.star),\n ),\n // Radial 5\n Transform.rotate(\n angle: animationCurve.value * 2 * pi + (2 * pi / 8 * 4), // Rotate the radial by 180 degrees\n child: Icon(Icons.check),\n ),\n // Radial 6\n Transform.rotate(\n angle: animationCurve.value * 2 * pi + (2 * pi / 8 * 5), // Rotate the radial by 225 degrees\n child: Icon(Icons.print),\n ),\n // Radial 7\n Transform.rotate(\n angle: animationCurve.value * 2 * pi + (2 * pi / 8 * 6), // Rotate the radial by 270 degrees\n child: Icon(Icons.photo),\n ),\n // Radial 8\n Transform.rotate(\n angle: animationCurve.value * 2 * pi + (2 * pi / 8 * 7), // Rotate the radial by 315 degrees\n child: Icon(Icons.map),\n ),\n ],\n);\n\nIn this example, the AnimationController is used to animate the rotation of the radials around the central icon.\n"
] |
[
0,
0
] |
[] |
[] |
[
"dart",
"flutter",
"flutter_layout",
"menu"
] |
stackoverflow_0074497777_dart_flutter_flutter_layout_menu.txt
|
Q:
How to delete a django JWT token?
I am using the Django rest framework JSON Web token API that is found here on github (https://github.com/GetBlimp/django-rest-framework-jwt/tree/master/).
I can successfully create tokens and use them to call protected REST APis. However, there are certain cases where I would like to delete a specific token before its expiry time. So I thought to do this with a view like:
class Logout(APIView):
permission_classes = (IsAuthenticated, )
authentication_classes = (JSONWebTokenAuthentication, )
def post(self, request):
# simply delete the token to force a login
request.auth.delete() # This will not work
return Response(status=status.HTTP_200_OK)
The request.auth is simply a string object. So, this is of course, not going to work but I was not sure how I can clear the underlying token.
EDIT
Reading more about this, it seems that I do not need to do anything as nothing is ever stored on the server side with JWT. So just closing the application and regenerating the token on the next login is enough. Is that correct?
A:
The biggest disadvantage of JWT is that because the server does not save the session state, it is not possible to abolish a token or change the token's permissions during use. That is, once the JWT is signed, it will remain in effect until it expires, unless the server deploys additional logic.
So, you cannot invalidate the token even you create a new token or refresh it. Simply way to logout is remove the token from the client.
A:
Yes, it's correct to say that JWT tokens are not stored in the database. What you want, though, is to invalidate a token based on user activity, which doesn't seem to be possible ATM.
So, you can do what you suggested in your question, or redirect the user to some token refreshing endpoint, or even manually create a new token.
A:
Add this in Admin.py
class OutstandingTokenAdmin(token_blacklist.admin.OutstandingTokenAdmin):
def has_delete_permission(self, *args, **kwargs):
return True # or whatever logic you want
admin.site.unregister(token_blacklist.models.OutstandingToken)
admin.site.register(token_blacklist.models.OutstandingToken, OutstandingTokenAdmin)
A:
from rest_framework_simplejwt.token_blacklist.admin import OutstandingTokenAdmin
from rest_framework_simplejwt.token_blacklist.models import OutstandingToken
class OutstandingTokenAdmin(OutstandingTokenAdmin):
def has_delete_permission(self, *args, **kwargs):
return True # or whatever logic you want
def get_actions(self, request):
actions = super(OutstandingTokenAdmin, self).get_actions(request)
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
admin.site.unregister(OutstandingToken)
admin.site.register(OutstandingToken, OutstandingTokenAdmin)
|
How to delete a django JWT token?
|
I am using the Django rest framework JSON Web token API that is found here on github (https://github.com/GetBlimp/django-rest-framework-jwt/tree/master/).
I can successfully create tokens and use them to call protected REST APis. However, there are certain cases where I would like to delete a specific token before its expiry time. So I thought to do this with a view like:
class Logout(APIView):
permission_classes = (IsAuthenticated, )
authentication_classes = (JSONWebTokenAuthentication, )
def post(self, request):
# simply delete the token to force a login
request.auth.delete() # This will not work
return Response(status=status.HTTP_200_OK)
The request.auth is simply a string object. So, this is of course, not going to work but I was not sure how I can clear the underlying token.
EDIT
Reading more about this, it seems that I do not need to do anything as nothing is ever stored on the server side with JWT. So just closing the application and regenerating the token on the next login is enough. Is that correct?
|
[
"The biggest disadvantage of JWT is that because the server does not save the session state, it is not possible to abolish a token or change the token's permissions during use. That is, once the JWT is signed, it will remain in effect until it expires, unless the server deploys additional logic. \n So, you cannot invalidate the token even you create a new token or refresh it. Simply way to logout is remove the token from the client.\n",
"Yes, it's correct to say that JWT tokens are not stored in the database. What you want, though, is to invalidate a token based on user activity, which doesn't seem to be possible ATM.\nSo, you can do what you suggested in your question, or redirect the user to some token refreshing endpoint, or even manually create a new token.\n",
"Add this in Admin.py\nclass OutstandingTokenAdmin(token_blacklist.admin.OutstandingTokenAdmin):\n def has_delete_permission(self, *args, **kwargs):\n return True # or whatever logic you want\n\nadmin.site.unregister(token_blacklist.models.OutstandingToken)\nadmin.site.register(token_blacklist.models.OutstandingToken, OutstandingTokenAdmin)\n\n",
"from rest_framework_simplejwt.token_blacklist.admin import OutstandingTokenAdmin\nfrom rest_framework_simplejwt.token_blacklist.models import OutstandingToken\nclass OutstandingTokenAdmin(OutstandingTokenAdmin):\ndef has_delete_permission(self, *args, **kwargs):\nreturn True # or whatever logic you want\ndef get_actions(self, request):\n actions = super(OutstandingTokenAdmin, self).get_actions(request)\n if 'delete_selected' in actions:\n del actions['delete_selected']\n return actions\n\nadmin.site.unregister(OutstandingToken)\nadmin.site.register(OutstandingToken, OutstandingTokenAdmin)\n"
] |
[
9,
7,
2,
0
] |
[] |
[] |
[
"django",
"jwt",
"python",
"rest"
] |
stackoverflow_0040604877_django_jwt_python_rest.txt
|
Q:
Why don't absolute paths work when importing a typescript file into another typescript file, but are otherwise ok?
2nd EDIT: As soon as I tried to reference Types inside a function, it broke and required the relative import(before, it was only referenced as a parameter and that was fine). I've tried so many solutions to absolute path problems. Consider the following as the main crux of the issue: Absolute paths work for js files importing ts files, js files importing js files, and ts files importing js files, but not ts files importing ts files. That seems like an issue with my tsconfig but as far as I can see it looks right.
1st EDIT: New light has been shed on the below. Consider this part the main crux of the question and the rest as background material. I am converting an existing React Native project to Typescript. I am importing two ts files into another ts file. One works and one doesn't.
Works: import * as Types from 'app/lib/api/interfaces'
Doesn't work: import * as API from 'app/lib/api/index'
The only difference is that Types contains only interfaces and types, and API contains functions that make calls to my backend. Why would one work and the other one not?(A relative import does work)
I am converting an existing React Native project to Typescript. I was able to import a ts file into a js file like this (I read that you have to be explicit when doing this and it didn't work without the extension):
import * as API from 'app/lib/api/index.ts'
As soon as I converted the js file doing the importing to ts, I got this typescript error but the app still built:
An import path cannot end with a '.ts' extension.
When I removed the extension from the import(how I do all my imports):
import * as API from 'app/lib/api/index'
The typescript error went away but the app failed to build and I got the infamous:
app/lib/api/index could not be found within the project or in these
directories: node_modules, etc.
I spent many hours reading articles, Stack, trying different configurations with my config files (see commented out code in examples below) and nothing worked until I stumbled upon this:
Instead of:
import * as API from 'app/lib/api/index';
I did:
import type * as API from 'app/lib/api/index';
And it built ok with no error and all functionality seems to work! However, now I'm getting another typescript error:
'API' cannot be used as a value because it was imported using 'import
type'.
So, that's not right. I think I need to go back to the drawing board.
Using a relative import worked but this is ugly and non-relative/absolute imports work everywhere else so I'd like to avoid this:
import * as API from '../../lib/api/index'
Thanks in advance for anyone's help!
Previous things I tried:
Clearing watchman and metro cache.
Setting paths in tsconfig.json and alias in .babelrc (see below).
Removing index from the path: import * as API from 'app/lib/api
Using a js file extention: import * as API from 'app/lib/api/index.js'
Reinstalling node_modules and pods, restarting the TS Server, VSCode, my computer.
Adding the following to my .eslintrc.js in different combinations:
// Tried to attempt this in `.babelrc` as well but couldn't figure out how.
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx']
}
extends: [
'plugin:import/typescript',
]
plugins: [
'@typescript-eslint',
]
// Installed eslint-import-resolver-typescript and added:
settings: {
'import/resolver': {
typescript: {}
},
},
Tried these in different combinations in both settings and rules nodes:
'import/extensions': 0
'import/resolver': {
'babel-module': {
"extensions": [".js", ".jsx", ".ts", ".tsx"],
"alias": {
"app/*": "./app/*"
}
},
node: {
paths: ["."]
extensions: [".js", ".jsx", ".ts", ".tsx"],
moduleDirectory: ['node_modules', '.'],
}
}
Non-relative imports are working besides this one so I don't think it has anything to do with tsconfig. My gut says the issue might be with my eslint configuration, or maybe my metro.config.js, but of course I could be wrong!
.eslintrc.js:
module.exports = {
env: {
browser: true,
es6: true,
},
// resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
extends: [
'plugin:react/recommended',
'airbnb',
'airbnb-typescript',
// 'plugin:import/typescript',
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
},
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 2020,
sourceType: 'module',
project: `./tsconfig.json`,
},
plugins: [
'react',
'import',
// '@typescript-eslint'
],
rules: {
'react/no-did-update-set-state': 'off',
'react/prop-types': 'off',
// 'import/resolver': {
// "node": {
// "extensions": [".js", ".jsx", ".ts", ".tsx"],
// moduleDirectory: ['node_modules', '.'],
// },
// }
// 'import/extensions': 0
},
settings: {
'import/resolver': {
'babel-module': {
//"extensions": [".js", ".jsx", ".ts", ".tsx"],
//"alias": {
//"app/lib/api/index": "./app/lib/api/index.ts"
}
},
// typescript: {},
// node: {
// extensions: [".js", ".jsx", ".ts", ".tsx"],
// moduleDirectory: ['node_modules', '.'],
// },
}
// 'import/extensions': 0
},
};
metro.config.js:
module.exports = {
resolver: {
sourceExts: ['jsx', 'js', 'ts', 'tsx'],
},
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
};
For good measure:
.babelrc:
{
"presets": ["module:metro-react-native-babel-preset"],
"plugins": [
["module-resolver", {
"root": ["."]
// "alias": {
// "app/*": "app/*" (Also tried "./app/*")
// }
}]
]
}
tsconfig.json:
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "esnext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"lib": ["es2017"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
"jsx": "react-native", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
// "module": "commonjs", /* Specify what module code is generated. */
// "rootDir": ".", /* Specify the root folder within your source files. */
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
"baseUrl": ".", /* Specify the base directory to resolve non-relative module names. */
// "paths": {
// "app/*": ["app/*"]
// }, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
"types": ["react-native", "jest"], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
"allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "tsbuild", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
"noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
"isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
"allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
// "skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"exclude": [
"node_modules",
".babelrc",
"metro.config.js",
"jest.config.js"
]
}
A:
Absolute paths do not work when importing a TypeScript file into another TypeScript file because TypeScript uses a module resolution strategy to determine how to locate and load modules. This strategy is similar to the way that Node.js resolves modules, and is based on the concept of a "module path".
When using absolute paths to import a TypeScript file, the module path is determined by the location of the file on the file system. This can cause problems when the file is moved or renamed, as the module path will no longer be valid. Additionally, the module path may be different on different machines or in different environments, which can cause inconsistencies and errors.
To avoid these problems, TypeScript recommends using relative paths when importing one TypeScript file into another. Relative paths are based on the relative location of the files on the file system, and are not affected by changes to the file names or locations. This makes them more flexible and reliable than absolute paths.
For example, instead of using an absolute path like this:
import { SomeClass } from '/path/to/some/file';
You can use a relative path like this:
import { SomeClass } from '../some/file';
This will make the import more robust and easier to maintain, and will help avoid errors and inconsistencies when working with multiple TypeScript files.
|
Why don't absolute paths work when importing a typescript file into another typescript file, but are otherwise ok?
|
2nd EDIT: As soon as I tried to reference Types inside a function, it broke and required the relative import(before, it was only referenced as a parameter and that was fine). I've tried so many solutions to absolute path problems. Consider the following as the main crux of the issue: Absolute paths work for js files importing ts files, js files importing js files, and ts files importing js files, but not ts files importing ts files. That seems like an issue with my tsconfig but as far as I can see it looks right.
1st EDIT: New light has been shed on the below. Consider this part the main crux of the question and the rest as background material. I am converting an existing React Native project to Typescript. I am importing two ts files into another ts file. One works and one doesn't.
Works: import * as Types from 'app/lib/api/interfaces'
Doesn't work: import * as API from 'app/lib/api/index'
The only difference is that Types contains only interfaces and types, and API contains functions that make calls to my backend. Why would one work and the other one not?(A relative import does work)
I am converting an existing React Native project to Typescript. I was able to import a ts file into a js file like this (I read that you have to be explicit when doing this and it didn't work without the extension):
import * as API from 'app/lib/api/index.ts'
As soon as I converted the js file doing the importing to ts, I got this typescript error but the app still built:
An import path cannot end with a '.ts' extension.
When I removed the extension from the import(how I do all my imports):
import * as API from 'app/lib/api/index'
The typescript error went away but the app failed to build and I got the infamous:
app/lib/api/index could not be found within the project or in these
directories: node_modules, etc.
I spent many hours reading articles, Stack, trying different configurations with my config files (see commented out code in examples below) and nothing worked until I stumbled upon this:
Instead of:
import * as API from 'app/lib/api/index';
I did:
import type * as API from 'app/lib/api/index';
And it built ok with no error and all functionality seems to work! However, now I'm getting another typescript error:
'API' cannot be used as a value because it was imported using 'import
type'.
So, that's not right. I think I need to go back to the drawing board.
Using a relative import worked but this is ugly and non-relative/absolute imports work everywhere else so I'd like to avoid this:
import * as API from '../../lib/api/index'
Thanks in advance for anyone's help!
Previous things I tried:
Clearing watchman and metro cache.
Setting paths in tsconfig.json and alias in .babelrc (see below).
Removing index from the path: import * as API from 'app/lib/api
Using a js file extention: import * as API from 'app/lib/api/index.js'
Reinstalling node_modules and pods, restarting the TS Server, VSCode, my computer.
Adding the following to my .eslintrc.js in different combinations:
// Tried to attempt this in `.babelrc` as well but couldn't figure out how.
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx']
}
extends: [
'plugin:import/typescript',
]
plugins: [
'@typescript-eslint',
]
// Installed eslint-import-resolver-typescript and added:
settings: {
'import/resolver': {
typescript: {}
},
},
Tried these in different combinations in both settings and rules nodes:
'import/extensions': 0
'import/resolver': {
'babel-module': {
"extensions": [".js", ".jsx", ".ts", ".tsx"],
"alias": {
"app/*": "./app/*"
}
},
node: {
paths: ["."]
extensions: [".js", ".jsx", ".ts", ".tsx"],
moduleDirectory: ['node_modules', '.'],
}
}
Non-relative imports are working besides this one so I don't think it has anything to do with tsconfig. My gut says the issue might be with my eslint configuration, or maybe my metro.config.js, but of course I could be wrong!
.eslintrc.js:
module.exports = {
env: {
browser: true,
es6: true,
},
// resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
extends: [
'plugin:react/recommended',
'airbnb',
'airbnb-typescript',
// 'plugin:import/typescript',
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
},
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 2020,
sourceType: 'module',
project: `./tsconfig.json`,
},
plugins: [
'react',
'import',
// '@typescript-eslint'
],
rules: {
'react/no-did-update-set-state': 'off',
'react/prop-types': 'off',
// 'import/resolver': {
// "node": {
// "extensions": [".js", ".jsx", ".ts", ".tsx"],
// moduleDirectory: ['node_modules', '.'],
// },
// }
// 'import/extensions': 0
},
settings: {
'import/resolver': {
'babel-module': {
//"extensions": [".js", ".jsx", ".ts", ".tsx"],
//"alias": {
//"app/lib/api/index": "./app/lib/api/index.ts"
}
},
// typescript: {},
// node: {
// extensions: [".js", ".jsx", ".ts", ".tsx"],
// moduleDirectory: ['node_modules', '.'],
// },
}
// 'import/extensions': 0
},
};
metro.config.js:
module.exports = {
resolver: {
sourceExts: ['jsx', 'js', 'ts', 'tsx'],
},
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
};
For good measure:
.babelrc:
{
"presets": ["module:metro-react-native-babel-preset"],
"plugins": [
["module-resolver", {
"root": ["."]
// "alias": {
// "app/*": "app/*" (Also tried "./app/*")
// }
}]
]
}
tsconfig.json:
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "esnext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"lib": ["es2017"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
"jsx": "react-native", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
// "module": "commonjs", /* Specify what module code is generated. */
// "rootDir": ".", /* Specify the root folder within your source files. */
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
"baseUrl": ".", /* Specify the base directory to resolve non-relative module names. */
// "paths": {
// "app/*": ["app/*"]
// }, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
"types": ["react-native", "jest"], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
"allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "tsbuild", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
"noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
"isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
"allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
// "skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"exclude": [
"node_modules",
".babelrc",
"metro.config.js",
"jest.config.js"
]
}
|
[
"Absolute paths do not work when importing a TypeScript file into another TypeScript file because TypeScript uses a module resolution strategy to determine how to locate and load modules. This strategy is similar to the way that Node.js resolves modules, and is based on the concept of a \"module path\".\nWhen using absolute paths to import a TypeScript file, the module path is determined by the location of the file on the file system. This can cause problems when the file is moved or renamed, as the module path will no longer be valid. Additionally, the module path may be different on different machines or in different environments, which can cause inconsistencies and errors.\nTo avoid these problems, TypeScript recommends using relative paths when importing one TypeScript file into another. Relative paths are based on the relative location of the files on the file system, and are not affected by changes to the file names or locations. This makes them more flexible and reliable than absolute paths.\nFor example, instead of using an absolute path like this:\nimport { SomeClass } from '/path/to/some/file';\n\nYou can use a relative path like this:\nimport { SomeClass } from '../some/file';\n\nThis will make the import more robust and easier to maintain, and will help avoid errors and inconsistencies when working with multiple TypeScript files.\n"
] |
[
0
] |
[] |
[] |
[
"es6_modules",
"eslint",
"typescript"
] |
stackoverflow_0074453006_es6_modules_eslint_typescript.txt
|
Q:
Javascript for card shuffle failing
Over my head with javascript. I'm trying to get the cards to shuffle when clicking next.
Currently, it moves forward with one random shuffle and stops. Back and forward buttons then no longer work at that point.
Please help—many thanks.
When I'm lost and unsure what sample of the code to pinpoint, the captions go up to 499. The sample is also here: https://rrrhhhhhhhhh.github.io/sentences/
Very new to javascript. So any help is greatly appreciated. Very open to better ways to achieve this???
How I have it set up:
HTML:
var r = -1;
var mx = 499; // maximum
var a = new Array();
function AddNumsToDict(){
var m,n,i,j;
i = 0;
j = 0;
while (i <= 499)
{
m = (500 * Math.random()) + 1;
n = Math.floor(m);
for (j=0;j<=499;j++)
{
if (a[j] == (n-1))
{
j = -1;
break;
}
}
if (j != -1)
{
//a.push(n-1);
a[i] = (n-1);
i++;
j=0;
}
}
return;
}
function startup()
{
writit('SENTENCES<br><br><br>Robert Grenier', 'test');
SetCookie("pg", -1);
AddNumsToDict();
}
function SetCookie(sName, sValue)
{
document.cookie = sName + "=" + escape(sValue) + ";"
}
function GetCookie(sName)
{
// cookies are separated by semicolons
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
// a cookie with the requested name does not exist
return null;
}
function doBack(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
//if ((oNxt) && (oPrev))
//{
var num = GetCookie("pg");
if (num == mx){ //maximum
SetCookie("pg",parseInt(num) - 1);
num = GetCookie("pg");
}
// oNxt.disabled = false;
// if (num <= 1){
// oPrev.disabled = true;
// }
if (num >= 1){
num--;
writit(Caption[a[num]], 'test');
SetCookie("pg",num);
}
//}
}
function doNext(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
// if ((oNxt) && (oPrev))
// {
var num = GetCookie("pg");
// if (num > -1){
// oPrev.disabled = false;
// }
// else{
// oPrev.disabled = true;
// }
// if (num >= parseInt(mx)-1){ //maximum - 1
// oNxt.disabled = true;
// }
// else {
// oNxt.disabled = false;
// }
if (num <= parseInt(mx)-2){
num++;
writit(Caption[a[num]],'test');
SetCookie("pg",num);
}
// }
}
function writit(text,id)
{
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = '';
x.innerHTML = text;
}
else if (document.all)
{
x = document.all[id];
x.innerHTML = text;
}
else if (document.layers)
{
x = document.layers[id];
l = (480-(getNumLines(text)*8))/2;
w = (764-(getWidestLine(text)*8))/2;
text2 = '<td id=rel align="center" CLASS="testclass" style="font:12px courier,courier new;padding-left:' + w.toString() + 'px' + ';padding-top:' + l.toString() + 'px' + '">' + text + '</td>';
x.document.open();
x.document.write(text2);
x.document.close();
}
}
function getNumLines(mystr)
{
var a = mystr.split("<br>")
return(a.length);
}
function getWidestLine(mystr)
{
if (mystr.indexOf(" ") != -1)
{
re = / */g;
mystr = mystr.replace(re,"Z");
//alert(mystr);
}
if (mystr.indexOf("<u>") != -1)
{
re = /<u>*/g;
mystr = mystr.replace(re, "");
re = /<\/u>*/g;
mystr = mystr.replace(re, "");
}
if (mystr.indexOf("<br>") != -1)
{
var ss, t;
var lngest;
ss = mystr.split("<br>");
lngest = ss[0].length;
for (t=0; t < ss.length; t++)
{
if (ss[t].length > lngest)
{
lngest = ss[t].length;
}
}
}
else {
lngest = mystr.length;
}
return(lngest);
}
// -->
</script>
<body bgcolor="gainsboro" onload="startup();">
<table bgcolor="white" border height="480px" width="764px" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table nowrap>
<tr>
<td><img width="700px" height="1px" src="./resources/images/w.gif"></td>
<td>
<div class="testclass" id="test"></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<center>
<form>
<p>
<input type="button" onclick="doBack(); return false" value="Back">
<input type="button" onclick="doNext(); return false" value="Next">
JS:
var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };
if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }
{
let window = _____WB$wombat$assign$function_____("window");
let self = _____WB$wombat$assign$function_____("self");
let document = _____WB$wombat$assign$function_____("document");
let location = _____WB$wombat$assign$function_____("location");
let top = _____WB$wombat$assign$function_____("top");
let parent = _____WB$wombat$assign$function_____("parent");
let frames = _____WB$wombat$assign$function_____("frames");
let opener = _____WB$wombat$assign$function_____("opener");
function CaptionArray(len) {
this.length=len
}
Caption = new CaptionArray(499);
Caption[0] = "leaf and the ants as latterly"
Caption[1] = "thought<br>living in<br>Davis would<br>be ok"
Caption[2] = "sure arm today"
Caption[3] = "AMY<br><br>no we<br>both do<br>different<br>songs together"
Caption[4] = "much of anything she doesn't like that at all"
Caption[5] = "SUNG AS LAKE<br><br><br>that never wanted back to come"
Caption[6] = "five sound shut doors"
Caption[7] = "oh<br>my nose is<br>so<br>red<br>Obediah<br>dear"
Caption[8] = "these<br>cubes<br>have been<br>on the floor"
Caption[9] = "sweating importunate"
Caption[10] = "all over noises phone rings"
Caption[11] = "I think this is the water supply for Lake Johnsbury"
Caption[12] = "Paw so greasy"
Caption[13] = "BLACK & WHITE RAIN<br><br><br>clear water grey drops<br><br><br>on windshields in a line<br><br><br>of cars progressing slowly<br><br><br>with windshield wipers wiping"
Caption[14] = "EMILY<br><br>Roger,<br><br>are you<br><br>thinking of me"
Caption[15] = "STICKS<br><br><br>rhythm is inside the sound like another"
Caption[16] = "I think their dog always barks when coming back from the woods"
Caption[17] = "weren't there<br><br>conversations"
Caption[18] = "LOOKING AT FIRE<br><br><u>ashes</u> to ashes<br><br>looking at the fire<br><br>at has been added"
Caption[19] = "a the bank"
}
A:
It looks like you're trying to implement a shuffle function for a collection of sentences in JavaScript. In order to achieve this, you can create a function that shuffles the sentences in the Caption array and then use that function to shuffle the sentences each time the user clicks on the "next" button.
Here is an example of how you could implement this:
var Caption = [ "Sentence 1", "Sentence 2", "Sentence 3", ...];
// This function shuffles the elements in the given array
function shuffle(array) {
// loop through the array and swap each element with a random other element in the array
for (var i = 0; i < array.length; i++) {
var j = Math.floor(Math.random() * array.length);
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
// This function is called when the user clicks on the "next" button
function doNext() {
// shuffle the sentences in the Caption array
shuffle(Caption);
// display the next sentence from the Caption array
var num = GetCookie("pg");
if (num <= parseInt(mx) - 2) {
num++;
writit(Caption[num], "test");
SetCookie("pg", num);
}
}
This should allow the user to click on the "next" button to shuffle the sentences and display a new sentence each time. I hope this helps! Let me know if you have any other questions.
|
Javascript for card shuffle failing
|
Over my head with javascript. I'm trying to get the cards to shuffle when clicking next.
Currently, it moves forward with one random shuffle and stops. Back and forward buttons then no longer work at that point.
Please help—many thanks.
When I'm lost and unsure what sample of the code to pinpoint, the captions go up to 499. The sample is also here: https://rrrhhhhhhhhh.github.io/sentences/
Very new to javascript. So any help is greatly appreciated. Very open to better ways to achieve this???
How I have it set up:
HTML:
var r = -1;
var mx = 499; // maximum
var a = new Array();
function AddNumsToDict(){
var m,n,i,j;
i = 0;
j = 0;
while (i <= 499)
{
m = (500 * Math.random()) + 1;
n = Math.floor(m);
for (j=0;j<=499;j++)
{
if (a[j] == (n-1))
{
j = -1;
break;
}
}
if (j != -1)
{
//a.push(n-1);
a[i] = (n-1);
i++;
j=0;
}
}
return;
}
function startup()
{
writit('SENTENCES<br><br><br>Robert Grenier', 'test');
SetCookie("pg", -1);
AddNumsToDict();
}
function SetCookie(sName, sValue)
{
document.cookie = sName + "=" + escape(sValue) + ";"
}
function GetCookie(sName)
{
// cookies are separated by semicolons
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
// a cookie with the requested name does not exist
return null;
}
function doBack(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
//if ((oNxt) && (oPrev))
//{
var num = GetCookie("pg");
if (num == mx){ //maximum
SetCookie("pg",parseInt(num) - 1);
num = GetCookie("pg");
}
// oNxt.disabled = false;
// if (num <= 1){
// oPrev.disabled = true;
// }
if (num >= 1){
num--;
writit(Caption[a[num]], 'test');
SetCookie("pg",num);
}
//}
}
function doNext(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
// if ((oNxt) && (oPrev))
// {
var num = GetCookie("pg");
// if (num > -1){
// oPrev.disabled = false;
// }
// else{
// oPrev.disabled = true;
// }
// if (num >= parseInt(mx)-1){ //maximum - 1
// oNxt.disabled = true;
// }
// else {
// oNxt.disabled = false;
// }
if (num <= parseInt(mx)-2){
num++;
writit(Caption[a[num]],'test');
SetCookie("pg",num);
}
// }
}
function writit(text,id)
{
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = '';
x.innerHTML = text;
}
else if (document.all)
{
x = document.all[id];
x.innerHTML = text;
}
else if (document.layers)
{
x = document.layers[id];
l = (480-(getNumLines(text)*8))/2;
w = (764-(getWidestLine(text)*8))/2;
text2 = '<td id=rel align="center" CLASS="testclass" style="font:12px courier,courier new;padding-left:' + w.toString() + 'px' + ';padding-top:' + l.toString() + 'px' + '">' + text + '</td>';
x.document.open();
x.document.write(text2);
x.document.close();
}
}
function getNumLines(mystr)
{
var a = mystr.split("<br>")
return(a.length);
}
function getWidestLine(mystr)
{
if (mystr.indexOf(" ") != -1)
{
re = / */g;
mystr = mystr.replace(re,"Z");
//alert(mystr);
}
if (mystr.indexOf("<u>") != -1)
{
re = /<u>*/g;
mystr = mystr.replace(re, "");
re = /<\/u>*/g;
mystr = mystr.replace(re, "");
}
if (mystr.indexOf("<br>") != -1)
{
var ss, t;
var lngest;
ss = mystr.split("<br>");
lngest = ss[0].length;
for (t=0; t < ss.length; t++)
{
if (ss[t].length > lngest)
{
lngest = ss[t].length;
}
}
}
else {
lngest = mystr.length;
}
return(lngest);
}
// -->
</script>
<body bgcolor="gainsboro" onload="startup();">
<table bgcolor="white" border height="480px" width="764px" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table nowrap>
<tr>
<td><img width="700px" height="1px" src="./resources/images/w.gif"></td>
<td>
<div class="testclass" id="test"></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<center>
<form>
<p>
<input type="button" onclick="doBack(); return false" value="Back">
<input type="button" onclick="doNext(); return false" value="Next">
JS:
var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };
if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }
{
let window = _____WB$wombat$assign$function_____("window");
let self = _____WB$wombat$assign$function_____("self");
let document = _____WB$wombat$assign$function_____("document");
let location = _____WB$wombat$assign$function_____("location");
let top = _____WB$wombat$assign$function_____("top");
let parent = _____WB$wombat$assign$function_____("parent");
let frames = _____WB$wombat$assign$function_____("frames");
let opener = _____WB$wombat$assign$function_____("opener");
function CaptionArray(len) {
this.length=len
}
Caption = new CaptionArray(499);
Caption[0] = "leaf and the ants as latterly"
Caption[1] = "thought<br>living in<br>Davis would<br>be ok"
Caption[2] = "sure arm today"
Caption[3] = "AMY<br><br>no we<br>both do<br>different<br>songs together"
Caption[4] = "much of anything she doesn't like that at all"
Caption[5] = "SUNG AS LAKE<br><br><br>that never wanted back to come"
Caption[6] = "five sound shut doors"
Caption[7] = "oh<br>my nose is<br>so<br>red<br>Obediah<br>dear"
Caption[8] = "these<br>cubes<br>have been<br>on the floor"
Caption[9] = "sweating importunate"
Caption[10] = "all over noises phone rings"
Caption[11] = "I think this is the water supply for Lake Johnsbury"
Caption[12] = "Paw so greasy"
Caption[13] = "BLACK & WHITE RAIN<br><br><br>clear water grey drops<br><br><br>on windshields in a line<br><br><br>of cars progressing slowly<br><br><br>with windshield wipers wiping"
Caption[14] = "EMILY<br><br>Roger,<br><br>are you<br><br>thinking of me"
Caption[15] = "STICKS<br><br><br>rhythm is inside the sound like another"
Caption[16] = "I think their dog always barks when coming back from the woods"
Caption[17] = "weren't there<br><br>conversations"
Caption[18] = "LOOKING AT FIRE<br><br><u>ashes</u> to ashes<br><br>looking at the fire<br><br>at has been added"
Caption[19] = "a the bank"
}
|
[
"It looks like you're trying to implement a shuffle function for a collection of sentences in JavaScript. In order to achieve this, you can create a function that shuffles the sentences in the Caption array and then use that function to shuffle the sentences each time the user clicks on the \"next\" button.\nHere is an example of how you could implement this:\nvar Caption = [ \"Sentence 1\", \"Sentence 2\", \"Sentence 3\", ...];\n\n// This function shuffles the elements in the given array\nfunction shuffle(array) {\n // loop through the array and swap each element with a random other element in the array\n for (var i = 0; i < array.length; i++) {\n var j = Math.floor(Math.random() * array.length);\n var temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n }\n}\n\n// This function is called when the user clicks on the \"next\" button\nfunction doNext() {\n // shuffle the sentences in the Caption array\n shuffle(Caption);\n\n // display the next sentence from the Caption array\n var num = GetCookie(\"pg\");\n if (num <= parseInt(mx) - 2) {\n num++;\n writit(Caption[num], \"test\");\n SetCookie(\"pg\", num);\n }\n}\n\nThis should allow the user to click on the \"next\" button to shuffle the sentences and display a new sentence each time. I hope this helps! Let me know if you have any other questions.\n"
] |
[
-1
] |
[] |
[] |
[
"css",
"html",
"javascript"
] |
stackoverflow_0074670599_css_html_javascript.txt
|
Q:
What is the ":ABPerson" string in CNContact identifier?
My iOS application checks contacts from time to time and imports new to its own database.
I checks that contact already exists by identifier field, that usually filled by UUID:
CNContactStore *store = [CNContactStore new];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError *error) {
if (granted) {
NSArray *keys = @[CNContactNamePrefixKey,
CNContactGivenNameKey,
CNContactMiddleNameKey,
CNContactFamilyNameKey,
CNContactInstantMessageAddressesKey];
NSString *containerId = store.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&err];
for (CNContact *contact in cnContacts) {
...
NSString *contactId = [contact identifier];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"uuid == %@", contactId]];
...
}
Sometimes identifier excepts UUID contains :ABPerson string (eg 9326A125-3C0A-494F-9E50-BBFCF1140EF0:ABPerson), and such contact appears just one time. Next time appears same contact, but with another UUID and without :ABPerson.
So, my contacts importer considers that they are 2 different contacts and saves them 2 times.
What is the :ABPerson string in CNContact identifier?
I know about AddressBook framework with ABPerson class, but I'm using Contacts framework for work with device contacts, why :ABPerson appears here?
Can I just filter or check this string in the identifier for preventing contacts duplicates?
Are there other strings that may be contained in CNContact identifiers?
A:
Looks like :ABPerson is added when sharing a contact from the Contacts application. By the way, be careful because a shared contact may have a different ID even on a same device.
A:
The :ABPerson string in the CNContact identifier is used to indicate that the contact comes from the user's Address Book. The :ABPerson string is appended to the end of the contact's UUID, which is a unique identifier for the contact. The ABPerson class is part of the Address Book framework, which is used to access and manage the user's address book.
You can filter or check for the :ABPerson string in the CNContact identifier to prevent saving the same contact multiple times. However, it's recommended to use the UUID of the contact to check for duplicates, as it is a unique identifier for the contact and will not change between updates.
Other strings that may be contained in the CNContact identifier include :ABMultiValue and :ABPersonMultiValue, which are used to indicate that the contact has multiple values for a specific property (such as multiple email addresses or phone numbers).
|
What is the ":ABPerson" string in CNContact identifier?
|
My iOS application checks contacts from time to time and imports new to its own database.
I checks that contact already exists by identifier field, that usually filled by UUID:
CNContactStore *store = [CNContactStore new];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError *error) {
if (granted) {
NSArray *keys = @[CNContactNamePrefixKey,
CNContactGivenNameKey,
CNContactMiddleNameKey,
CNContactFamilyNameKey,
CNContactInstantMessageAddressesKey];
NSString *containerId = store.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&err];
for (CNContact *contact in cnContacts) {
...
NSString *contactId = [contact identifier];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"uuid == %@", contactId]];
...
}
Sometimes identifier excepts UUID contains :ABPerson string (eg 9326A125-3C0A-494F-9E50-BBFCF1140EF0:ABPerson), and such contact appears just one time. Next time appears same contact, but with another UUID and without :ABPerson.
So, my contacts importer considers that they are 2 different contacts and saves them 2 times.
What is the :ABPerson string in CNContact identifier?
I know about AddressBook framework with ABPerson class, but I'm using Contacts framework for work with device contacts, why :ABPerson appears here?
Can I just filter or check this string in the identifier for preventing contacts duplicates?
Are there other strings that may be contained in CNContact identifiers?
|
[
"Looks like :ABPerson is added when sharing a contact from the Contacts application. By the way, be careful because a shared contact may have a different ID even on a same device.\n",
"The :ABPerson string in the CNContact identifier is used to indicate that the contact comes from the user's Address Book. The :ABPerson string is appended to the end of the contact's UUID, which is a unique identifier for the contact. The ABPerson class is part of the Address Book framework, which is used to access and manage the user's address book.\nYou can filter or check for the :ABPerson string in the CNContact identifier to prevent saving the same contact multiple times. However, it's recommended to use the UUID of the contact to check for duplicates, as it is a unique identifier for the contact and will not change between updates.\nOther strings that may be contained in the CNContact identifier include :ABMultiValue and :ABPersonMultiValue, which are used to indicate that the contact has multiple values for a specific property (such as multiple email addresses or phone numbers).\n"
] |
[
0,
0
] |
[] |
[] |
[
"cncontact",
"ios",
"objective_c"
] |
stackoverflow_0041379885_cncontact_ios_objective_c.txt
|
Q:
Decimal value rounded up in vb.net
Everytime I execute UPDATE function with decimal values it captures rounded off integer values. Anyone knows what’s the datatype to use? I tried money and float still I’m getting rounded off value.
Here’s my .vb code
cmd.CommandText=“UPDATE [dbo].[transaction] SET Price=@Price WHERE ID=@ID”
cmd.Parameters.Add(“@Price”,SqlDbType,Decimal,18,2).Values=Textbox1.text
cmd.Parameters.Add(“@ID”,SqlDbType,Int).Values=Textbox2.text
SQL Server Datatype
ID(PK,Int,not null)
Price(decimal(18,2),null)
Input: 25.75
Result: 25
Desired Result: 25.75
A:
You need to set Option Strict On - it would have pointed out that there is no overload of .Add which takes (String, SqlDbType, Integer, Integer).
You could use something like:
Dim dv = Decimal.Parse(Textbox1.Text)
cmd.Parameters.Add(New SqlParameter With {
.ParameterName = "@Price",
.SqlDbType = SqlDbType.Decimal,
.Precision = 18,
.Scale = 2,
.Value = dv})
(You should also set Option Strict On as the default for new VB projects.)
|
Decimal value rounded up in vb.net
|
Everytime I execute UPDATE function with decimal values it captures rounded off integer values. Anyone knows what’s the datatype to use? I tried money and float still I’m getting rounded off value.
Here’s my .vb code
cmd.CommandText=“UPDATE [dbo].[transaction] SET Price=@Price WHERE ID=@ID”
cmd.Parameters.Add(“@Price”,SqlDbType,Decimal,18,2).Values=Textbox1.text
cmd.Parameters.Add(“@ID”,SqlDbType,Int).Values=Textbox2.text
SQL Server Datatype
ID(PK,Int,not null)
Price(decimal(18,2),null)
Input: 25.75
Result: 25
Desired Result: 25.75
|
[
"You need to set Option Strict On - it would have pointed out that there is no overload of .Add which takes (String, SqlDbType, Integer, Integer).\nYou could use something like:\nDim dv = Decimal.Parse(Textbox1.Text)\ncmd.Parameters.Add(New SqlParameter With {\n .ParameterName = \"@Price\",\n .SqlDbType = SqlDbType.Decimal,\n .Precision = 18,\n .Scale = 2,\n .Value = dv})\n\n(You should also set Option Strict On as the default for new VB projects.)\n"
] |
[
1
] |
[] |
[] |
[
"sql_server",
"vb.net"
] |
stackoverflow_0074669532_sql_server_vb.net.txt
|
Q:
How to add Java 9 to Android Studio?
I am using Robolectric library and the latest version of it v4.3.1 requires Java 9 to run. I am trying to point JRE on edit configurations but I am not finding Java 9 in the drop-down even though I have already installed it. It would be really helpful if somebody can please explain!
Please check Java 9 installed.
A:
The only workaround to run Robolectric test in the Android Studio is to change JRE for the test task.
Select IDE menu Run -> Edit Configuration and then change the option from the picture to the location of JDK9:
A:
Tests can run on prior versions as a temporary workaround
You will not be able to run Robolectric against SDK 29 for now (27 April 2020), but this will likely be updated in the future. Currently, as all of the answers before me pointed out, there is no support of Java 9 or later in Android Studio.
But if you are here to make your Robolectic tests run you could simply avoid SDK 29 by setting the Robolectric @Config annotation for your class. Robolectric will simply run your tests against all of the supported SDK versions of your app except 29.
Implement
Set the maxSdk and minSdk versions to run on. This can be based on the app's min and max SDK versions, or set to one version like below in order to make tests faster.
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.robolectric.annotation.Config
import org.junit.runner.RunWith
import android.os.Build
@RunWith(AndroidJUnit4::class)
@Config(maxSdk = Build.VERSION_CODES.P, minSdk = Build.VERSION_CODES.P) // Value of Build.VERSION_CODES.P is 28
class TestClass {
...
}
Of course it is just another "ugly" patch, but it will get you going until you'll be able to run tests against all of the desired SDKs, or at least SDK 29 and all below.
A:
So far Android doesn't support Java 9. As per documentation, Android supports all Java 7 features and a part of Java 8 features.
When developing apps for Android, using Java 8 language features is
optional. You can keep your project's source and target compatibility
values set to Java 7, but you still need to compile using JDK 8.
A:
You can't use Java 9, Android only supports till Java 8.
You should use the JDK version that comes with Android Studio, no need for side alone JDK. The current JDK version is based on OpenJDK 8.
A:
I don't guarantee that it will work but you can set JDK to any version from the project Structure Option
File>Project Structure>SDK Location>'change JDK location here'
sorry but it's not working either i have tried to select JDK9 but i got a prompt like this
A:
In Android Studio, under "Build, Execution, Deployment => Gradle => Gradle JDK", you can choose the JDK version. In newer versions of Android Studio like Artic Fox, it comes with JDK11.
|
How to add Java 9 to Android Studio?
|
I am using Robolectric library and the latest version of it v4.3.1 requires Java 9 to run. I am trying to point JRE on edit configurations but I am not finding Java 9 in the drop-down even though I have already installed it. It would be really helpful if somebody can please explain!
Please check Java 9 installed.
|
[
"The only workaround to run Robolectric test in the Android Studio is to change JRE for the test task.\nSelect IDE menu Run -> Edit Configuration and then change the option from the picture to the location of JDK9:\n\n",
"Tests can run on prior versions as a temporary workaround\nYou will not be able to run Robolectric against SDK 29 for now (27 April 2020), but this will likely be updated in the future. Currently, as all of the answers before me pointed out, there is no support of Java 9 or later in Android Studio.\nBut if you are here to make your Robolectic tests run you could simply avoid SDK 29 by setting the Robolectric @Config annotation for your class. Robolectric will simply run your tests against all of the supported SDK versions of your app except 29.\nImplement\nSet the maxSdk and minSdk versions to run on. This can be based on the app's min and max SDK versions, or set to one version like below in order to make tests faster.\nimport androidx.test.ext.junit.runners.AndroidJUnit4\nimport org.robolectric.annotation.Config\nimport org.junit.runner.RunWith\nimport android.os.Build\n\n@RunWith(AndroidJUnit4::class)\n@Config(maxSdk = Build.VERSION_CODES.P, minSdk = Build.VERSION_CODES.P) // Value of Build.VERSION_CODES.P is 28\nclass TestClass {\n...\n}\n\nOf course it is just another \"ugly\" patch, but it will get you going until you'll be able to run tests against all of the desired SDKs, or at least SDK 29 and all below. \n",
"So far Android doesn't support Java 9. As per documentation, Android supports all Java 7 features and a part of Java 8 features.\n\nWhen developing apps for Android, using Java 8 language features is\n optional. You can keep your project's source and target compatibility\n values set to Java 7, but you still need to compile using JDK 8.\n\n",
"You can't use Java 9, Android only supports till Java 8.\nYou should use the JDK version that comes with Android Studio, no need for side alone JDK. The current JDK version is based on OpenJDK 8.\n",
"I don't guarantee that it will work but you can set JDK to any version from the project Structure Option \nFile>Project Structure>SDK Location>'change JDK location here'\n\nsorry but it's not working either i have tried to select JDK9 but i got a prompt like this\n",
"In Android Studio, under \"Build, Execution, Deployment => Gradle => Gradle JDK\", you can choose the JDK version. In newer versions of Android Studio like Artic Fox, it comes with JDK11.\n\n"
] |
[
7,
5,
3,
2,
2,
0
] |
[] |
[] |
[
"android",
"android_studio",
"java",
"robolectric",
"robolectric_gradle_plugin"
] |
stackoverflow_0058516687_android_android_studio_java_robolectric_robolectric_gradle_plugin.txt
|
Q:
react-native require cycle how to fix it?
I have some modals and I get this error:
WARN Require cycle: src\components\Modal\index.ts -> src\components\Modal\ModalAddress\ModalAddress.tsx -> src\components\Modal\index.ts
Require cycles are allowed, but can result in uninitialized values. Consider refactoring to remove the need for a cycle.
WARN Require cycle: src\components\Modal\index.ts -> src\components\Modal\ModalShopInfo\ModalShopInfo.tsx -> src\components\ParentReviews\index.ts -> src\components\ParentReviews\ParentReviews.tsx -> src\components\Modal\index.ts
Modal folder is like this
-Modal
--index.ts
---/ModalAddress
---/ModalShopInfo
index.ts
export { default as ModalAddress } from './ModalAddress /ModalAddress';
export { default as ModalShopInfo } from './ModalShopInfo/ModalShopInfo';
export * from './ModalAddress/Model';
export * from './ModalShopInfo/Model';
...
What I am doing wrong ?
A:
Move the shared code or state from the ModalAddress and ModalShopInfo modules into a separate module, and then import that module into both ModalAddress and ModalShopInfo instead of importing each other. This should break the require cycle and allow your code to run without errors.
It's because a require cycle occurs when a module imports another module that imports the original module. This creates a circular dependency where each module is dependent on the other, which can result in uninitialized values and cause errors in your code. To solve that you can refactor your code to remove the circular dependency. Like; you can move the shared code or state into a separate module that both the original module and the imported module can import and use. This will break the circular dependency and allow your code to run properly.
|
react-native require cycle how to fix it?
|
I have some modals and I get this error:
WARN Require cycle: src\components\Modal\index.ts -> src\components\Modal\ModalAddress\ModalAddress.tsx -> src\components\Modal\index.ts
Require cycles are allowed, but can result in uninitialized values. Consider refactoring to remove the need for a cycle.
WARN Require cycle: src\components\Modal\index.ts -> src\components\Modal\ModalShopInfo\ModalShopInfo.tsx -> src\components\ParentReviews\index.ts -> src\components\ParentReviews\ParentReviews.tsx -> src\components\Modal\index.ts
Modal folder is like this
-Modal
--index.ts
---/ModalAddress
---/ModalShopInfo
index.ts
export { default as ModalAddress } from './ModalAddress /ModalAddress';
export { default as ModalShopInfo } from './ModalShopInfo/ModalShopInfo';
export * from './ModalAddress/Model';
export * from './ModalShopInfo/Model';
...
What I am doing wrong ?
|
[
"Move the shared code or state from the ModalAddress and ModalShopInfo modules into a separate module, and then import that module into both ModalAddress and ModalShopInfo instead of importing each other. This should break the require cycle and allow your code to run without errors.\nIt's because a require cycle occurs when a module imports another module that imports the original module. This creates a circular dependency where each module is dependent on the other, which can result in uninitialized values and cause errors in your code. To solve that you can refactor your code to remove the circular dependency. Like; you can move the shared code or state into a separate module that both the original module and the imported module can import and use. This will break the circular dependency and allow your code to run properly.\n"
] |
[
1
] |
[] |
[] |
[
"expo",
"react_native"
] |
stackoverflow_0074668550_expo_react_native.txt
|
Q:
macOS, call uninstall script when drag-and-drop app to trash icon
I'm working on some app that has LaunchDaemon running on the background, and thus it requires some operations to be removed, prior to deleting the data/exe files.
Is there an option to call an uninstall script upon drag-and-drop my app into the trash bin ?
my app uses pkg file format for deployment, but I couldn't find any uninstall callback within this format. is there a way to do so ?
Thanks
A:
This has been asked previously and in short, there hasn't been a good way of doing this up to and including macOS 12 'Monterey'.
However, there have been some changes in this area with macOS 13.0 Ventura; there's an introduction to the new mechanism in the WWDC22 session 'What’s new in privacy'. The new SMAppService APIs support automatic cleanup. Unfortunately you'll of course still have to find a workaround for any older macOS versions you support.
One way to ensure you don't consume unnecessary resources on a user's system, especially if uninstall isn't clean and the user isn't expecting your code to be lying around on their system anymore, is to avoid launching your daemon on every boot. Try to make it launch conditionally based on events, such as when your app first tries to connect via XPC/Mach, or using IOKit XPC events when the user first plugs in the device your daemon is driving.
|
macOS, call uninstall script when drag-and-drop app to trash icon
|
I'm working on some app that has LaunchDaemon running on the background, and thus it requires some operations to be removed, prior to deleting the data/exe files.
Is there an option to call an uninstall script upon drag-and-drop my app into the trash bin ?
my app uses pkg file format for deployment, but I couldn't find any uninstall callback within this format. is there a way to do so ?
Thanks
|
[
"This has been asked previously and in short, there hasn't been a good way of doing this up to and including macOS 12 'Monterey'.\nHowever, there have been some changes in this area with macOS 13.0 Ventura; there's an introduction to the new mechanism in the WWDC22 session 'What’s new in privacy'. The new SMAppService APIs support automatic cleanup. Unfortunately you'll of course still have to find a workaround for any older macOS versions you support.\nOne way to ensure you don't consume unnecessary resources on a user's system, especially if uninstall isn't clean and the user isn't expecting your code to be lying around on their system anymore, is to avoid launching your daemon on every boot. Try to make it launch conditionally based on events, such as when your app first tries to connect via XPC/Mach, or using IOKit XPC events when the user first plugs in the device your daemon is driving.\n"
] |
[
0
] |
[] |
[] |
[
"bash",
"launch_daemon",
"macos",
"pkg_file"
] |
stackoverflow_0074669813_bash_launch_daemon_macos_pkg_file.txt
|
Q:
How to interrupt other std::threads c++
I have a server which is built in a thread-per-client way. Lately, I bumped into a problem that I'm having a really hard time to come up with a solution to, so I thought to ask some help.
My server hosts a lobby, in the lobby there are many rooms (all of them owned by users), and in rooms there are players. Each room has an admin, when the admin chooses to leave - the room is closed, and all of the users are supposed to return to the lobby.
Now, I already have a working code - but there's the problem, I have no idea how should I have the other clients also exiting from the room. The code running in the thread is as following:
while(in_lobby)
{
//Receive a message
//Do stuff
//In certain cases change the Boolean to fit to the situation
//Send a comeback
}
while(in_room)
{
//Receive a message
//Do stuff
//In certain cases change the Boolean to fit to the situation
//Send a comeback
}
while(in_game)
{
//When a game started
//Not practical right now, though
}
There is no problem messing with the booleans from a thread of one client to another (because they are not exactly local variables, they are several conditions that I could change through the thread which is handling the administrator choosing to close the room).
The problem occurs when the condition DOES change, and the while loop is supposed to exit before the next iteration. Why does it occur? Because in the beginning of the iteration there's a recv() call, which awaits the client's messages.
Now, the condition is okay, everything is okay, but the loop won't continue (so it won't reach the next iteration - to see that the condition is false) until the server receives a certain message from the client (which it shouldn't, because closing the room doesn't depend on a regular user - the user only receives and alert, which is also sent through the admin's thread, about the room being closed).
My question therefore is:
How can I perform what I want? How can I make these users to break out of the loop, returning to the lobby (there is no problem with doing so with the admin, as his thread is the one that does everything and he returns to the lobby successfully) without changing the whole architecture from a thread-per-client way?
A:
"Because in the beginning of the iteration there's a recv() call, which awaits the client's messages."
Probably you don't want to have a blocking recv() call at this point in 1st place.
There's the select() function from the Windows Socket API, you can use to observe the state changes for a number of socket file descriptors.
Basically you will have a thread running a loop, and poll the return value of a select() call. Not to hog the CPU with a tight loop, a reasonable timeout value should be specified, but it's possible with a zero timeout, and just poll the available states as well.
If the return value signals that there's some action available for one of the observed sockets (select() > 0), you can inspect the observed socket file descriptors if they were triggered using the
FD_ISSET(s, *set)
macro.
A:
Because in the beginning of the iteration there's a recv() call, which awaits the client's messages.
I'm not familiar with the particulars if what you're using, but two tricks that can be used in similar circumstances are:
Have your server put bytes into the stream that recv() reads from.
Close the stream.
With the intent that either of these will force recv() to return.
If you can't do this with winsock, then another solution is to add another layer. You write a wrapper class that manages the complexities of how to read from a socket while still being able to receive notifications from other sources. Then your clients only use the wrapper class for receiving communications.
In the long term, this solution is probably better than using recv() directly anyways, since it separates concerns; client code is only worried about how to deal with the client and not the details of how to do robust communications, and the communications code only has to deal with how to receive and relay communications.
A:
Besides πάντα ῥεῖ's comment, you could try to implement a Provider-Consumer pattern.
Use a queue for store clients messages and read from it using that loop, if no messages to read just continue. This way the loop don't waits for the message arrives, that is the "Provider's" Job (the loop is the consumer since is consuming messages from the queue).
So, move the code calling recv out of the loop and use it for feed the queue.
Pseudocode:
Queue queue; // This has to be thread save.
class Provider: Thread
{
void run(queue)
{
while(1)
{
message = recv(); // This is where waiting occurs.
queue.push(message);
}
}
}
// This looks like it fits inside another thread. ;)
while (some_condition)
{
message = queue.pop(); // This returns immediately.
if (message)
{
//... so some things.
}
}
A:
Refactor your code so that there's one and only one place where you block on recv. Then you can move the client around all you want without having to disrupt the thread blocked in recv. You still want to receive a message if the client sends one, right?
So when a room is closed, the thread that closes the room can move clients out of it with no need to disturb the threads waiting for messages from those clients.
A:
The Stroika thread library - https://github.com/SophistSolutions/Stroika/blob/v2.1-Release/Library/Sources/Stroika/Foundation/Execution/Thread.h - supports interruption through cancelation points. This solves about 1/2 of the problem.
But what solves the rest - for networking applications - is that the networking library provide wrappers on networking objects like sockets (https://github.com/SophistSolutions/Stroika/blob/v2.1-Release/Library/Sources/Stroika/Foundation/IO/Network/Socket.h) - which automatically transform blocking operations into cancelation points. This allows you to write your networking applications simply, and just tell a thread to cancel/abort, and any ongoing networking calls are canceled automatically (by the library).
|
How to interrupt other std::threads c++
|
I have a server which is built in a thread-per-client way. Lately, I bumped into a problem that I'm having a really hard time to come up with a solution to, so I thought to ask some help.
My server hosts a lobby, in the lobby there are many rooms (all of them owned by users), and in rooms there are players. Each room has an admin, when the admin chooses to leave - the room is closed, and all of the users are supposed to return to the lobby.
Now, I already have a working code - but there's the problem, I have no idea how should I have the other clients also exiting from the room. The code running in the thread is as following:
while(in_lobby)
{
//Receive a message
//Do stuff
//In certain cases change the Boolean to fit to the situation
//Send a comeback
}
while(in_room)
{
//Receive a message
//Do stuff
//In certain cases change the Boolean to fit to the situation
//Send a comeback
}
while(in_game)
{
//When a game started
//Not practical right now, though
}
There is no problem messing with the booleans from a thread of one client to another (because they are not exactly local variables, they are several conditions that I could change through the thread which is handling the administrator choosing to close the room).
The problem occurs when the condition DOES change, and the while loop is supposed to exit before the next iteration. Why does it occur? Because in the beginning of the iteration there's a recv() call, which awaits the client's messages.
Now, the condition is okay, everything is okay, but the loop won't continue (so it won't reach the next iteration - to see that the condition is false) until the server receives a certain message from the client (which it shouldn't, because closing the room doesn't depend on a regular user - the user only receives and alert, which is also sent through the admin's thread, about the room being closed).
My question therefore is:
How can I perform what I want? How can I make these users to break out of the loop, returning to the lobby (there is no problem with doing so with the admin, as his thread is the one that does everything and he returns to the lobby successfully) without changing the whole architecture from a thread-per-client way?
|
[
"\n\"Because in the beginning of the iteration there's a recv() call, which awaits the client's messages.\"\n\nProbably you don't want to have a blocking recv() call at this point in 1st place.\nThere's the select() function from the Windows Socket API, you can use to observe the state changes for a number of socket file descriptors.\nBasically you will have a thread running a loop, and poll the return value of a select() call. Not to hog the CPU with a tight loop, a reasonable timeout value should be specified, but it's possible with a zero timeout, and just poll the available states as well.\nIf the return value signals that there's some action available for one of the observed sockets (select() > 0), you can inspect the observed socket file descriptors if they were triggered using the \nFD_ISSET(s, *set)\n\nmacro.\n",
"\nBecause in the beginning of the iteration there's a recv() call, which awaits the client's messages.\n\nI'm not familiar with the particulars if what you're using, but two tricks that can be used in similar circumstances are:\n\nHave your server put bytes into the stream that recv() reads from.\nClose the stream.\n\nWith the intent that either of these will force recv() to return.\nIf you can't do this with winsock, then another solution is to add another layer. You write a wrapper class that manages the complexities of how to read from a socket while still being able to receive notifications from other sources. Then your clients only use the wrapper class for receiving communications.\nIn the long term, this solution is probably better than using recv() directly anyways, since it separates concerns; client code is only worried about how to deal with the client and not the details of how to do robust communications, and the communications code only has to deal with how to receive and relay communications.\n",
"Besides πάντα ῥεῖ's comment, you could try to implement a Provider-Consumer pattern.\nUse a queue for store clients messages and read from it using that loop, if no messages to read just continue. This way the loop don't waits for the message arrives, that is the \"Provider's\" Job (the loop is the consumer since is consuming messages from the queue).\nSo, move the code calling recv out of the loop and use it for feed the queue.\nPseudocode:\nQueue queue; // This has to be thread save.\n\nclass Provider: Thread\n{\n void run(queue)\n {\n while(1)\n {\n message = recv(); // This is where waiting occurs.\n queue.push(message);\n }\n } \n}\n\n\n// This looks like it fits inside another thread. ;)\nwhile (some_condition)\n{\n message = queue.pop(); // This returns immediately.\n if (message)\n {\n //... so some things. \n }\n}\n\n",
"Refactor your code so that there's one and only one place where you block on recv. Then you can move the client around all you want without having to disrupt the thread blocked in recv. You still want to receive a message if the client sends one, right?\nSo when a room is closed, the thread that closes the room can move clients out of it with no need to disturb the threads waiting for messages from those clients.\n",
"The Stroika thread library - https://github.com/SophistSolutions/Stroika/blob/v2.1-Release/Library/Sources/Stroika/Foundation/Execution/Thread.h - supports interruption through cancelation points. This solves about 1/2 of the problem.\nBut what solves the rest - for networking applications - is that the networking library provide wrappers on networking objects like sockets (https://github.com/SophistSolutions/Stroika/blob/v2.1-Release/Library/Sources/Stroika/Foundation/IO/Network/Socket.h) - which automatically transform blocking operations into cancelation points. This allows you to write your networking applications simply, and just tell a thread to cancel/abort, and any ongoing networking calls are canceled automatically (by the library).\n"
] |
[
1,
1,
0,
0,
0
] |
[] |
[] |
[
"c++",
"multithreading",
"winsock2"
] |
stackoverflow_0030081889_c++_multithreading_winsock2.txt
|
Q:
Not showing the chart data developed with Plotly Library
Im developing an Heikin Ashi Chart using Bybit API. The code doesn't have errors but when I run it, Plotly Lib only open the chart and doesn't show my data.
import pandas as pd
import datetime as dt
import plotly.graph_objects as go
import calendar
import requests
symbol='BTCUSD' #symbol to be traded
tick_interval = '1' #candle in minutes
now = dt.datetime.utcnow()
unixtime = calendar.timegm(now.utctimetuple())
since = unixtime
start = str(since - 60 * 60 * int(tick_interval))
url = 'https://api.bybit.com/v2/public/kline/list?symbol='+symbol+'&interval='+tick_interval+'&from='+str(start)
data = requests.get(url).json()
D = pd.DataFrame(data['result'])
HAdf = pd.DataFrame()
HAdf = D[['open', 'close', 'high', 'low']]
HAdf['close'] = round(((D['open'].astype(float) + D['high'].astype(float) + D['low'].astype(float) + D['close'].astype(float))/4),2)
for i in range(len(D)):
if i == 0:
HAdf.iloc[0,0] = round(((D['open'].astype(float).iloc[0] + D['close'].astype(float).iloc[0])/2),2)
else:
HAdf.iat[i,0] = round(((HAdf.astype(float).iat[i-1,0] + HAdf.astype(float).iat[i-1,3])/2),2)
HAdf['high'] = HAdf.loc[:,['open', 'close']].join(D['high']).astype(float).max(axis=1)
HAdf['low'] = HAdf.loc[:,['open', 'close']].join(D['low']).astype(float).min(axis=1)
# Heikin Ashi bars chart
fig2 = go.Figure(data = [go.Candlestick(x = HAdf.index,
open = HAdf.open,
high = HAdf.high,
low = HAdf.low,
close = HAdf.close)])
fig2.update_layout(yaxis_range = [1500,2500],
title = 'Heikin Ashi Chart',
xaxis_title = 'Date',
yaxis_title = 'Price')
fig2.show()
I really appreciate if anyone can shortly explain how to fix it.
Python Version: 3.10.5
A:
Because you selected a very low y-axis range, if you remove it:
fig2.update_layout(
title = 'Heikin Ashi Chart',
xaxis_title = 'Date',
yaxis_title = 'Price')
Output:
|
Not showing the chart data developed with Plotly Library
|
Im developing an Heikin Ashi Chart using Bybit API. The code doesn't have errors but when I run it, Plotly Lib only open the chart and doesn't show my data.
import pandas as pd
import datetime as dt
import plotly.graph_objects as go
import calendar
import requests
symbol='BTCUSD' #symbol to be traded
tick_interval = '1' #candle in minutes
now = dt.datetime.utcnow()
unixtime = calendar.timegm(now.utctimetuple())
since = unixtime
start = str(since - 60 * 60 * int(tick_interval))
url = 'https://api.bybit.com/v2/public/kline/list?symbol='+symbol+'&interval='+tick_interval+'&from='+str(start)
data = requests.get(url).json()
D = pd.DataFrame(data['result'])
HAdf = pd.DataFrame()
HAdf = D[['open', 'close', 'high', 'low']]
HAdf['close'] = round(((D['open'].astype(float) + D['high'].astype(float) + D['low'].astype(float) + D['close'].astype(float))/4),2)
for i in range(len(D)):
if i == 0:
HAdf.iloc[0,0] = round(((D['open'].astype(float).iloc[0] + D['close'].astype(float).iloc[0])/2),2)
else:
HAdf.iat[i,0] = round(((HAdf.astype(float).iat[i-1,0] + HAdf.astype(float).iat[i-1,3])/2),2)
HAdf['high'] = HAdf.loc[:,['open', 'close']].join(D['high']).astype(float).max(axis=1)
HAdf['low'] = HAdf.loc[:,['open', 'close']].join(D['low']).astype(float).min(axis=1)
# Heikin Ashi bars chart
fig2 = go.Figure(data = [go.Candlestick(x = HAdf.index,
open = HAdf.open,
high = HAdf.high,
low = HAdf.low,
close = HAdf.close)])
fig2.update_layout(yaxis_range = [1500,2500],
title = 'Heikin Ashi Chart',
xaxis_title = 'Date',
yaxis_title = 'Price')
fig2.show()
I really appreciate if anyone can shortly explain how to fix it.
Python Version: 3.10.5
|
[
"Because you selected a very low y-axis range, if you remove it:\nfig2.update_layout(\n title = 'Heikin Ashi Chart', \n xaxis_title = 'Date', \n yaxis_title = 'Price')\n\nOutput:\n\n"
] |
[
1
] |
[] |
[] |
[
"bar_chart",
"plotly",
"plotly_python",
"python_3.10",
"trading"
] |
stackoverflow_0074668409_bar_chart_plotly_plotly_python_python_3.10_trading.txt
|
Q:
Why are my posts fetched with apollo cached (or so it seems) and how can I avoid this?
I'm learning React js and Graphql. My idea was to query my posts using @apollo/client in my getServerSideProps function, put them in a prop and pass them to the state.
When adding a mutation that deletes a post I made it so it will set the state again so the deleted post will disappear. However, what ends up happening is that the post will disappear, and will be deleted from the database. But when I refresh the page it is back again. Since it is deleted from the DB and getServerSideProps is supposed to run on every request I'm thinking maybe it has to do with caching but I have not been able to google a solution so far. Any help as to what's going on and how I could fix it would be appreciated.
export default function Posts({posts}) {
const [postList, setPostList] = useState(posts);
const postDeleted = ((deletedPostId)=> {
setPostList(postList.filter((post) => {
return post.id !== deletedPostId;
}))
})
return (
<div>
<h1 className={"text-4xl mb-5"}>Posts</h1>
<div className="flex flex-wrap">
{postList.map((post) => (
<div key={post.id} className={"md:w-1/3"}>
<PostPreview postDeleted={postDeleted} post={post}/>
</div>
))}
</div>
</div>
)
}
export async function getServerSideProps() {
const { data } = await client.query({
query: gql`
query Posts {
posts {
id
title
slug
}
}
`,
});
return {
props: {
posts: data.posts,
},
};
}
A:
It sounds like the issue you're experiencing is that your GraphQL query is being cached by Apollo Client, which is causing the deleted post to reappear on the page after refreshing. This is likely happening because you are using the getServerSideProps function in your Next.js app, which runs on the server and is intended to provide initial data to a page when it is loaded. Because the getServerSideProps function is only run on the server, the Apollo Client cache is not aware of any changes that are made to the data on the client-side, so it continues to return the cached version of the data when the page is refreshed.
To avoid this issue, you can either disable caching for the Apollo Client instance that you are using in your Next.js app, or you can refetch the data for your posts query after a post is deleted to ensure that the updated data is returned from the server.
To disable caching for your Apollo Client instance, you can set the defaultOptions property of the ApolloClient instance to disable the cache option. This will prevent the Apollo Client cache from being used for any queries that are run using this instance.
const client = new ApolloClient({
// Your existing Apollo Client configuration...
defaultOptions: {
watchQuery: {
fetchPolicy: 'no-cache'
}
}
});
|
Why are my posts fetched with apollo cached (or so it seems) and how can I avoid this?
|
I'm learning React js and Graphql. My idea was to query my posts using @apollo/client in my getServerSideProps function, put them in a prop and pass them to the state.
When adding a mutation that deletes a post I made it so it will set the state again so the deleted post will disappear. However, what ends up happening is that the post will disappear, and will be deleted from the database. But when I refresh the page it is back again. Since it is deleted from the DB and getServerSideProps is supposed to run on every request I'm thinking maybe it has to do with caching but I have not been able to google a solution so far. Any help as to what's going on and how I could fix it would be appreciated.
export default function Posts({posts}) {
const [postList, setPostList] = useState(posts);
const postDeleted = ((deletedPostId)=> {
setPostList(postList.filter((post) => {
return post.id !== deletedPostId;
}))
})
return (
<div>
<h1 className={"text-4xl mb-5"}>Posts</h1>
<div className="flex flex-wrap">
{postList.map((post) => (
<div key={post.id} className={"md:w-1/3"}>
<PostPreview postDeleted={postDeleted} post={post}/>
</div>
))}
</div>
</div>
)
}
export async function getServerSideProps() {
const { data } = await client.query({
query: gql`
query Posts {
posts {
id
title
slug
}
}
`,
});
return {
props: {
posts: data.posts,
},
};
}
|
[
"It sounds like the issue you're experiencing is that your GraphQL query is being cached by Apollo Client, which is causing the deleted post to reappear on the page after refreshing. This is likely happening because you are using the getServerSideProps function in your Next.js app, which runs on the server and is intended to provide initial data to a page when it is loaded. Because the getServerSideProps function is only run on the server, the Apollo Client cache is not aware of any changes that are made to the data on the client-side, so it continues to return the cached version of the data when the page is refreshed.\nTo avoid this issue, you can either disable caching for the Apollo Client instance that you are using in your Next.js app, or you can refetch the data for your posts query after a post is deleted to ensure that the updated data is returned from the server.\nTo disable caching for your Apollo Client instance, you can set the defaultOptions property of the ApolloClient instance to disable the cache option. This will prevent the Apollo Client cache from being used for any queries that are run using this instance.\nconst client = new ApolloClient({\n // Your existing Apollo Client configuration...\n defaultOptions: {\n watchQuery: {\n fetchPolicy: 'no-cache'\n }\n }\n});\n\n"
] |
[
1
] |
[] |
[] |
[
"apollo",
"graphql",
"javascript",
"next.js",
"reactjs"
] |
stackoverflow_0074669696_apollo_graphql_javascript_next.js_reactjs.txt
|
Q:
Encoding Problem in C# DOT.NET Core 6 taghelper
MVC pattern is used in the project.
Html statements in the cshtml view are as follows
<meta charset="utf-8">
<div>Yönetim</div>
If TagHelper is not used, the word Yönetim is written to the screen without any problem.
When I use TagHelper, the output.GetChildContentAsync() method returns the following result:
Yönetim
What is the cause of the problem, how do I solve it?
A:
The tag helper is encoding your text, so ö is being replaced with the HTML equivalent. You'd see the sme if you tried to display something like <strong>hello</strong> in there as well. It would show the < and > as < and '> respectively.
You don't say whether you are using MVC, Razor pages, Blazor, etc, so I can't give you an exact solution, but with the first three options you'd need something like @Raw("Yönetim"), and in Blazor you'd use @((MarkupString)"Yönetim")
|
Encoding Problem in C# DOT.NET Core 6 taghelper
|
MVC pattern is used in the project.
Html statements in the cshtml view are as follows
<meta charset="utf-8">
<div>Yönetim</div>
If TagHelper is not used, the word Yönetim is written to the screen without any problem.
When I use TagHelper, the output.GetChildContentAsync() method returns the following result:
Yönetim
What is the cause of the problem, how do I solve it?
|
[
"The tag helper is encoding your text, so ö is being replaced with the HTML equivalent. You'd see the sme if you tried to display something like <strong>hello</strong> in there as well. It would show the < and > as < and '> respectively.\nYou don't say whether you are using MVC, Razor pages, Blazor, etc, so I can't give you an exact solution, but with the first three options you'd need something like @Raw(\"Yönetim\"), and in Blazor you'd use @((MarkupString)\"Yönetim\")\n"
] |
[
0
] |
[] |
[] |
[
"asp.net_core_6.0",
"c#",
"character_encoding",
"tag_helpers"
] |
stackoverflow_0074670578_asp.net_core_6.0_c#_character_encoding_tag_helpers.txt
|
Q:
set df to value between tuple
i would like to set a df value between two values x_lim(0,2) to True.
I would like to get a df that looks like this:
x | y | z
0 | 7 | True
1 | 3 | True
2 | 4 | True
3 | 8 | False
i tried :
def set_label(df, x_lim, y_lim, variable):
for index, row in df.iterrows():
for i in range(x_lim[0],x_lim[1]):
df['Label'] = variable.get()
print(df)
could anyone help me to solve this problem ?
A:
Here is one way to do it:
import pandas as pd
# Create a dataframe with sample data
df = pd.DataFrame({'x': [0, 1, 2, 3], 'y': [7, 3, 4, 8]})
# Set the 'z' column to True if the value of 'x' is between 0 and 2 (inclusive)
df['z'] = df['x'].between(0, 2, inclusive=True)
# Print the resulting dataframe
print(df)
This will give you the following dataframe:
x y z
0 0 7 True
1 1 3 True
2 2 4 True
3 3 8 False
Hope this helps!
A:
Yes, you can use the loc method to create a new column in your DataFrame that has the values you want. Here's one way to do it:
def set_label(df, x_lim, y_lim, variable):
df['Label'] = False # create a new column with default value of False
df.loc[(df['x'] >= x_lim[0]) & (df['x'] <= x_lim[1]), 'Label'] = variable.get()
# set the values in the Label column to True where x is between x_lim[0] and x_lim[1]
return df
This function takes the DataFrame df, the tuple x_lim with the minimum and maximum values for the x column, and a variable that represents the value to set for the Label column. It creates a new column Label with default value of False, and then uses the loc method to set the values in the Label column to True where the x column is between x_lim[0] and x_lim[1]. Finally, it returns the modified DataFrame.
You can use this function like this:
# create a sample DataFrame
df = pd.DataFrame({'x': [0, 1, 2, 3], 'y': [7, 3, 4, 8]})
# set the label column to True where x is between 0 and 2
df = set_label(df, (0, 2), None, True)
print(df)
This will output the following DataFrame:
x y Label
0 0 7 True
1 1 3 True
2 2 4 True
3 3 8 False
I hope this helps! Let me know if you have any other questions.
|
set df to value between tuple
|
i would like to set a df value between two values x_lim(0,2) to True.
I would like to get a df that looks like this:
x | y | z
0 | 7 | True
1 | 3 | True
2 | 4 | True
3 | 8 | False
i tried :
def set_label(df, x_lim, y_lim, variable):
for index, row in df.iterrows():
for i in range(x_lim[0],x_lim[1]):
df['Label'] = variable.get()
print(df)
could anyone help me to solve this problem ?
|
[
"Here is one way to do it:\nimport pandas as pd\n\n# Create a dataframe with sample data\ndf = pd.DataFrame({'x': [0, 1, 2, 3], 'y': [7, 3, 4, 8]})\n\n# Set the 'z' column to True if the value of 'x' is between 0 and 2 (inclusive)\ndf['z'] = df['x'].between(0, 2, inclusive=True)\n\n# Print the resulting dataframe\nprint(df)\n\nThis will give you the following dataframe:\n x y z\n0 0 7 True\n1 1 3 True\n2 2 4 True\n3 3 8 False\n\nHope this helps!\n",
"Yes, you can use the loc method to create a new column in your DataFrame that has the values you want. Here's one way to do it:\ndef set_label(df, x_lim, y_lim, variable):\n df['Label'] = False # create a new column with default value of False\n df.loc[(df['x'] >= x_lim[0]) & (df['x'] <= x_lim[1]), 'Label'] = variable.get()\n # set the values in the Label column to True where x is between x_lim[0] and x_lim[1]\n return df\n\nThis function takes the DataFrame df, the tuple x_lim with the minimum and maximum values for the x column, and a variable that represents the value to set for the Label column. It creates a new column Label with default value of False, and then uses the loc method to set the values in the Label column to True where the x column is between x_lim[0] and x_lim[1]. Finally, it returns the modified DataFrame.\nYou can use this function like this:\n# create a sample DataFrame\ndf = pd.DataFrame({'x': [0, 1, 2, 3], 'y': [7, 3, 4, 8]})\n\n# set the label column to True where x is between 0 and 2\ndf = set_label(df, (0, 2), None, True)\n\nprint(df)\n\nThis will output the following DataFrame:\n x y Label\n0 0 7 True\n1 1 3 True\n2 2 4 True\n3 3 8 False\n\nI hope this helps! Let me know if you have any other questions.\n"
] |
[
2,
1
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074670641_pandas_python.txt
|
Q:
Bot is not waiting for the message
I'm trying to make the bot wait for a specific message(from a specific author and some specific things) But the bot is just waiting for any message and it makes the command.
Here's the function:
async def check(message):
if type == "netflix":
c.execute("SELECT price FROM netflix")
neprice = c.fetchall()
netprice= neprice[0][0]
netfprice = netprice*amount
nettax = await tax(args=netfprice)
try:
return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(nettax + netfprice) in message.content
except IndexError:
return False
Here's where I call the function:
await bot.wait_for('message', check=check, timeout=60)
Here's the full command:
@bot.slash_command()
@discord.ext.commands.cooldown(1,60, discord.ext.commands.BucketType.user)
async def buy(message, type: str, amount:Optional[int]):
if amount == None:
amount = 1
if amount < 0:
await message.respond("You cannot buy negative amount of accounts")
member = message.author
con = sqlite3.connect("db.sqlite")
c = con.cursor()
async def check(message):
if type == "netflix":
c.execute("SELECT price FROM netflix")
neprice = c.fetchall()
netprice= neprice[0][0]
netfprice = netprice*amount
nettax = await tax(args=netfprice)
try:
return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(nettax + netfprice) in message.content
except IndexError:
return False
elif type == "spotify" or "crunchyroll":
c.execute("SELECT price FROM spotify")
spotiprice = c.fetchall()
spotprice = spotiprice[0][0]
newspot = spotprice*amount
spotytax = await tax(args=newspot)
print(spotiprice[0][0])
try:
return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(newspot + spotytax) in message.content
except IndexError:
return False
if type == "netflix":
c.execute('SELECT *, COUNT(*) AS "count" FROM netflix GROUP BY price')
netamount= c.fetchall()
print(netamount[1])
if netamount[0][3] < amount:
await message.respond(f"We do not have this amount of accounts in the stock")
else:
c.execute("SELECT price FROM netflix ")
netfprice = c.fetchall()
netprice = netfprice[0][0]
newnet = netprice*amount
withtax = await tax(args=newnet)
embed = discord.Embed(title="transfer",description=f"Please transfer :{newnet + withtax}")
embed.add_field(name=f"c <@994347081294684240> {newnet + withtax}",value="**Copy paste the message for no error**")
embed.set_footer(text=f"Sidtho Host. | Requested by - {message.author}")
print("Sent embed, Waiting for receiving the credits")
await message.respond(embed=embed)
await bot.wait_for('message', check=check, timeout=60)
c.execute("SELECT email, password FROM netflix")
netres = c.fetchmany(size=amount)
# print(netres)
embed = discord.Embed(title=f"حساب {type}", description="")
embed.add_field(name="Sidtho Host.",value=" ",inline=False)
for thisamount in netres:
try:
email = thisamount[0]
password= thisamount[1]
embed.add_field(name=f"Email: {email}", value=f"Password: {password}", inline=False)
# print(f"The email is {email} \n The password is {password}
except TypeError as err:
print(f"Gave A TypeError. Where {err} ")
await member.send(embed=embed)
c.execute("DELETE FROM netflix WHERE email=? AND password=?",(email, password))
There is no traceback So no error.
Please note that the check function is a Function, not a command.
and the await bot.wait_for is on a command.
Please note too that type is a value that the user will give to the bot, and its not the python built.
A:
In your code, you wrote await message.respond(...).
There isn't a respond() function in both discord.py and pycord, as far as I know. Try changing it to reply(...) and see if it works.
A:
async def buy(message, type: str, amount:Optional[int]):
#type here the stuff that u want make before the check
def check(m):
return m.mentions[0].id == 994347081294684240 and m.author.id == 282859044593598464 and int(nettax + netfprice) in m.content
try:
response = await client.wait_for('message', check=check, timeout=30.0)
except:
#here u can send a message when the time is done
message.send("timeout")
return
so yeah it should look like this u take the response and run any checks on or save to db.
|
Bot is not waiting for the message
|
I'm trying to make the bot wait for a specific message(from a specific author and some specific things) But the bot is just waiting for any message and it makes the command.
Here's the function:
async def check(message):
if type == "netflix":
c.execute("SELECT price FROM netflix")
neprice = c.fetchall()
netprice= neprice[0][0]
netfprice = netprice*amount
nettax = await tax(args=netfprice)
try:
return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(nettax + netfprice) in message.content
except IndexError:
return False
Here's where I call the function:
await bot.wait_for('message', check=check, timeout=60)
Here's the full command:
@bot.slash_command()
@discord.ext.commands.cooldown(1,60, discord.ext.commands.BucketType.user)
async def buy(message, type: str, amount:Optional[int]):
if amount == None:
amount = 1
if amount < 0:
await message.respond("You cannot buy negative amount of accounts")
member = message.author
con = sqlite3.connect("db.sqlite")
c = con.cursor()
async def check(message):
if type == "netflix":
c.execute("SELECT price FROM netflix")
neprice = c.fetchall()
netprice= neprice[0][0]
netfprice = netprice*amount
nettax = await tax(args=netfprice)
try:
return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(nettax + netfprice) in message.content
except IndexError:
return False
elif type == "spotify" or "crunchyroll":
c.execute("SELECT price FROM spotify")
spotiprice = c.fetchall()
spotprice = spotiprice[0][0]
newspot = spotprice*amount
spotytax = await tax(args=newspot)
print(spotiprice[0][0])
try:
return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(newspot + spotytax) in message.content
except IndexError:
return False
if type == "netflix":
c.execute('SELECT *, COUNT(*) AS "count" FROM netflix GROUP BY price')
netamount= c.fetchall()
print(netamount[1])
if netamount[0][3] < amount:
await message.respond(f"We do not have this amount of accounts in the stock")
else:
c.execute("SELECT price FROM netflix ")
netfprice = c.fetchall()
netprice = netfprice[0][0]
newnet = netprice*amount
withtax = await tax(args=newnet)
embed = discord.Embed(title="transfer",description=f"Please transfer :{newnet + withtax}")
embed.add_field(name=f"c <@994347081294684240> {newnet + withtax}",value="**Copy paste the message for no error**")
embed.set_footer(text=f"Sidtho Host. | Requested by - {message.author}")
print("Sent embed, Waiting for receiving the credits")
await message.respond(embed=embed)
await bot.wait_for('message', check=check, timeout=60)
c.execute("SELECT email, password FROM netflix")
netres = c.fetchmany(size=amount)
# print(netres)
embed = discord.Embed(title=f"حساب {type}", description="")
embed.add_field(name="Sidtho Host.",value=" ",inline=False)
for thisamount in netres:
try:
email = thisamount[0]
password= thisamount[1]
embed.add_field(name=f"Email: {email}", value=f"Password: {password}", inline=False)
# print(f"The email is {email} \n The password is {password}
except TypeError as err:
print(f"Gave A TypeError. Where {err} ")
await member.send(embed=embed)
c.execute("DELETE FROM netflix WHERE email=? AND password=?",(email, password))
There is no traceback So no error.
Please note that the check function is a Function, not a command.
and the await bot.wait_for is on a command.
Please note too that type is a value that the user will give to the bot, and its not the python built.
|
[
"In your code, you wrote await message.respond(...).\nThere isn't a respond() function in both discord.py and pycord, as far as I know. Try changing it to reply(...) and see if it works.\n",
"async def buy(message, type: str, amount:Optional[int]):\n #type here the stuff that u want make before the check\n def check(m):\n return m.mentions[0].id == 994347081294684240 and m.author.id == 282859044593598464 and int(nettax + netfprice) in m.content \n try:\n response = await client.wait_for('message', check=check, timeout=30.0)\n except:\n #here u can send a message when the time is done\n message.send(\"timeout\")\n return\n \n\n\nso yeah it should look like this u take the response and run any checks on or save to db.\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"discord.py",
"pycord",
"python"
] |
stackoverflow_0074659035_discord.py_pycord_python.txt
|
Q:
Expo EAS build crash and disappear after successful install Android React Native
My expo application works normally on Expo go, even using the command bellow it still works.
npx expo start --no-dev --minify
But when building with different methods it don't work at all, with different crashes.
eas build -p android --profile preview
It generates the APK, when i drag to the emulator (android 11) it gets the "successful install", so I open and the splash screen shows, after that it crashes and the app disappear from the device. Looks like it was automatically uninstalled, because I can't find it anywhere in the files.
expo build:android -t apk
With the deprecated method above i still get a "successful install", but it never gets to the splash screen, just get a white screen and it never crashes or disappear from device.
I tried on multiple devices and android versions and i have the same problem with each build in all of them. So i guess the problem is the build. I couldn't find anyone else with the solution or a hint for it.
I tried uninstalling multiple npm packages to see if was the problem with no successes.
Its my first time working with React Native and Expo, so I can be missing something.
//app.json
{
"expo": {
"name": "tv_box",
"slug": "tv_box",
"version": "1.0.0",
"orientation": "landscape",
"icon": "./assets/icon.png",
"userInterfaceStyle": "light",
"splash": {
"image": "./assets/splash.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
"updates": {
"fallbackToCacheTimeout": 0
},
"assetBundlePatterns": [
"**/*"
],
"ios": {
"supportsTablet": true
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#FFFFFF"
},
"package": "com.test.tv_box"
},
"web": {
"favicon": "./assets/favicon.png"
},
"extra": {
"eas": {
"projectId": "4b9e5710-cdd0-4e3a-846d-3faed6c56510"
}
}
}
}
//eas.json
{
"cli": {
"version": ">= 2.8.0"
},
"build": {
"development": {
"developmentClient": true,
"distribution": "internal"
},
"preview": {
"distribution": "internal"
},
"production": {}
},
"submit": {
"production": {}
}
}
//package.json
{
"name": "tv_box",
"version": "1.0.0",
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web"
},
"dependencies": {
"@react-native-async-storage/async-storage": "^1.17.10",
"@react-navigation/stack": "^6.3.2",
"expo": "~46.0.7",
"expo-status-bar": "~1.4.0",
"expo-system-ui": "~1.3.0",
"expo-updates": "~0.14.7",
"pocketbase": "^0.7.4",
"react": "18.0.0",
"react-native": "0.69.6",
"react-native-gesture-handler": "~2.5.0",
"react-native-restart": "^0.0.24",
"react-native-vector-icons": "^9.2.0",
"expo-av": "~12.0.4"
},
"devDependencies": {
"@babel/core": "^7.12.9"
},
"private": true
}
A:
It's disappears in most of cases due to release build. In debug build you had to get normal error screen ( red ), add
"developmentClient": true
in your eas.json -> development block and try again.
A:
Solved with
npm i react-native-screens
And make sure you have everything updated in the latest version to build with EAS including the Expo SDK, React Native, expo and eas CLI.
|
Expo EAS build crash and disappear after successful install Android React Native
|
My expo application works normally on Expo go, even using the command bellow it still works.
npx expo start --no-dev --minify
But when building with different methods it don't work at all, with different crashes.
eas build -p android --profile preview
It generates the APK, when i drag to the emulator (android 11) it gets the "successful install", so I open and the splash screen shows, after that it crashes and the app disappear from the device. Looks like it was automatically uninstalled, because I can't find it anywhere in the files.
expo build:android -t apk
With the deprecated method above i still get a "successful install", but it never gets to the splash screen, just get a white screen and it never crashes or disappear from device.
I tried on multiple devices and android versions and i have the same problem with each build in all of them. So i guess the problem is the build. I couldn't find anyone else with the solution or a hint for it.
I tried uninstalling multiple npm packages to see if was the problem with no successes.
Its my first time working with React Native and Expo, so I can be missing something.
//app.json
{
"expo": {
"name": "tv_box",
"slug": "tv_box",
"version": "1.0.0",
"orientation": "landscape",
"icon": "./assets/icon.png",
"userInterfaceStyle": "light",
"splash": {
"image": "./assets/splash.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
"updates": {
"fallbackToCacheTimeout": 0
},
"assetBundlePatterns": [
"**/*"
],
"ios": {
"supportsTablet": true
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#FFFFFF"
},
"package": "com.test.tv_box"
},
"web": {
"favicon": "./assets/favicon.png"
},
"extra": {
"eas": {
"projectId": "4b9e5710-cdd0-4e3a-846d-3faed6c56510"
}
}
}
}
//eas.json
{
"cli": {
"version": ">= 2.8.0"
},
"build": {
"development": {
"developmentClient": true,
"distribution": "internal"
},
"preview": {
"distribution": "internal"
},
"production": {}
},
"submit": {
"production": {}
}
}
//package.json
{
"name": "tv_box",
"version": "1.0.0",
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web"
},
"dependencies": {
"@react-native-async-storage/async-storage": "^1.17.10",
"@react-navigation/stack": "^6.3.2",
"expo": "~46.0.7",
"expo-status-bar": "~1.4.0",
"expo-system-ui": "~1.3.0",
"expo-updates": "~0.14.7",
"pocketbase": "^0.7.4",
"react": "18.0.0",
"react-native": "0.69.6",
"react-native-gesture-handler": "~2.5.0",
"react-native-restart": "^0.0.24",
"react-native-vector-icons": "^9.2.0",
"expo-av": "~12.0.4"
},
"devDependencies": {
"@babel/core": "^7.12.9"
},
"private": true
}
|
[
"It's disappears in most of cases due to release build. In debug build you had to get normal error screen ( red ), add\n\"developmentClient\": true\n\nin your eas.json -> development block and try again.\n",
"Solved with\n\nnpm i react-native-screens\n\nAnd make sure you have everything updated in the latest version to build with EAS including the Expo SDK, React Native, expo and eas CLI.\n"
] |
[
1,
0
] |
[] |
[] |
[
"android",
"build",
"eas",
"expo",
"react_native"
] |
stackoverflow_0074667397_android_build_eas_expo_react_native.txt
|
Q:
Multiple touchable options component in scrollview react native is re-rendering to the top when there is change in component
This is my react-native app where i'm rendering multiple touchable components in a long scrollView, everything is working as expected but the scroll view component is rendering to the top of the scrollView when I make changes in the component (select/di-select), but I think the expected behavior is to remain to the portion where I've made the selection, instead every time I select an option from the bottom of the component the scroll view goes to the top.
These are the image for the end result of the code
This is my code for the rendering the scrollView
const creativityOptions = [
{
id: 1,
name: 'art',
},
{id: 2, name: 'design'},
{id: 3, name: 'making-videos'},
{id: 4, name: 'make-up'},
{id: 5, name: 'photography'},
{id: 6, name: 'writing'},
{id: 7, name: 'singing'},
{id: 8, name: 'dancing'},
{id: 9, name: 'crafts'},
];
const [fieldValue, setFiledValue] = React.useState({
name: '',
email: '',
dob: new Date(),
interests: {
creativity: [],
sports: [],
stayingIn: [],
tvFilm: [],
reading: [],
music: [],
foodsDrink: [],
travelling: [],
pets: [],
},
});
const setInterestValue = (item, option) => {
if (fieldValue.interests[item].some(item => item.id == option.id)) {
var filtered = fieldValue.interests[item].filter(
val => val.id !== option.id,
);
setFiledValue({
...fieldValue,
interests: {...fieldValue.interests, [item]: filtered},
});
} else {
if (lengthOfInterest <= 7) {
setFiledValue({
...fieldValue,
interests: {
...fieldValue.interests,
[item]: [...fieldValue.interests[item], option],
},
});
}
}
};
const RenderInterest = () => {
return (
<View>
<ScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={{paddingHorizontal: 10, paddingBottom: 80}}>
<Text
F24
M
style={{
color: Colors.black,
marginTop: 50,
marginHorizontal: 20,
}}>
Your Interest
</Text>
<DynamicTouchableComponent
title="Creativity"
options={creativityOptions}
selectedOptions={fieldValue.interests.creativity}
selectedOptionsCallback={options =>
setInterestValue('creativity', options)
}
/>
<DynamicTouchableComponent
title="Sports"
options={sportsOption}
selectedOptions={fieldValue.interests.sports}
selectedOptionsCallback={options =>
setInterestValue('sports', options)
}
/>
<DynamicTouchableComponent
title="Staying In"
options={stayingInOptions}
selectedOptions={fieldValue.interests.stayingIn}
selectedOptionsCallback={options =>
setInterestValue('stayingIn', options)
}
/>
<DynamicTouchableComponent
title="Film & TV"
options={filmTVOptions}
selectedOptions={fieldValue.interests.tvFilm}
selectedOptionsCallback={options =>
setInterestValue('tvFilm', options)
}
/>
<DynamicTouchableComponent
title="Reading"
options={readingOptions}
selectedOptions={fieldValue.interests.reading}
selectedOptionsCallback={options =>
setInterestValue('reading', options)
}
/>
<DynamicTouchableComponent
title="Music"
options={musicOptions}
selectedOptions={fieldValue.interests.music}
selectedOptionsCallback={options =>
setInterestValue('music', options)
}
/>
<DynamicTouchableComponent
title="Food & Drink"
options={foodDrinkOptions}
selectedOptions={fieldValue.interests.foodsDrink}
selectedOptionsCallback={options =>
setInterestValue('foodsDrink', options)
}
/>
<DynamicTouchableComponent
title="Travelling"
options={travelOptions}
selectedOptions={fieldValue.interests.travelling}
selectedOptionsCallback={options =>
setInterestValue('travelling', options)
}
/>
<DynamicTouchableComponent
title="Pets"
options={petsOptions}
selectedOptions={fieldValue.interests.pets}
selectedOptionsCallback={options =>
setInterestValue('pets', options)
}
/>
</ScrollView>
<View
style={{
position: 'absolute',
bottom: 0,
height: 70,
width: '100%',
backgroundColor: Colors.white,
justifyContent: 'center',
}}>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
}}>
<TouchableOpacity
activeOpacity={0.4}
disabled={lengthOfInterest >= 1}
style={{
paddingLeft: 20,
}}
onPress={() => {}}>
<Text
F18
R
style={{
color: lengthOfInterest >= 1 ? Colors.grayDark : Colors.black,
}}>
Skip
</Text>
</TouchableOpacity>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
marginRight: 30,
}}>
<Text
F16
R
style={{
color: Colors.black,
marginRight: 15,
}}>
{`${lengthOfInterest}/8`}
</Text>
<NextButton
style={{
backgroundColor:
lengthOfInterest >= 1 ? Colors.primaryDark : Colors.border,
}}
disabled={lengthOfInterest < 1}
iconStyle={
lengthOfInterest >= 1 ? Colors.black : Colors.grayDark
}
onPress={() => {
// setShowInterest(false);
// setPageIndex(pageIndex + 1);
handleSignup();
}}
/>
</View>
</View>
</View>
</View>
);
};
This is for the Dynamic component where the options are rendered
export const DynamicTouchableComponent = ({
title,
options,
style,
selectedOptionsCallback,
selectedOptions,
}) => {
const setInterest = index => {
const selectedvalue = options[index];
selectedOptionsCallback(selectedvalue);
};
return (
<View
style={{
flex: 1,
}}>
<Text
F22
M
style={{
color: Colors.black,
marginTop: 30,
marginLeft: 10,
}}>
{title}
</Text>
<View
style={[
{
flexDirection: 'row',
flexWrap: 'wrap',
flexGrow: 1,
},
style,
]}>
{options.map((option, index) => {
return (
<TouchableOpacity
key={index}
style={[
styles.option2,
{
alignItems: 'center',
backgroundColor: selectedOptions.some(
item => item.id == option.id,
)
? Colors.primary
: Colors.white,
paddingVertical: 6,
paddingHorizontal: 10,
borderColor: Colors.primary,
marginHorizontal: 10,
},
]}
onPress={() => {
setInterest(index);
}}>
<Text
F14
R
style={{
color: selectedOptions.some(item => item.id == option.id)
? Colors.white
: Colors.headingGray,
textTransform: 'capitalize',
}}>
{option.name}
</Text>
</TouchableOpacity>
);
})}
</View>
</View>
);
};
A:
Use the scrollTo method from the ScrollView component to prevent the scrollview from re-rendering to the top of the scrollview when making changes to a component.
you can add a ref to your ScrollView component:
const scroollRef = React.useRef();
...
<ScrollView
ref={scroollRef}
showsVerticalScrollIndicator={false}
contentContainerStyle={{paddingHorizontal: 10, paddingBottom: 80}}>
Then, when you want to prevent the ScrollView from re-rendering to the top, you can call the scrollTo method in the setInterestValue method like this:
const setInterestValue = (item, option) => {
if (fieldValue.interests[item].some(item => item.id == option.id)) {
var filtered = fieldValue.interests[item].filter(
val => val.id !== option.id,
);
scroollRef.current.scrollTo({x: 0, y: 0, animated: true});
setFiledValue({
...fieldValue,
interests: {...fieldValue.interests, [item]: filtered},
});
} else {
if (lengthOfInterest <= 7) {
setFiledValue({
...fieldValue,
interests: {
...fieldValue.interests,
[item]: [...fieldValue.interests[item], option],
},
|
Multiple touchable options component in scrollview react native is re-rendering to the top when there is change in component
|
This is my react-native app where i'm rendering multiple touchable components in a long scrollView, everything is working as expected but the scroll view component is rendering to the top of the scrollView when I make changes in the component (select/di-select), but I think the expected behavior is to remain to the portion where I've made the selection, instead every time I select an option from the bottom of the component the scroll view goes to the top.
These are the image for the end result of the code
This is my code for the rendering the scrollView
const creativityOptions = [
{
id: 1,
name: 'art',
},
{id: 2, name: 'design'},
{id: 3, name: 'making-videos'},
{id: 4, name: 'make-up'},
{id: 5, name: 'photography'},
{id: 6, name: 'writing'},
{id: 7, name: 'singing'},
{id: 8, name: 'dancing'},
{id: 9, name: 'crafts'},
];
const [fieldValue, setFiledValue] = React.useState({
name: '',
email: '',
dob: new Date(),
interests: {
creativity: [],
sports: [],
stayingIn: [],
tvFilm: [],
reading: [],
music: [],
foodsDrink: [],
travelling: [],
pets: [],
},
});
const setInterestValue = (item, option) => {
if (fieldValue.interests[item].some(item => item.id == option.id)) {
var filtered = fieldValue.interests[item].filter(
val => val.id !== option.id,
);
setFiledValue({
...fieldValue,
interests: {...fieldValue.interests, [item]: filtered},
});
} else {
if (lengthOfInterest <= 7) {
setFiledValue({
...fieldValue,
interests: {
...fieldValue.interests,
[item]: [...fieldValue.interests[item], option],
},
});
}
}
};
const RenderInterest = () => {
return (
<View>
<ScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={{paddingHorizontal: 10, paddingBottom: 80}}>
<Text
F24
M
style={{
color: Colors.black,
marginTop: 50,
marginHorizontal: 20,
}}>
Your Interest
</Text>
<DynamicTouchableComponent
title="Creativity"
options={creativityOptions}
selectedOptions={fieldValue.interests.creativity}
selectedOptionsCallback={options =>
setInterestValue('creativity', options)
}
/>
<DynamicTouchableComponent
title="Sports"
options={sportsOption}
selectedOptions={fieldValue.interests.sports}
selectedOptionsCallback={options =>
setInterestValue('sports', options)
}
/>
<DynamicTouchableComponent
title="Staying In"
options={stayingInOptions}
selectedOptions={fieldValue.interests.stayingIn}
selectedOptionsCallback={options =>
setInterestValue('stayingIn', options)
}
/>
<DynamicTouchableComponent
title="Film & TV"
options={filmTVOptions}
selectedOptions={fieldValue.interests.tvFilm}
selectedOptionsCallback={options =>
setInterestValue('tvFilm', options)
}
/>
<DynamicTouchableComponent
title="Reading"
options={readingOptions}
selectedOptions={fieldValue.interests.reading}
selectedOptionsCallback={options =>
setInterestValue('reading', options)
}
/>
<DynamicTouchableComponent
title="Music"
options={musicOptions}
selectedOptions={fieldValue.interests.music}
selectedOptionsCallback={options =>
setInterestValue('music', options)
}
/>
<DynamicTouchableComponent
title="Food & Drink"
options={foodDrinkOptions}
selectedOptions={fieldValue.interests.foodsDrink}
selectedOptionsCallback={options =>
setInterestValue('foodsDrink', options)
}
/>
<DynamicTouchableComponent
title="Travelling"
options={travelOptions}
selectedOptions={fieldValue.interests.travelling}
selectedOptionsCallback={options =>
setInterestValue('travelling', options)
}
/>
<DynamicTouchableComponent
title="Pets"
options={petsOptions}
selectedOptions={fieldValue.interests.pets}
selectedOptionsCallback={options =>
setInterestValue('pets', options)
}
/>
</ScrollView>
<View
style={{
position: 'absolute',
bottom: 0,
height: 70,
width: '100%',
backgroundColor: Colors.white,
justifyContent: 'center',
}}>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
}}>
<TouchableOpacity
activeOpacity={0.4}
disabled={lengthOfInterest >= 1}
style={{
paddingLeft: 20,
}}
onPress={() => {}}>
<Text
F18
R
style={{
color: lengthOfInterest >= 1 ? Colors.grayDark : Colors.black,
}}>
Skip
</Text>
</TouchableOpacity>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
marginRight: 30,
}}>
<Text
F16
R
style={{
color: Colors.black,
marginRight: 15,
}}>
{`${lengthOfInterest}/8`}
</Text>
<NextButton
style={{
backgroundColor:
lengthOfInterest >= 1 ? Colors.primaryDark : Colors.border,
}}
disabled={lengthOfInterest < 1}
iconStyle={
lengthOfInterest >= 1 ? Colors.black : Colors.grayDark
}
onPress={() => {
// setShowInterest(false);
// setPageIndex(pageIndex + 1);
handleSignup();
}}
/>
</View>
</View>
</View>
</View>
);
};
This is for the Dynamic component where the options are rendered
export const DynamicTouchableComponent = ({
title,
options,
style,
selectedOptionsCallback,
selectedOptions,
}) => {
const setInterest = index => {
const selectedvalue = options[index];
selectedOptionsCallback(selectedvalue);
};
return (
<View
style={{
flex: 1,
}}>
<Text
F22
M
style={{
color: Colors.black,
marginTop: 30,
marginLeft: 10,
}}>
{title}
</Text>
<View
style={[
{
flexDirection: 'row',
flexWrap: 'wrap',
flexGrow: 1,
},
style,
]}>
{options.map((option, index) => {
return (
<TouchableOpacity
key={index}
style={[
styles.option2,
{
alignItems: 'center',
backgroundColor: selectedOptions.some(
item => item.id == option.id,
)
? Colors.primary
: Colors.white,
paddingVertical: 6,
paddingHorizontal: 10,
borderColor: Colors.primary,
marginHorizontal: 10,
},
]}
onPress={() => {
setInterest(index);
}}>
<Text
F14
R
style={{
color: selectedOptions.some(item => item.id == option.id)
? Colors.white
: Colors.headingGray,
textTransform: 'capitalize',
}}>
{option.name}
</Text>
</TouchableOpacity>
);
})}
</View>
</View>
);
};
|
[
"Use the scrollTo method from the ScrollView component to prevent the scrollview from re-rendering to the top of the scrollview when making changes to a component.\nyou can add a ref to your ScrollView component:\nconst scroollRef = React.useRef();\n\n...\n\n<ScrollView\n ref={scroollRef}\n showsVerticalScrollIndicator={false}\n contentContainerStyle={{paddingHorizontal: 10, paddingBottom: 80}}>\n\nThen, when you want to prevent the ScrollView from re-rendering to the top, you can call the scrollTo method in the setInterestValue method like this:\nconst setInterestValue = (item, option) => {\n if (fieldValue.interests[item].some(item => item.id == option.id)) {\n var filtered = fieldValue.interests[item].filter(\n val => val.id !== option.id,\n );\n scroollRef.current.scrollTo({x: 0, y: 0, animated: true});\n\n setFiledValue({\n ...fieldValue,\n interests: {...fieldValue.interests, [item]: filtered},\n });\n } else {\n if (lengthOfInterest <= 7) {\n setFiledValue({\n ...fieldValue,\n interests: {\n ...fieldValue.interests,\n [item]: [...fieldValue.interests[item], option],\n },\n\n"
] |
[
0
] |
[] |
[] |
[
"javascript",
"jsx",
"react_hooks",
"react_native",
"reactjs"
] |
stackoverflow_0074668124_javascript_jsx_react_hooks_react_native_reactjs.txt
|
Q:
Fill opacity don't work with calculate value Recharts
For each Stacked Bar element, I calculate its percentage
const valuePercent = attribute => ({payload}) => {
const keys = getKeys(chartData);
const total = keys.reduce((acc, curr) => {
return acc + payload[curr].count;
}, 0);
const ratio = total > 0 ? payload[attribute].count / total : 0;
return `${(ratio * 100).toFixed(0)}%`;
};
But when I substitute this value in the style, it doesn't work. What could be the problem?
return keys.map((item, index) => ( <
Bar key = {
index
}
dataKey = {
`${item}.count`
}
stackId = 'a'
style = {
{
fill: '#0452D7',
fillOpacity: valuePercent(item),
}
}
/>
));
if you just put some value in fill opacity, everything is fine. At the same time, I see in the console that the function is triggered, and the percentages are calculated
A:
The problem with the code is that the fillOpacity property expects a numeric value, but the valuePercent function is returning a string that contains the percentage value. This causes an error when the style is applied to the Bar element, as the string value is not a valid numeric value for the fillOpacity property.
To fix this, you can modify the valuePercent function to return a numeric value instead of a string. You can do this by parsing the percentage value from the string and converting it to a number, like this:
const valuePercent = attribute => ({ payload }) => {
const keys = getKeys(chartData);
const total = keys.reduce((acc, curr) => {
return acc + payload[curr].count;
}, 0);
const ratio = total > 0 ? payload[attribute].count / total : 0;
return parseInt(`${(ratio * 100).toFixed(0)}%`, 10) / 100;
};
In this updated version of the valuePercent function, the percentage value is parsed from the string and divided by 100, which converts it to a decimal value between 0 and 1. This decimal value can then be used as the fillOpacity property value, which should fix the issue with the style.
You can then use the valuePercent function in the style property like this:
return keys.map((item, index) => (
<Bar
key={index}
dataKey={`${item}.count`}
stackId="a"
style={{
fill: '#0452D7',
fillOpacity: valuePercent(item),
}}
/>
));
I hope this helps! Let me know if you have any other questions.
|
Fill opacity don't work with calculate value Recharts
|
For each Stacked Bar element, I calculate its percentage
const valuePercent = attribute => ({payload}) => {
const keys = getKeys(chartData);
const total = keys.reduce((acc, curr) => {
return acc + payload[curr].count;
}, 0);
const ratio = total > 0 ? payload[attribute].count / total : 0;
return `${(ratio * 100).toFixed(0)}%`;
};
But when I substitute this value in the style, it doesn't work. What could be the problem?
return keys.map((item, index) => ( <
Bar key = {
index
}
dataKey = {
`${item}.count`
}
stackId = 'a'
style = {
{
fill: '#0452D7',
fillOpacity: valuePercent(item),
}
}
/>
));
if you just put some value in fill opacity, everything is fine. At the same time, I see in the console that the function is triggered, and the percentages are calculated
|
[
"The problem with the code is that the fillOpacity property expects a numeric value, but the valuePercent function is returning a string that contains the percentage value. This causes an error when the style is applied to the Bar element, as the string value is not a valid numeric value for the fillOpacity property.\nTo fix this, you can modify the valuePercent function to return a numeric value instead of a string. You can do this by parsing the percentage value from the string and converting it to a number, like this:\nconst valuePercent = attribute => ({ payload }) => {\n const keys = getKeys(chartData);\n const total = keys.reduce((acc, curr) => {\n return acc + payload[curr].count;\n }, 0);\n const ratio = total > 0 ? payload[attribute].count / total : 0;\n return parseInt(`${(ratio * 100).toFixed(0)}%`, 10) / 100;\n};\n\nIn this updated version of the valuePercent function, the percentage value is parsed from the string and divided by 100, which converts it to a decimal value between 0 and 1. This decimal value can then be used as the fillOpacity property value, which should fix the issue with the style.\nYou can then use the valuePercent function in the style property like this:\nreturn keys.map((item, index) => (\n <Bar\n key={index}\n dataKey={`${item}.count`}\n stackId=\"a\"\n style={{\n fill: '#0452D7',\n fillOpacity: valuePercent(item),\n }}\n />\n));\n\nI hope this helps! Let me know if you have any other questions.\n"
] |
[
0
] |
[] |
[] |
[
"javascript",
"reactjs",
"recharts"
] |
stackoverflow_0074638254_javascript_reactjs_recharts.txt
|
Q:
React - what is the proper way to do global state?
I have here an app, and I want the App component to hold the current logged in user. I have the following routes and components.
Basically, every component in my app will make use of the user object. Sure I can pass the user as props to each and every component, but that is not elegant. What is the proper React way of sharing the user prop globally?
const App = () => {
const [user, setUser] = useState(null);
return (
<Router>
<div className="app">
<Topbar />
<Switch>
<Route path="/login" exact component={Login} />
<Route path="/home" exact component={Home} />
<Route path="/" exact component={ShopMenu} />
<Route path="/orders">
<Orders />
</Route>
<Route path="/wishlist" exact component={Wishlist} />
<Route path="/wallet" exact component={Wallet} />
<Route path="/cart" exact component={Cart} />
</Switch>
<BottomBar />
</div>
</Router>
);
};
A:
Take a look at React Context and more specifically useContext as you're using hooks.
The idea of context is exactly that - for you to be able to share updateable state to the descendants without having to pass it from component to component (the so called "prop-drilling").
const UserContext = React.createContext(null);
const App = () => {
const [user, setUser] = useState(null);
return (
<Router>
<div className="app">
<UserContext.Provider value={user}>
<Topbar />
<Switch>
<Route path="/login" exact component={Login} />
<Route path="/home" exact component={Home} />
<Route path="/" exact component={ShopMenu} />
<Route path="/orders">
<Orders />
</Route>
<Route path="/wishlist" exact component={Wishlist} />
<Route path="/wallet" exact component={Wallet} />
<Route path="/cart" exact component={Cart} />
</Switch>
<BottomBar />
</UserContext.Provider>
</div>
</Router>
);
};
Then, in your component:
const Topbar = () => {
const user = useContext(UserContext);
// use `user` here
};
If you want to have access to the setter (setUser) you can pass it through the context as well.
A:
Simple React Global State with Hooks (Observer Design Pattern)
However "React way" was asked for, it might be helpful for all of you who seek for a simple and robust alternative.
codesandbox example
The concept is based on Yezy Ilomo's article. It just has been put into a working condition and been renamed the variables & functions to be more self-explaining.
I use it in production, in multiple projects, with this particular implementation directly (not Yezy's npm package) and it works like a charm.
|
React - what is the proper way to do global state?
|
I have here an app, and I want the App component to hold the current logged in user. I have the following routes and components.
Basically, every component in my app will make use of the user object. Sure I can pass the user as props to each and every component, but that is not elegant. What is the proper React way of sharing the user prop globally?
const App = () => {
const [user, setUser] = useState(null);
return (
<Router>
<div className="app">
<Topbar />
<Switch>
<Route path="/login" exact component={Login} />
<Route path="/home" exact component={Home} />
<Route path="/" exact component={ShopMenu} />
<Route path="/orders">
<Orders />
</Route>
<Route path="/wishlist" exact component={Wishlist} />
<Route path="/wallet" exact component={Wallet} />
<Route path="/cart" exact component={Cart} />
</Switch>
<BottomBar />
</div>
</Router>
);
};
|
[
"Take a look at React Context and more specifically useContext as you're using hooks.\nThe idea of context is exactly that - for you to be able to share updateable state to the descendants without having to pass it from component to component (the so called \"prop-drilling\").\nconst UserContext = React.createContext(null);\n\nconst App = () => {\n const [user, setUser] = useState(null);\n\n return (\n <Router>\n <div className=\"app\">\n <UserContext.Provider value={user}>\n <Topbar />\n <Switch>\n <Route path=\"/login\" exact component={Login} />\n <Route path=\"/home\" exact component={Home} />\n <Route path=\"/\" exact component={ShopMenu} />\n <Route path=\"/orders\">\n <Orders />\n </Route>\n <Route path=\"/wishlist\" exact component={Wishlist} />\n <Route path=\"/wallet\" exact component={Wallet} />\n <Route path=\"/cart\" exact component={Cart} />\n </Switch>\n <BottomBar />\n </UserContext.Provider>\n </div>\n </Router>\n );\n};\n\nThen, in your component:\nconst Topbar = () => {\n const user = useContext(UserContext);\n\n // use `user` here\n};\n\nIf you want to have access to the setter (setUser) you can pass it through the context as well.\n",
"Simple React Global State with Hooks (Observer Design Pattern)\nHowever \"React way\" was asked for, it might be helpful for all of you who seek for a simple and robust alternative.\ncodesandbox example\nThe concept is based on Yezy Ilomo's article. It just has been put into a working condition and been renamed the variables & functions to be more self-explaining.\nI use it in production, in multiple projects, with this particular implementation directly (not Yezy's npm package) and it works like a charm.\n"
] |
[
24,
0
] |
[
"Welcome to stack overflow;\nYes you can save your state globally for which react-redux library react offers in which you need to store your state globally and you can access state in any component from redux\nhere is the complete guide\nYou can also check\ncomplete guide here of how to use redux with react\nAlso you can use context api\ncheck here for context api\n"
] |
[
-6
] |
[
"react_router",
"reactjs"
] |
stackoverflow_0069675357_react_router_reactjs.txt
|
Q:
How windows handle the clipboard interface with Xming?
My question comes from a problem:
I Use Xming on Windows 7 to connect to a Linux host (through PuTTY) in order to start and display a gnome-terminal.
I have some troubles using the Windows clipboard:
Copy from Windows to Xming works well. (Ctrl-C then middle-click on
Xming)
Copy from Xming to another Xming cession works with delay. (Selection
on Xming then middle-click on the other Xming)
Copy from Xming to Windows works most of the time with delay. (Selection
on Xming then Ctrl-V on Windows)
On Windows: I have to repeat the Ctrl+V many times before it passed my text. (<10 kBytes)
Note that firsts failing attempts don't past the previous clipboard content.
Note 2:
If I use a VB script to paste the clipboard content I have no delay.
Set objHTML = CreateObject("htmlfile")
ClipboardText = objHTML.ParentWindow.ClipboardData.GetData("text")
path = "D:\Users\blanchj1\AppData\Local\Temp\clipboard"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(path, 2, true)
objFile.WriteLine ClipboardText
objFile.Close
Note 3:
If I paste through an application menu ex notepad++ -> edit -> paste, I still have this delay.
Note 4:
If I paste the content with Ctrl+V a second time, I still have this delay.
Note 5:
The delay seems proportional to the number of charters to paste.
So I suppose this delay comes from a windows issue.
Is that a problem of characters-encoding conversion?
Who can explain to me how it works?
A:
Your observation that the delay is proportional to the number of characters pasted should be expected, since each of those characters must be fed through the SSH terminal, a serial pipeline. Additionally, rendering those characters on your end takes some effort from Windows. I suspect that the reason that you see less delay with your VBScript paste operation is that the VBScript paste operation largely eliminates the user interface from the process, since the clipboard can deal with the characters, without having to figure out how to draw them.
A:
When you use Xming to connect to a Linux host and run a graphical application, Xming acts as a client for the X Window System, which is the standard graphical windowing system for Linux. Xming receives the graphical output from the Linux host and displays it on your Windows machine.
The clipboard is a feature that allows you to transfer text or other data between different applications. In the X Window System, there is a standard clipboard called the "selection" that works similarly to the clipboard in Windows. When you copy text in an X Window application, it is automatically copied to the selection. Then, when you paste text in another X Window application, it automatically retrieves the text from the selection.
When you use Xming to run a Linux graphical application on your Windows machine, the application's use of the selection is automatically translated to the Windows clipboard. This allows you to use the Windows clipboard to transfer text between the Linux application and other Windows applications.
It is likely that the delay you are experiencing when copying from Xming to Windows is due to the process of translating the selection to the Windows clipboard. This translation may take some time, especially if the text being copied is large. The fact that the delay seems proportional to the number of characters suggests that this is the case.
Another possible cause of the delay could be the way that Windows handles the clipboard interface with Xming. Xming may be using a different clipboard format than the one that Windows expects, which could cause Windows to have to do additional processing to handle the clipboard data. This is just a guess, however, and more information would be needed to confirm this.
|
How windows handle the clipboard interface with Xming?
|
My question comes from a problem:
I Use Xming on Windows 7 to connect to a Linux host (through PuTTY) in order to start and display a gnome-terminal.
I have some troubles using the Windows clipboard:
Copy from Windows to Xming works well. (Ctrl-C then middle-click on
Xming)
Copy from Xming to another Xming cession works with delay. (Selection
on Xming then middle-click on the other Xming)
Copy from Xming to Windows works most of the time with delay. (Selection
on Xming then Ctrl-V on Windows)
On Windows: I have to repeat the Ctrl+V many times before it passed my text. (<10 kBytes)
Note that firsts failing attempts don't past the previous clipboard content.
Note 2:
If I use a VB script to paste the clipboard content I have no delay.
Set objHTML = CreateObject("htmlfile")
ClipboardText = objHTML.ParentWindow.ClipboardData.GetData("text")
path = "D:\Users\blanchj1\AppData\Local\Temp\clipboard"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(path, 2, true)
objFile.WriteLine ClipboardText
objFile.Close
Note 3:
If I paste through an application menu ex notepad++ -> edit -> paste, I still have this delay.
Note 4:
If I paste the content with Ctrl+V a second time, I still have this delay.
Note 5:
The delay seems proportional to the number of charters to paste.
So I suppose this delay comes from a windows issue.
Is that a problem of characters-encoding conversion?
Who can explain to me how it works?
|
[
"Your observation that the delay is proportional to the number of characters pasted should be expected, since each of those characters must be fed through the SSH terminal, a serial pipeline. Additionally, rendering those characters on your end takes some effort from Windows. I suspect that the reason that you see less delay with your VBScript paste operation is that the VBScript paste operation largely eliminates the user interface from the process, since the clipboard can deal with the characters, without having to figure out how to draw them.\n",
"When you use Xming to connect to a Linux host and run a graphical application, Xming acts as a client for the X Window System, which is the standard graphical windowing system for Linux. Xming receives the graphical output from the Linux host and displays it on your Windows machine.\nThe clipboard is a feature that allows you to transfer text or other data between different applications. In the X Window System, there is a standard clipboard called the \"selection\" that works similarly to the clipboard in Windows. When you copy text in an X Window application, it is automatically copied to the selection. Then, when you paste text in another X Window application, it automatically retrieves the text from the selection.\nWhen you use Xming to run a Linux graphical application on your Windows machine, the application's use of the selection is automatically translated to the Windows clipboard. This allows you to use the Windows clipboard to transfer text between the Linux application and other Windows applications.\nIt is likely that the delay you are experiencing when copying from Xming to Windows is due to the process of translating the selection to the Windows clipboard. This translation may take some time, especially if the text being copied is large. The fact that the delay seems proportional to the number of characters suggests that this is the case.\nAnother possible cause of the delay could be the way that Windows handles the clipboard interface with Xming. Xming may be using a different clipboard format than the one that Windows expects, which could cause Windows to have to do additional processing to handle the clipboard data. This is just a guess, however, and more information would be needed to confirm this.\n"
] |
[
0,
0
] |
[] |
[] |
[
"clipboard",
"delay",
"paste",
"windows",
"xming"
] |
stackoverflow_0027377465_clipboard_delay_paste_windows_xming.txt
|
Q:
How does indexing work on mongodb serverless?
When running a dedicated instance of mongod, indexing large collections can result in blocked writes / increased response times, thus we usually do rolling indexes on secondary instances first and promote them to primary once done.
I'm unable to find any documentation on this for mongodb serverles. How does it handle these long running jobs and what are the costs?
Is this assumption correct?
Mongodb serverless performs indexing in the background and spins up new instances once indexing is down, while taking old ones offline?
Each index is charged as a write?
A:
Rolling indexing is intended
For workloads which cannot tolerate performance decrease due to index builds
I don't believe serverless Atlas aims this particular audience. Instead it's focuses on easy-to-start and no-long-term-commitments selling points, i.e. for infrequent/random usage pattern which can be more cost -efficient comparing to standard cluster offering.
From the long list of limitations, it explicitly says:
Build Index with Rolling Build
| Serverless instances don't support building indexes with a rolling build.
So no, it's unlikely the assumption is correct. I believe they use standard routine introduced in v4.2 when they ditched foreground indexes: https://www.mongodb.com/docs/v4.2/core/index-creation/#index-operations
Disclaimer:
The question is about implementation details of a proprietary service. I do not work in MongoDB Inc, nor don't have access to internal architecture documentation. The answer is based on publicly available resources and common sense.
|
How does indexing work on mongodb serverless?
|
When running a dedicated instance of mongod, indexing large collections can result in blocked writes / increased response times, thus we usually do rolling indexes on secondary instances first and promote them to primary once done.
I'm unable to find any documentation on this for mongodb serverles. How does it handle these long running jobs and what are the costs?
Is this assumption correct?
Mongodb serverless performs indexing in the background and spins up new instances once indexing is down, while taking old ones offline?
Each index is charged as a write?
|
[
"Rolling indexing is intended\n\nFor workloads which cannot tolerate performance decrease due to index builds\n\nI don't believe serverless Atlas aims this particular audience. Instead it's focuses on easy-to-start and no-long-term-commitments selling points, i.e. for infrequent/random usage pattern which can be more cost -efficient comparing to standard cluster offering.\nFrom the long list of limitations, it explicitly says:\n\nBuild Index with Rolling Build\n| Serverless instances don't support building indexes with a rolling build.\n\nSo no, it's unlikely the assumption is correct. I believe they use standard routine introduced in v4.2 when they ditched foreground indexes: https://www.mongodb.com/docs/v4.2/core/index-creation/#index-operations\n\nDisclaimer:\nThe question is about implementation details of a proprietary service. I do not work in MongoDB Inc, nor don't have access to internal architecture documentation. The answer is based on publicly available resources and common sense.\n"
] |
[
0
] |
[] |
[] |
[
"mongodb"
] |
stackoverflow_0074506850_mongodb.txt
|
Q:
Pimcore: How to check if in editmode/admin area (in php)?
Have googled this but cannot seem to find it... I have a (php) Listener class in which I need to know if i'm currently in admin edit page for a data object (similar to 'editmode' var in twig)... how to do this check in php?
Inside a Controller the editmode is available:
$this->editmode
but how to get this in a class that's not a controller (ie a listener class / any other class)?
A:
Have you tried to do same as the Controller (eg. FrontentController) does ?
https://github.com/pimcore/pimcore/blob/11.x/lib/Controller/FrontendController.php#L62
Thats the magic behind $this->iseditmode
|
Pimcore: How to check if in editmode/admin area (in php)?
|
Have googled this but cannot seem to find it... I have a (php) Listener class in which I need to know if i'm currently in admin edit page for a data object (similar to 'editmode' var in twig)... how to do this check in php?
Inside a Controller the editmode is available:
$this->editmode
but how to get this in a class that's not a controller (ie a listener class / any other class)?
|
[
"Have you tried to do same as the Controller (eg. FrontentController) does ?\nhttps://github.com/pimcore/pimcore/blob/11.x/lib/Controller/FrontendController.php#L62\nThats the magic behind $this->iseditmode\n"
] |
[
0
] |
[] |
[] |
[
"pimcore",
"pimcore_v5"
] |
stackoverflow_0074473733_pimcore_pimcore_v5.txt
|
Q:
preg_replace, where is the mistake?
I want to replace, in a dictionary, the letters that start with a vowel with an acute accent, by the letter a, but when I put 'á' it doesn't read it to me and therefore it doesn't replace it. How can I make the function read it to me that special character?
$letter_in_progress = 'área';
$pattern = '/á/i';
echo preg_replace($pattern, 'a', $letter_in_progress);
A:
If you want to remove any accents, you can transliterate them to ASCII.
$letter_in_progress = 'área';
echo iconv('UTF-8', 'ASCII//TRANSLIT', $letter_in_progress);
area
|
preg_replace, where is the mistake?
|
I want to replace, in a dictionary, the letters that start with a vowel with an acute accent, by the letter a, but when I put 'á' it doesn't read it to me and therefore it doesn't replace it. How can I make the function read it to me that special character?
$letter_in_progress = 'área';
$pattern = '/á/i';
echo preg_replace($pattern, 'a', $letter_in_progress);
|
[
"If you want to remove any accents, you can transliterate them to ASCII.\n$letter_in_progress = 'área';\necho iconv('UTF-8', 'ASCII//TRANSLIT', $letter_in_progress);\n\n\narea\n\n"
] |
[
2
] |
[] |
[] |
[
"php"
] |
stackoverflow_0074670535_php.txt
|
Q:
How do I make it stop storing everything in the first element of the list?
I am trying to have each line be stored in a different element of the list. The text file is as follows...
244
Large Cake Pan
7
19.99
576
Assorted Sprinkles
3
12.89
212
Deluxe Icing Set
6
37.97
827
Yellow Cake Mix
3
1.99
194
Cupcake Display Board
2
27.99
285
Bakery Boxes
7
8.59
736
Mixer
5
136.94
I am trying to have 244, 576, etc. be in ID. And "Large Cake Pan","Assorted Sprinkles", etc. in Name. You get the idea, but it's storing everything in ID, and I don't know how to make it store the information in its corresponding element.
Here is my code so far:
import Inventory
def process_inventory(filename, inventory_dict):
inventory_dict = {}
inventory_file = open(filename, "r")
for line in inventory_file:
line = line.split('\n')
ID = line[0]
Name = line[1]
Quantity = line[2]
Price = line[3]
my_inventory = Inventory.Inventory(ID, Name, Quantity, Price)
inventory_dict[ID] = my_inventory
inventory_file.close()
return inventory_dict
def main():
inventory1={}
process_inventory("Inventory.txt", inventory1)
A:
In the code you've provided, you're overwriting the inventory_dict parameter with an empty dictionary on the second line of the process_inventory function. This means that the dictionary that you pass to the function as an argument won't be used or updated in the function.
To fix this, you should remove the line inventory_dict = {}, and instead use the inventory_dict parameter directly. This will ensure that the function updates the dictionary that is passed to it as an argument.
Additionally, you're splitting the line on the '\n' character, which is not present in the data. Instead, you should split the line on the space character, ' ', so that you can separate the ID, name, quantity, and price values.
Here's how you can modify the process_inventory function to fix these issues:
def process_inventory(filename, inventory_dict):
inventory_file = open(filename, "r")
for line in inventory_file:
# Split the line on spaces to get the ID, name, quantity, and price values
values = line.split(' ')
ID = values[0]
Name = values[1]
Quantity = values[2]
Price = values[3]
my_inventory = Inventory.Inventory(ID, Name, Quantity, Price)
inventory_dict[ID] = my_inventory
inventory_file.close()
return inventory_dict
With these changes, each line will be processed and added to the inventory_dict dictionary with the ID as the key and the Inventory object as the value.
Note: There is no Inventory class defined in the code you've provided, so it's not clear how the Inventory objects are supposed to be created. You may need to adjust this part of the code depending on how the Inventory class is defined.
|
How do I make it stop storing everything in the first element of the list?
|
I am trying to have each line be stored in a different element of the list. The text file is as follows...
244
Large Cake Pan
7
19.99
576
Assorted Sprinkles
3
12.89
212
Deluxe Icing Set
6
37.97
827
Yellow Cake Mix
3
1.99
194
Cupcake Display Board
2
27.99
285
Bakery Boxes
7
8.59
736
Mixer
5
136.94
I am trying to have 244, 576, etc. be in ID. And "Large Cake Pan","Assorted Sprinkles", etc. in Name. You get the idea, but it's storing everything in ID, and I don't know how to make it store the information in its corresponding element.
Here is my code so far:
import Inventory
def process_inventory(filename, inventory_dict):
inventory_dict = {}
inventory_file = open(filename, "r")
for line in inventory_file:
line = line.split('\n')
ID = line[0]
Name = line[1]
Quantity = line[2]
Price = line[3]
my_inventory = Inventory.Inventory(ID, Name, Quantity, Price)
inventory_dict[ID] = my_inventory
inventory_file.close()
return inventory_dict
def main():
inventory1={}
process_inventory("Inventory.txt", inventory1)
|
[
"In the code you've provided, you're overwriting the inventory_dict parameter with an empty dictionary on the second line of the process_inventory function. This means that the dictionary that you pass to the function as an argument won't be used or updated in the function.\nTo fix this, you should remove the line inventory_dict = {}, and instead use the inventory_dict parameter directly. This will ensure that the function updates the dictionary that is passed to it as an argument.\nAdditionally, you're splitting the line on the '\\n' character, which is not present in the data. Instead, you should split the line on the space character, ' ', so that you can separate the ID, name, quantity, and price values.\nHere's how you can modify the process_inventory function to fix these issues:\ndef process_inventory(filename, inventory_dict):\n inventory_file = open(filename, \"r\")\n for line in inventory_file:\n # Split the line on spaces to get the ID, name, quantity, and price values\n values = line.split(' ')\n ID = values[0]\n Name = values[1]\n Quantity = values[2]\n Price = values[3]\n my_inventory = Inventory.Inventory(ID, Name, Quantity, Price)\n inventory_dict[ID] = my_inventory\n inventory_file.close()\n return inventory_dict\n\nWith these changes, each line will be processed and added to the inventory_dict dictionary with the ID as the key and the Inventory object as the value.\nNote: There is no Inventory class defined in the code you've provided, so it's not clear how the Inventory objects are supposed to be created. You may need to adjust this part of the code depending on how the Inventory class is defined.\n"
] |
[
0
] |
[] |
[] |
[
"dictionary",
"file",
"list",
"python"
] |
stackoverflow_0074670666_dictionary_file_list_python.txt
|
Q:
"Error: ENOENT: no such file or directory", when using React Native with Hermes
Whenever there is an error in my code while running expo with Hermes locally, I get this error message as well:
Error: ENOENT: no such file or directory, open 'C:\Users\kudo\01_Work\Repos\expo\expo\android\versioned-react-native\ReactAndroid\hermes-engine\.cxx\MinSizeRel\6d3b5k69\x86\lib\InternalBytecode\InternalBytecode.js'
Now if I fix the code error, for instance a missing bracket, the aforementioned error also disappears and everything works. However, this error appears no matter what error is in my code, and it's quite lengthy and is preventing me from debugging. If I remove Hermes, the error also disappears, but I would like to use Hermes.
Here is my env info:
expo-env-info 1.0.5 environment info:
System:
OS: Windows 10 10.0.19044
Binaries:
Node: 16.16.0 - C:\Program Files\nodejs\node.EXE
Yarn: 1.22.19 - ~\AppData\Roaming\npm\yarn.CMD
npm: 9.1.1 - C:\Program Files\nodejs\npm.CMD
IDEs:
Android Studio: AI-212.5712.43.2112.8609683
npmPackages:
expo: ^46.0.0 => 46.0.15
react: 18.0.0 => 18.0.0
react-dom: 18.0.0 => 18.0.0
react-native: 0.69.6 => 0.69.6
react-native-web: ~0.18.7 => 0.18.9
Expo Workflow: managed
Things I've tried:
rm -rf node_modules
npm cache clean --force
Deleting the metro_cache folder in appdata
npx expo start --clear
I expected the error to no longer appear, however the aforementioned steps did nothing at all.
A:
Probably a problem with the Hermes engine. It appears that the engine is trying to open a file that does not exist on your system. You can try reinstalling Hermes to see if that fixes the problem.
If that doesn't work, you can try disabling Hermes by adding the following line to your app.json file:
"hermes": false
This will prevent the Hermes engine from being used, and should prevent the error from occurring. However, disabling Hermes may also cause performance issues in your app, so only do this as a last resort.
|
"Error: ENOENT: no such file or directory", when using React Native with Hermes
|
Whenever there is an error in my code while running expo with Hermes locally, I get this error message as well:
Error: ENOENT: no such file or directory, open 'C:\Users\kudo\01_Work\Repos\expo\expo\android\versioned-react-native\ReactAndroid\hermes-engine\.cxx\MinSizeRel\6d3b5k69\x86\lib\InternalBytecode\InternalBytecode.js'
Now if I fix the code error, for instance a missing bracket, the aforementioned error also disappears and everything works. However, this error appears no matter what error is in my code, and it's quite lengthy and is preventing me from debugging. If I remove Hermes, the error also disappears, but I would like to use Hermes.
Here is my env info:
expo-env-info 1.0.5 environment info:
System:
OS: Windows 10 10.0.19044
Binaries:
Node: 16.16.0 - C:\Program Files\nodejs\node.EXE
Yarn: 1.22.19 - ~\AppData\Roaming\npm\yarn.CMD
npm: 9.1.1 - C:\Program Files\nodejs\npm.CMD
IDEs:
Android Studio: AI-212.5712.43.2112.8609683
npmPackages:
expo: ^46.0.0 => 46.0.15
react: 18.0.0 => 18.0.0
react-dom: 18.0.0 => 18.0.0
react-native: 0.69.6 => 0.69.6
react-native-web: ~0.18.7 => 0.18.9
Expo Workflow: managed
Things I've tried:
rm -rf node_modules
npm cache clean --force
Deleting the metro_cache folder in appdata
npx expo start --clear
I expected the error to no longer appear, however the aforementioned steps did nothing at all.
|
[
"Probably a problem with the Hermes engine. It appears that the engine is trying to open a file that does not exist on your system. You can try reinstalling Hermes to see if that fixes the problem.\nIf that doesn't work, you can try disabling Hermes by adding the following line to your app.json file:\n\n\"hermes\": false\n\nThis will prevent the Hermes engine from being used, and should prevent the error from occurring. However, disabling Hermes may also cause performance issues in your app, so only do this as a last resort.\n"
] |
[
0
] |
[] |
[] |
[
"expo",
"react_native",
"react_native_hermes"
] |
stackoverflow_0074667131_expo_react_native_react_native_hermes.txt
|
Q:
Why useLocalStorage does not work with Next.js?
This will raise an Error: Hydration failed because the initial UI does not match what was rendered on the server. error:
const [selectedOrganizationShortId, setSelectedOrganizationShortId] =
useLocalStorage<string>('teamId', undefined)
This will not:
const [selectedOrganizationShortId, setSelectedOrganizationShortId] =
useState<string>(undefined)
const [selectedProgramId, saveSelectedProgramId] = useState<
string | undefined
>(undefined)
though both does the same. I would use useLocalStorage as it is handy convenience solution, but seems it is not compatible with Next.js.
useLocalStorage is used from here: https://usehooks-ts.com/react-hook/use-local-storage
A:
My answer is a suggestion for your need.
You could write a custom hook for your purpose so no need to any external libraries:
import { useEffect, useState, Dispatch, SetStateAction } from 'react'
type SetValue<T> = Dispatch<SetStateAction<T>>
export default function useLocalStorage<T>(key: string, fallbackValue: T): [T | undefined, SetValue<T | undefined>] {
const [value, setValue] = useState<T | undefined>();
useEffect(() => {
const stored = localStorage.getItem(key);
setValue(stored ? JSON.parse(stored) : fallbackValue);
}, [fallbackValue, key]);
useEffect(() => {
if (value) {
localStorage.setItem(key, JSON.stringify(value))
}
}, [key, value]);
return [value, setValue];
}
And then use it like this:
const [value, setValue] = useLocalStorage<string>('key', 'value');
A:
This works for me:
import { useEffect, useState, Dispatch, SetStateAction } from 'react'
type SetValue<T> = Dispatch<SetStateAction<T>>
export default function useLocalStorage<T>(
key: string,
fallbackValue: T
): [T, SetValue<T>] {
const [value, setValue] = useState()
useEffect(() => {
const stored = localStorage.getItem(key)
if (!stored) {
return
}
setValue(stored ? JSON.parse(stored) : fallbackValue)
}, [fallbackValue, key])
useEffect(() => {
if (!value) {
return
}
localStorage.setItem(key, JSON.stringify(value))
}, [key, value])
return [value, setValue]
}
And calling like this:
const [selectedOrganizationShortId, setSelectedOrganizationShortId] =
useLocalStorage<string>(
'teamId',
auth.userDTO?.organizations
? Object.keys(auth.userDTO?.organizations)[0]
: ''
|
Why useLocalStorage does not work with Next.js?
|
This will raise an Error: Hydration failed because the initial UI does not match what was rendered on the server. error:
const [selectedOrganizationShortId, setSelectedOrganizationShortId] =
useLocalStorage<string>('teamId', undefined)
This will not:
const [selectedOrganizationShortId, setSelectedOrganizationShortId] =
useState<string>(undefined)
const [selectedProgramId, saveSelectedProgramId] = useState<
string | undefined
>(undefined)
though both does the same. I would use useLocalStorage as it is handy convenience solution, but seems it is not compatible with Next.js.
useLocalStorage is used from here: https://usehooks-ts.com/react-hook/use-local-storage
|
[
"My answer is a suggestion for your need.\nYou could write a custom hook for your purpose so no need to any external libraries:\nimport { useEffect, useState, Dispatch, SetStateAction } from 'react'\n\ntype SetValue<T> = Dispatch<SetStateAction<T>>\n\nexport default function useLocalStorage<T>(key: string, fallbackValue: T): [T | undefined, SetValue<T | undefined>] {\n const [value, setValue] = useState<T | undefined>();\n\n useEffect(() => {\n const stored = localStorage.getItem(key);\n setValue(stored ? JSON.parse(stored) : fallbackValue);\n }, [fallbackValue, key]);\n\n useEffect(() => {\n if (value) {\n localStorage.setItem(key, JSON.stringify(value))\n }\n }, [key, value]);\n\n return [value, setValue];\n}\n\nAnd then use it like this:\nconst [value, setValue] = useLocalStorage<string>('key', 'value');\n\n",
"This works for me:\nimport { useEffect, useState, Dispatch, SetStateAction } from 'react'\n\ntype SetValue<T> = Dispatch<SetStateAction<T>>\n\nexport default function useLocalStorage<T>(\n key: string,\n fallbackValue: T\n): [T, SetValue<T>] {\n const [value, setValue] = useState()\n useEffect(() => {\n const stored = localStorage.getItem(key)\n if (!stored) {\n return\n }\n setValue(stored ? JSON.parse(stored) : fallbackValue)\n }, [fallbackValue, key])\n\n useEffect(() => {\n if (!value) {\n return\n }\n localStorage.setItem(key, JSON.stringify(value))\n }, [key, value])\n\n return [value, setValue]\n}\n\nAnd calling like this:\nconst [selectedOrganizationShortId, setSelectedOrganizationShortId] =\n useLocalStorage<string>(\n 'teamId',\n auth.userDTO?.organizations\n ? Object.keys(auth.userDTO?.organizations)[0]\n : ''\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"next.js",
"react_hooks",
"reactjs",
"static_site_generation"
] |
stackoverflow_0074667758_next.js_react_hooks_reactjs_static_site_generation.txt
|
Q:
Run MathJax at specific point or re-run it somewhere in code
Let me simplify the script:
Gets input from user
Calculates stuff
Adds calculated stuff to HTML with MathJax
The problem is, that MathJax runs at the beginning, when the stuff is not calculated yet. It shows 'undefined' in equations. Later, when it's calculated, the equations looks something like this $ l_D = 3m $
Is there any way to run MathJax at specific point? Or to re-run it after that stuff is calculated?
Edit: Someone suggested MathJax.typeset(), but I got an error: Uncaught TypeError: MathJax.typeset is not a function
Link to file in repo, I just need to re-run MathJax at the end of poVypocte function, nearly at the end
EditEdit: SOLVED
I don't know, if it's 'legal', but I made the JavaScript to add MathJax to <head>, like this:
add = document.createElement("script");
add.setAttribute("type", "text/javascript");
add.setAttribute("id", "MathJax-script");
add.setAttribute("defer", true);
add.setAttribute("src","https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js");
document.getElementsByTagName("head")[0].appendChild(add);
+ some more stuff
Thanks for help anyways :)
A:
Yes, there is a way to run MathJax at a specific point in your code. MathJax provides a typeset method that you can use to typeset a portion of your page at a specific time. You can use this method to typeset your equations after you have calculated the values for them. Here is an example of how you might do this:
// Calculate your values
let l_D = 3m;
// Add the calculated value to the page using MathJax
let math = document.createElement('math');
math.innerHTML = '$l_D = ' + l_D + '$';
document.body.appendChild(math);
// Typeset the math element using MathJax
MathJax.typeset(math);
This code will add the calculated value of l_D to the page as a MathJax equation, and then use the typeset method to typeset the equation so that it is rendered properly by MathJax.
Alternatively, if you have a large number of equations that you need to typeset, you can use the typesetPromise method to typeset all of the equations on the page at once. This method returns a promise that will be resolved when all of the equations have been typeset, so you can use it to make sure that your equations are rendered properly before your code continues. Here is an example of how you might do this:
// Calculate your values
let l_D = 3m;
// Add the calculated value to the page using MathJax
let math = document.createElement('math');
math.innerHTML = '$l_D = ' + l_D + '$';
document.body.appendChild(math);
// Typeset all of the equations on the page using MathJax
MathJax.typesetPromise().then(function () {
// Your code here, to be executed after all of the equations have been typeset
});
This code will add the calculated value of l_D to the page as a MathJax equation, and then use the typesetPromise method to typeset all of the equations on the page. The code inside the then method will be executed after all of the equations have been typeset, so you can be sure that your equations will be rendered properly when your code continues.
|
Run MathJax at specific point or re-run it somewhere in code
|
Let me simplify the script:
Gets input from user
Calculates stuff
Adds calculated stuff to HTML with MathJax
The problem is, that MathJax runs at the beginning, when the stuff is not calculated yet. It shows 'undefined' in equations. Later, when it's calculated, the equations looks something like this $ l_D = 3m $
Is there any way to run MathJax at specific point? Or to re-run it after that stuff is calculated?
Edit: Someone suggested MathJax.typeset(), but I got an error: Uncaught TypeError: MathJax.typeset is not a function
Link to file in repo, I just need to re-run MathJax at the end of poVypocte function, nearly at the end
EditEdit: SOLVED
I don't know, if it's 'legal', but I made the JavaScript to add MathJax to <head>, like this:
add = document.createElement("script");
add.setAttribute("type", "text/javascript");
add.setAttribute("id", "MathJax-script");
add.setAttribute("defer", true);
add.setAttribute("src","https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js");
document.getElementsByTagName("head")[0].appendChild(add);
+ some more stuff
Thanks for help anyways :)
|
[
"Yes, there is a way to run MathJax at a specific point in your code. MathJax provides a typeset method that you can use to typeset a portion of your page at a specific time. You can use this method to typeset your equations after you have calculated the values for them. Here is an example of how you might do this:\n// Calculate your values\nlet l_D = 3m;\n\n// Add the calculated value to the page using MathJax\nlet math = document.createElement('math');\nmath.innerHTML = '$l_D = ' + l_D + '$';\ndocument.body.appendChild(math);\n\n// Typeset the math element using MathJax\nMathJax.typeset(math);\n\nThis code will add the calculated value of l_D to the page as a MathJax equation, and then use the typeset method to typeset the equation so that it is rendered properly by MathJax.\nAlternatively, if you have a large number of equations that you need to typeset, you can use the typesetPromise method to typeset all of the equations on the page at once. This method returns a promise that will be resolved when all of the equations have been typeset, so you can use it to make sure that your equations are rendered properly before your code continues. Here is an example of how you might do this:\n// Calculate your values\nlet l_D = 3m;\n\n// Add the calculated value to the page using MathJax\nlet math = document.createElement('math');\nmath.innerHTML = '$l_D = ' + l_D + '$';\ndocument.body.appendChild(math);\n\n// Typeset all of the equations on the page using MathJax\nMathJax.typesetPromise().then(function () {\n // Your code here, to be executed after all of the equations have been typeset\n});\n\nThis code will add the calculated value of l_D to the page as a MathJax equation, and then use the typesetPromise method to typeset all of the equations on the page. The code inside the then method will be executed after all of the equations have been typeset, so you can be sure that your equations will be rendered properly when your code continues.\n"
] |
[
0
] |
[] |
[] |
[
"javascript",
"mathjax"
] |
stackoverflow_0074670660_javascript_mathjax.txt
|
Q:
My PATCH request is showing as successful, but nothing is being updated
Trying to make a simple patch request against a single document, and the request returns
{
"acknowledged": true,
"modifiedCount": 1,
"upsertedId": null,
"upsertedCount": 0,
"matchedCount": 1
}
This is the document I am trying to update
{
"_id": "63843e60079d9cdf9c26505a",
"name": "AKG_HSD271",
"image": "images/Products/AKG_hsd271.png",
"colour": "Black",
"description": "AKG HSD271 over-ear headset",
"price": "165.99",
"startingDateAvailable": "2022-05-10T15:23:28.000Z",
"type": "Over-Ear",
"isOnSale": false,
"stock": 46,
"EndingDateAvailable": "N/A",
"manufacturer": "AKG",
"updatedAt": "2022-12-03T08:48:35.302Z"
}
This is the request body I am sending (via Postman)
{
"price": "100.99"
}
And here is the code for my route handler
router.patch('/Products/:id', (req, res) => {
console.log('/Products/'+req.params.id);
const updates = req.body;
Product.updateOne({_id: ObjectId(req.params.id)}, {$set: updates})
.then(result => {
console.log(result);
res.json(result);
})
.catch(err => {
res.status(500).send(err.message);
});
});
Can't for the love of me figure out what is going wrong and why the price field won't change, and can't find any threads that have a suggestion I haven't tried. Any ideas?
A:
Found the problem. Including the built in json() function in express before my route handlers seemed to do the trick:
router.use(express.json())
Apparently in express, the body property does not exist on the req object unless you include the json middleware. Hope this helps others.
|
My PATCH request is showing as successful, but nothing is being updated
|
Trying to make a simple patch request against a single document, and the request returns
{
"acknowledged": true,
"modifiedCount": 1,
"upsertedId": null,
"upsertedCount": 0,
"matchedCount": 1
}
This is the document I am trying to update
{
"_id": "63843e60079d9cdf9c26505a",
"name": "AKG_HSD271",
"image": "images/Products/AKG_hsd271.png",
"colour": "Black",
"description": "AKG HSD271 over-ear headset",
"price": "165.99",
"startingDateAvailable": "2022-05-10T15:23:28.000Z",
"type": "Over-Ear",
"isOnSale": false,
"stock": 46,
"EndingDateAvailable": "N/A",
"manufacturer": "AKG",
"updatedAt": "2022-12-03T08:48:35.302Z"
}
This is the request body I am sending (via Postman)
{
"price": "100.99"
}
And here is the code for my route handler
router.patch('/Products/:id', (req, res) => {
console.log('/Products/'+req.params.id);
const updates = req.body;
Product.updateOne({_id: ObjectId(req.params.id)}, {$set: updates})
.then(result => {
console.log(result);
res.json(result);
})
.catch(err => {
res.status(500).send(err.message);
});
});
Can't for the love of me figure out what is going wrong and why the price field won't change, and can't find any threads that have a suggestion I haven't tried. Any ideas?
|
[
"Found the problem. Including the built in json() function in express before my route handlers seemed to do the trick:\nrouter.use(express.json())\n\nApparently in express, the body property does not exist on the req object unless you include the json middleware. Hope this helps others.\n"
] |
[
0
] |
[] |
[] |
[
"express",
"javascript",
"mongodb",
"node.js"
] |
stackoverflow_0074665301_express_javascript_mongodb_node.js.txt
|
Q:
How can I write xlsx to file in browser with ExcelJS?
I am trying to create an xlsx file in the browser and find https://github.com/exceljs/exceljs very powerful. However, I can't find a way how to save my xlsx object to a file. Probably I need to use Buffer, but how to generate a file from it?
const buffer = await workbook.xlsx.writeBuffer();
This library can generate files in the browser https://docs.sheetjs.com/docs/ but it is not good at building complex fields.
A:
To save the xlsx file in the browser with ExcelJS, you can use the saveAs method. This method allows you to save a file from a JavaScript program in the browser.
Here is an example:
const workbook = new Excel.Workbook();
// Add data to the workbook
const buffer = await workbook.xlsx.writeBuffer();
const fileSaver = require('file-saver');
fileSaver.saveAs(new Blob([buffer]), 'my-file.xlsx');
A:
To generate a file from a Buffer object using the exceljs library, you can use the saveAs method provided by the FileSaver.js library. Here's an example of how you can use it:
const buffer = await workbook.xlsx.writeBuffer();
// Import the FileSaver.js library
import * as FileSaver from 'file-saver';
// Use the FileSaver.js saveAs() method to save the file
FileSaver.saveAs(new Blob([buffer]), 'my-file.xlsx');
The saveAs method will trigger a download prompt in the browser, allowing the user to save the generated file to their local system.
|
How can I write xlsx to file in browser with ExcelJS?
|
I am trying to create an xlsx file in the browser and find https://github.com/exceljs/exceljs very powerful. However, I can't find a way how to save my xlsx object to a file. Probably I need to use Buffer, but how to generate a file from it?
const buffer = await workbook.xlsx.writeBuffer();
This library can generate files in the browser https://docs.sheetjs.com/docs/ but it is not good at building complex fields.
|
[
"To save the xlsx file in the browser with ExcelJS, you can use the saveAs method. This method allows you to save a file from a JavaScript program in the browser.\nHere is an example:\nconst workbook = new Excel.Workbook();\n\n// Add data to the workbook\n\nconst buffer = await workbook.xlsx.writeBuffer();\n\nconst fileSaver = require('file-saver');\n\nfileSaver.saveAs(new Blob([buffer]), 'my-file.xlsx');\n\n",
"To generate a file from a Buffer object using the exceljs library, you can use the saveAs method provided by the FileSaver.js library. Here's an example of how you can use it:\nconst buffer = await workbook.xlsx.writeBuffer();\n\n// Import the FileSaver.js library\nimport * as FileSaver from 'file-saver';\n\n// Use the FileSaver.js saveAs() method to save the file\nFileSaver.saveAs(new Blob([buffer]), 'my-file.xlsx');\n\nThe saveAs method will trigger a download prompt in the browser, allowing the user to save the generated file to their local system.\n"
] |
[
2,
0
] |
[] |
[] |
[
"exceljs",
"javascript",
"xlsx"
] |
stackoverflow_0074670466_exceljs_javascript_xlsx.txt
|
Q:
Function argument evaluation and side effects
The C++20 standard says in Function Call, 7.6.1.3/8:
The initialization of a parameter, including every associated value computation and side effect, is indeterminately sequenced with respect to that of any other parameter.
Indeterminately sequenced (as opposed to unsequenced) ensures that side effects affecting the same memory region are not undefined behavior. Cppreference gives the following examples:
f(i = -2, i = -2); // undefined behavior until C++17
f(++i, ++i); // undefined behavior until C++17, unspecified after C++17
The change in C++17 doesn't seem to be in the quoted section though whose wording essentially stayed the same through the centuries decades. (OK; in n3337 it is only a note.)
And a simple example elicits warnings from both gcc and clang:
void f(int fa, int fb);
void m() // contains code calling f()
{
int a = 11;
f(++a, ++a);
cout << "after f(): a=" << a << '\n';
}
<source>:6:7: warning: multiple unsequenced modifications to 'a' [-Wunsequenced]
f(++a, ++a);
^ ~~
gcc also produces unintuitive code, incrementing a twice before moving its value into both parameter registers. That contradicts my understanding of the standard wording.
Fellow stackoverflow user Davis Herring mentioned in a comment that while the initialization is sequenced, the evaluation of the argument expressions is not.
Am I misinterpreting this wording? Is cppreference wrong? Are the compilers wrong, especially gcc? What, if anything, changed in C++17 regarding specifically function parameters?
A:
If your question is whether "initialization of a parameter" involves evaluating the expression(s) that are part of its initializer... of course it does. Initializing a parameter works exactly like initializing any other object ([dcl.init]/1):
The process of initialization described in this subclause applies to all initializations regardless of syntactic context, including the initialization of a function parameter ([expr.call]), the initialization of a return value ([stmt.return]), or when an initializer follows a declarator.
Emphasis added.
The entirety of [dcl.init] describes the process of initializing objects, but in all cases, it involves evaluating the initializer expression(s). That therefore fits under the "every associated value computation and side effect" part of the rule about sequencing.
Any compiler which doesn't do this for the parameter initializer expression(s) is in error.
Compilers can warn about whatever they want. Indeed, compiler warnings are frequently code that is technically valid but unreasonable.
The main point of even changing this part of the standard is not to make trivial nonsense like f(++a, ++a) into semi-reasonable code. It's for dealing with cases where the writer of the code has no idea that the same object is being referenced in multiple places. Consider:
template<typename ...Args>
void g(Args &&args)
{
f((++args) ...);
}
Pre-C++17, what this code was valid depends entirely on whether the user passed two references to the same object, and a compiler could not reasonably warn about the potential problems. Post-C++17, this code is safe (modulo compiler bugs).
So giving out warnings for easily detectable confusing code is not just valid, but good.
A:
c++17 also added [dcl.init]/18:
If the initializer is a parenthesized expression-list, the expressions are evaluated in the order specified for function calls ([expr.call]).
This clause talks about sequencing of argument expressions and links them to rules for function calls, so i think this actually implies that
"associated value computation" includes evaluation of the argument expressions.
|
Function argument evaluation and side effects
|
The C++20 standard says in Function Call, 7.6.1.3/8:
The initialization of a parameter, including every associated value computation and side effect, is indeterminately sequenced with respect to that of any other parameter.
Indeterminately sequenced (as opposed to unsequenced) ensures that side effects affecting the same memory region are not undefined behavior. Cppreference gives the following examples:
f(i = -2, i = -2); // undefined behavior until C++17
f(++i, ++i); // undefined behavior until C++17, unspecified after C++17
The change in C++17 doesn't seem to be in the quoted section though whose wording essentially stayed the same through the centuries decades. (OK; in n3337 it is only a note.)
And a simple example elicits warnings from both gcc and clang:
void f(int fa, int fb);
void m() // contains code calling f()
{
int a = 11;
f(++a, ++a);
cout << "after f(): a=" << a << '\n';
}
<source>:6:7: warning: multiple unsequenced modifications to 'a' [-Wunsequenced]
f(++a, ++a);
^ ~~
gcc also produces unintuitive code, incrementing a twice before moving its value into both parameter registers. That contradicts my understanding of the standard wording.
Fellow stackoverflow user Davis Herring mentioned in a comment that while the initialization is sequenced, the evaluation of the argument expressions is not.
Am I misinterpreting this wording? Is cppreference wrong? Are the compilers wrong, especially gcc? What, if anything, changed in C++17 regarding specifically function parameters?
|
[
"If your question is whether \"initialization of a parameter\" involves evaluating the expression(s) that are part of its initializer... of course it does. Initializing a parameter works exactly like initializing any other object ([dcl.init]/1):\n\nThe process of initialization described in this subclause applies to all initializations regardless of syntactic context, including the initialization of a function parameter ([expr.call]), the initialization of a return value ([stmt.return]), or when an initializer follows a declarator.\n\nEmphasis added.\nThe entirety of [dcl.init] describes the process of initializing objects, but in all cases, it involves evaluating the initializer expression(s). That therefore fits under the \"every associated value computation and side effect\" part of the rule about sequencing.\nAny compiler which doesn't do this for the parameter initializer expression(s) is in error.\nCompilers can warn about whatever they want. Indeed, compiler warnings are frequently code that is technically valid but unreasonable.\nThe main point of even changing this part of the standard is not to make trivial nonsense like f(++a, ++a) into semi-reasonable code. It's for dealing with cases where the writer of the code has no idea that the same object is being referenced in multiple places. Consider:\ntemplate<typename ...Args>\nvoid g(Args &&args)\n{\n f((++args) ...);\n}\n\nPre-C++17, what this code was valid depends entirely on whether the user passed two references to the same object, and a compiler could not reasonably warn about the potential problems. Post-C++17, this code is safe (modulo compiler bugs).\nSo giving out warnings for easily detectable confusing code is not just valid, but good.\n",
"c++17 also added [dcl.init]/18:\n\nIf the initializer is a parenthesized expression-list, the expressions are evaluated in the order specified for function calls ([expr.call]).\n\nThis clause talks about sequencing of argument expressions and links them to rules for function calls, so i think this actually implies that\n\"associated value computation\" includes evaluation of the argument expressions.\n"
] |
[
6,
0
] |
[] |
[] |
[
"c++",
"c++17",
"language_lawyer",
"side_effects",
"undefined_behavior"
] |
stackoverflow_0071013035_c++_c++17_language_lawyer_side_effects_undefined_behavior.txt
|
Q:
How to `\link{}` to a specific section of an Rd file with Roxygen2?
Say I want to link to the "Details" section of my documentation for function foo, what do I do? \link{foo:Details} doesn't appear to work, so what is the right command?
A:
You can use \linkSections{} to link to sections of an Rd file.
\linkSections{foo}
will link to the section of the foo documentation that you are currently viewing.
If you want to link to a specific section, you can use
\linkSections{foo,Details}
to link to the Details section of the foo documentation.
A:
To link to a specific section of an Rd file with Roxygen2, you can use the \link{} command and specify the name of the Rd file followed by a # symbol and the name of the section you want to link to.
For example, if the name of the Rd file is foo.Rd and the name of the section you want to link to is "Details", you would use the following syntax:
\link{foo.Rd#Details}
Note that the section name must be surrounded by double quotes if it contains spaces or other special characters. For example, if the section name is "Advanced options", you would use the following syntax:
\link{foo.Rd#"Advanced options"}
Additionally, you can use the \code{} command to include the name of the Rd file and the section name in your documentation in a monospaced font, like this:
See the \code{"Details"} section in the \code{foo} Rd file for more information.
This will be rendered as:
See the "Details" section in the foo Rd file for more information.
|
How to `\link{}` to a specific section of an Rd file with Roxygen2?
|
Say I want to link to the "Details" section of my documentation for function foo, what do I do? \link{foo:Details} doesn't appear to work, so what is the right command?
|
[
"You can use \\linkSections{} to link to sections of an Rd file.\n\\linkSections{foo}\n\nwill link to the section of the foo documentation that you are currently viewing.\nIf you want to link to a specific section, you can use\n\\linkSections{foo,Details}\n\nto link to the Details section of the foo documentation.\n",
"To link to a specific section of an Rd file with Roxygen2, you can use the \\link{} command and specify the name of the Rd file followed by a # symbol and the name of the section you want to link to.\nFor example, if the name of the Rd file is foo.Rd and the name of the section you want to link to is \"Details\", you would use the following syntax:\n\\link{foo.Rd#Details}\n\nNote that the section name must be surrounded by double quotes if it contains spaces or other special characters. For example, if the section name is \"Advanced options\", you would use the following syntax:\n\\link{foo.Rd#\"Advanced options\"}\n\nAdditionally, you can use the \\code{} command to include the name of the Rd file and the section name in your documentation in a monospaced font, like this:\nSee the \\code{\"Details\"} section in the \\code{foo} Rd file for more information.\n\nThis will be rendered as:\nSee the \"Details\" section in the foo Rd file for more information.\n"
] |
[
0,
0
] |
[] |
[] |
[
"r",
"roxygen",
"roxygen2"
] |
stackoverflow_0021578412_r_roxygen_roxygen2.txt
|
Q:
Making a graph connecting points with each other
Does anyone know how to plot the following plot:
For more detail:
The dots show the combinations in which the variables (K,Q,W...) were tested with each other. I dont know the code to plot this graph. Can anyone help me here?
I'm very new to Rstudio and don't know the code to plot my data the way I want to.
A:
I don't believe this would be possible in base R. I recommend recreating your dataset manually and then use pivot_longer() so your data is tidy enough for ggplot(). (Also, this kind of figure would probably be easy enough to recreate in PowerPoint if you wanted to go that route.)
library(tidyverse)
letter <- c("K", "Q", "W", "Z")
x1 <- c(1, 1, 0, 0)
x2 <- c(1, 0, 1, 0)
x3 <- c(1, 1, 0, 1)
x4 <- c(0, 0, 1, 1)
x5 <- c(1, 0, 1, 1)
df <- data.frame(letter, x1, x2, x3, x4, x5) %>%
pivot_longer(cols = -letter) %>%
filter(value == 1) %>%
mutate(letter = factor(letter, levels = c("Z", "W", "Q", "K")))
# mutating into a factor orders the `letter` variable so the letters are in your preferred order
# make your color palette
# based off here: https://stackoverflow.com/questions/70099073/make-color-of-one-category-grey-in-ggplot
mycolors <- c("green", "red", "yellow", "blue", "purple")
names(mycolors) <- levels(df$name)
color_scale <- scale_color_manual(name = "grp", values = mycolors)
ggplot(df, aes(x = name, y = letter)) +
geom_line(aes(x = name, group = name)) +
geom_point(aes(color = name), size = 6) +
color_scale +
theme_void() + # very blank ggplot2 theme
theme(legend.position = "none") + # turn off legend
theme(axis.text.y = element_text(color = "black")) # color the yaxis tick marks
|
Making a graph connecting points with each other
|
Does anyone know how to plot the following plot:
For more detail:
The dots show the combinations in which the variables (K,Q,W...) were tested with each other. I dont know the code to plot this graph. Can anyone help me here?
I'm very new to Rstudio and don't know the code to plot my data the way I want to.
|
[
"I don't believe this would be possible in base R. I recommend recreating your dataset manually and then use pivot_longer() so your data is tidy enough for ggplot(). (Also, this kind of figure would probably be easy enough to recreate in PowerPoint if you wanted to go that route.)\nlibrary(tidyverse)\nletter <- c(\"K\", \"Q\", \"W\", \"Z\")\nx1 <- c(1, 1, 0, 0)\nx2 <- c(1, 0, 1, 0)\nx3 <- c(1, 1, 0, 1)\nx4 <- c(0, 0, 1, 1)\nx5 <- c(1, 0, 1, 1)\ndf <- data.frame(letter, x1, x2, x3, x4, x5) %>%\n pivot_longer(cols = -letter) %>%\n filter(value == 1) %>% \n mutate(letter = factor(letter, levels = c(\"Z\", \"W\", \"Q\", \"K\"))) \n # mutating into a factor orders the `letter` variable so the letters are in your preferred order\n\n# make your color palette\n# based off here: https://stackoverflow.com/questions/70099073/make-color-of-one-category-grey-in-ggplot\nmycolors <- c(\"green\", \"red\", \"yellow\", \"blue\", \"purple\")\nnames(mycolors) <- levels(df$name)\ncolor_scale <- scale_color_manual(name = \"grp\", values = mycolors)\n\nggplot(df, aes(x = name, y = letter)) + \n geom_line(aes(x = name, group = name)) + \n geom_point(aes(color = name), size = 6) + \n color_scale +\n theme_void() + # very blank ggplot2 theme\n theme(legend.position = \"none\") + # turn off legend\n theme(axis.text.y = element_text(color = \"black\")) # color the yaxis tick marks\n\n\n"
] |
[
0
] |
[] |
[] |
[
"plot",
"r"
] |
stackoverflow_0074666136_plot_r.txt
|
Q:
Not Receiving Expo Notifications on Android apk when app is killed from menu tray
I did everything right following expo documentation.
Configure Firebase.
Download json file from Firebase.
adding credentials to expo bundle identifier.
Finally I build my app using eas build -p android --profile local
When i download this APK, notifications work fine for me in two states:
When app is open
When app is in background (but not cleared from system tray)
But notifications are no received when I clear out the app (kill app)
My app.json android object structure:
"android": {
"package": "www.blabla.com",
"googleServicesFile": "./google-services.json",
"versionCode": 20,
"useNextNotificationsApi": true,
"config": {
"googleMaps": {
"apiKey": "blablabla"
}
},
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#FFFFFF"
}
},
My eas.json:
{
"cli": {
"version": ">= 2.5.1"
},
"build": {
"development": {
"developmentClient": true,
"distribution": "internal"
},
"local": {
"distribution": "internal",
"android": {
"buildType": "apk"
}
},
"production": {}
},
"submit": {
"production": {}
}
}
My useEffect:
useEffect(() => {
registerForPushNotificationsAsync()
.then((token) => {
setExpoPushToken(token), saveTokenOnline(token);
})
.catch((error) => {
toast.show(error.message, {
type: "danger",
placement: "bottom",
duration: 2000,
animationType: "zoom-in",
});
console.log(error);
console.log(error.message);
});
// This listener is fired whenever a notification is received while the app is foregrounded
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
setNotification(notification);
});
// This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed)
responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
console.log(response);
});
// Do unmounting stuff here
return () => {
Notifications.removeNotificationSubscription(
notificationListener.current
);
Notifications.removeNotificationSubscription(responseListener.current);
};
}, []);
other function:
async function registerForPushNotificationsAsync() {
let token;
if (Device.isDevice) {
const { status: existingStatus } =
await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Failed to get push token for push notification!");
return;
}
token = (await Notifications.getExpoPushTokenAsync()).data;
console.log(token);
saveToken(token);
if (!token) {
toast.show("Error getting Token", {
type: "danger",
placement: "bottom",
duration: 2000,
animationType: "zoom-in",
});
}
} else {
alert("Must use physical device for Push Notifications");
}
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C",
});
}
return token;
}
I need notifications to work even when app is killed
A:
you need to use the Expo.Notifications.setNotificationHandler API. This allows you to specify a function that will be called whenever your app receives a push notification, even if it is killed.
This function can then handle the notification as needed, for example by showing a notification to the user.
import { Notifications } from 'expo';
Notifications.setNotificationHandler({
handleNotification: async () => {
// Show a notification to the user here
}
});
You can also use the setNotificationHandler API to handle notifications when the app is in the background or foreground. can be useful to handle notifications differently depending on the app's state.
|
Not Receiving Expo Notifications on Android apk when app is killed from menu tray
|
I did everything right following expo documentation.
Configure Firebase.
Download json file from Firebase.
adding credentials to expo bundle identifier.
Finally I build my app using eas build -p android --profile local
When i download this APK, notifications work fine for me in two states:
When app is open
When app is in background (but not cleared from system tray)
But notifications are no received when I clear out the app (kill app)
My app.json android object structure:
"android": {
"package": "www.blabla.com",
"googleServicesFile": "./google-services.json",
"versionCode": 20,
"useNextNotificationsApi": true,
"config": {
"googleMaps": {
"apiKey": "blablabla"
}
},
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#FFFFFF"
}
},
My eas.json:
{
"cli": {
"version": ">= 2.5.1"
},
"build": {
"development": {
"developmentClient": true,
"distribution": "internal"
},
"local": {
"distribution": "internal",
"android": {
"buildType": "apk"
}
},
"production": {}
},
"submit": {
"production": {}
}
}
My useEffect:
useEffect(() => {
registerForPushNotificationsAsync()
.then((token) => {
setExpoPushToken(token), saveTokenOnline(token);
})
.catch((error) => {
toast.show(error.message, {
type: "danger",
placement: "bottom",
duration: 2000,
animationType: "zoom-in",
});
console.log(error);
console.log(error.message);
});
// This listener is fired whenever a notification is received while the app is foregrounded
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
setNotification(notification);
});
// This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed)
responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
console.log(response);
});
// Do unmounting stuff here
return () => {
Notifications.removeNotificationSubscription(
notificationListener.current
);
Notifications.removeNotificationSubscription(responseListener.current);
};
}, []);
other function:
async function registerForPushNotificationsAsync() {
let token;
if (Device.isDevice) {
const { status: existingStatus } =
await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Failed to get push token for push notification!");
return;
}
token = (await Notifications.getExpoPushTokenAsync()).data;
console.log(token);
saveToken(token);
if (!token) {
toast.show("Error getting Token", {
type: "danger",
placement: "bottom",
duration: 2000,
animationType: "zoom-in",
});
}
} else {
alert("Must use physical device for Push Notifications");
}
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C",
});
}
return token;
}
I need notifications to work even when app is killed
|
[
"you need to use the Expo.Notifications.setNotificationHandler API. This allows you to specify a function that will be called whenever your app receives a push notification, even if it is killed.\nThis function can then handle the notification as needed, for example by showing a notification to the user.\nimport { Notifications } from 'expo';\n\nNotifications.setNotificationHandler({\n handleNotification: async () => {\n // Show a notification to the user here\n }\n});\n\nYou can also use the setNotificationHandler API to handle notifications when the app is in the background or foreground. can be useful to handle notifications differently depending on the app's state.\n"
] |
[
0
] |
[] |
[] |
[
"expo",
"firebase_cloud_messaging",
"react_native"
] |
stackoverflow_0074666657_expo_firebase_cloud_messaging_react_native.txt
|
Q:
JavaScript is not executed in tracking form
I'm doing an e-commerce website for school and got the task to implement an order tracking system to display the status history of the order. I used a template for this, and half of the code is working. In the views.py file I fetch the information form the database and put it in json format.
However in my html file there is a js script that is supposed to display the iformation from the database and that is not working.
I unfortunately do not have any previous experience with web development, so I'm lost as to why it doesn't work because in the video that used the template it worked.
If someone could help me that would be fantastic as we have to hand the project in in two days.
PS.:
When I put in the ref code and email, it just gives back the HttpResponse with the json. I'm not sure what to do with the HttpResponse though. How does it interact with the script in the html file?
I put
jQuery.noConflict();
at the start of the script as I thought maybe the bootstrap js was overshadowing my script. It didn't do anything though.
Here is my views.py function:
def tracking(request):
if request.method == "POST":
ref_code = request.POST.get('ref_code', '')
email = request.POST.get('email', '')
try:
order = Order.objects.filter(ref_code=ref_code, email=email)
if len(order) > 0:
update = OrderUpdate.objects.filter(ref_code=ref_code)
updates = []
for item in update:
updates.append(
{'text': item.update_desc, 'time': item.timestamp})
response = json.dumps(updates, default=str)
return HttpResponse(response)
else:
return HttpResponse('Please enter a valid ref code and email address.')
finally:
print()
return render(request, 'order_tracking.html')
Here is the script from the order_tracking html file:
<script>
jQuery.noConflict();
$('#trackingForm').submit(function(event) {
$('#items').empty();
var formData = {
'ref_code': $('input[name=ref_code]').val(),
'email': $('input[name=email]').val(),
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
};
print(ref_code)
$.ajax({
type: 'POST',
url: '/order-tracking/',
data: formData,
encode: true
})
.done(function(data) {
console.log(data)
updates = JSON.parse(data);
if (updates.length > 0 & updates != {}) {
for (i = 0; i < updates.length; i++) {
let text = updates[i]['text'];
let time = updates[i]['time'];
mystr = `
<li class="list-group-item d-flex justify-content-between align-items-center">
${text}
<span class="badge badge-primary badge-pill">${time}</span>
</li>`
$('#items').append(mystr);
}
} else {
mystr = `<li class="list-group-item d-flex justify-content-between align-items-center">
Sorry, We are not able to fetch this ref code and email. Make sure to type correct ref code and email</li>`
$('#items').append(mystr);
}
});
event.preventDefault();
});
</script>
And this is the rest of the html file, I'm not sure if it's relevant:
{% block content %}
<div class="container tracking">
<div class="col my-4">
<h2> Enter Your Order ID and Email address to track your order </h2>
<form method="post" action="#" id="trackingForm">{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputname">Ref Code</label>
<input type="text" class="form-control" id="ref_code" name="ref_code" placeholder="Ref Code">
</div>
<div class="form-group col-md-6">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email">
</div>
<button type="submit" class="btn btn-primary">Track Order</button>
</div>
</div>
<div class="col my-4">
<h2>Your Order Status:</h2>
<div class="my-4">
<ul class="list-group" id="items">
</ul>
</div>
</div>
</div>
{% endblock content %}
A:
There are a few potential issues with your code:
You are not rendering the JSON data in the HTML template, so the information from the database is not being displayed on the page. You will need to pass the data from the database to the HTML template and then use it to populate the elements on the page.
The JavaScript code is not being executed, as it is not within a document ready function. This means that it will not run when the page loads. You will need to wrap your code in a document ready function, like this:
$(document).ready(function() {
// your code here
});
You are using jQuery's .noConflict() function, which is meant to be used when multiple libraries are being used on the same page. This may be causing issues with the code, as it is not necessary in this case. You can remove the .noConflict() call and just use $ as the shorthand for jQuery.
The print(ref_code) line in your code is not being executed, as it is not within a function. This may be causing issues with the code, as it is not being called. You will need to move this line of code into a function, like this:
function printRefCode() {
print(ref_code);
}
The $.ajax() call is not being executed, as it is not within a function. This may be causing issues with the code, as it is not being called. You will need to move this line of code into a function, like this:
function submitForm() {
$.ajax({
type: 'POST',
url: '/order-tracking/',
data: formData,
encode: true
});
}
I hope this helps you out! And good luck on the assignment!
|
JavaScript is not executed in tracking form
|
I'm doing an e-commerce website for school and got the task to implement an order tracking system to display the status history of the order. I used a template for this, and half of the code is working. In the views.py file I fetch the information form the database and put it in json format.
However in my html file there is a js script that is supposed to display the iformation from the database and that is not working.
I unfortunately do not have any previous experience with web development, so I'm lost as to why it doesn't work because in the video that used the template it worked.
If someone could help me that would be fantastic as we have to hand the project in in two days.
PS.:
When I put in the ref code and email, it just gives back the HttpResponse with the json. I'm not sure what to do with the HttpResponse though. How does it interact with the script in the html file?
I put
jQuery.noConflict();
at the start of the script as I thought maybe the bootstrap js was overshadowing my script. It didn't do anything though.
Here is my views.py function:
def tracking(request):
if request.method == "POST":
ref_code = request.POST.get('ref_code', '')
email = request.POST.get('email', '')
try:
order = Order.objects.filter(ref_code=ref_code, email=email)
if len(order) > 0:
update = OrderUpdate.objects.filter(ref_code=ref_code)
updates = []
for item in update:
updates.append(
{'text': item.update_desc, 'time': item.timestamp})
response = json.dumps(updates, default=str)
return HttpResponse(response)
else:
return HttpResponse('Please enter a valid ref code and email address.')
finally:
print()
return render(request, 'order_tracking.html')
Here is the script from the order_tracking html file:
<script>
jQuery.noConflict();
$('#trackingForm').submit(function(event) {
$('#items').empty();
var formData = {
'ref_code': $('input[name=ref_code]').val(),
'email': $('input[name=email]').val(),
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
};
print(ref_code)
$.ajax({
type: 'POST',
url: '/order-tracking/',
data: formData,
encode: true
})
.done(function(data) {
console.log(data)
updates = JSON.parse(data);
if (updates.length > 0 & updates != {}) {
for (i = 0; i < updates.length; i++) {
let text = updates[i]['text'];
let time = updates[i]['time'];
mystr = `
<li class="list-group-item d-flex justify-content-between align-items-center">
${text}
<span class="badge badge-primary badge-pill">${time}</span>
</li>`
$('#items').append(mystr);
}
} else {
mystr = `<li class="list-group-item d-flex justify-content-between align-items-center">
Sorry, We are not able to fetch this ref code and email. Make sure to type correct ref code and email</li>`
$('#items').append(mystr);
}
});
event.preventDefault();
});
</script>
And this is the rest of the html file, I'm not sure if it's relevant:
{% block content %}
<div class="container tracking">
<div class="col my-4">
<h2> Enter Your Order ID and Email address to track your order </h2>
<form method="post" action="#" id="trackingForm">{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputname">Ref Code</label>
<input type="text" class="form-control" id="ref_code" name="ref_code" placeholder="Ref Code">
</div>
<div class="form-group col-md-6">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email">
</div>
<button type="submit" class="btn btn-primary">Track Order</button>
</div>
</div>
<div class="col my-4">
<h2>Your Order Status:</h2>
<div class="my-4">
<ul class="list-group" id="items">
</ul>
</div>
</div>
</div>
{% endblock content %}
|
[
"There are a few potential issues with your code:\nYou are not rendering the JSON data in the HTML template, so the information from the database is not being displayed on the page. You will need to pass the data from the database to the HTML template and then use it to populate the elements on the page.\nThe JavaScript code is not being executed, as it is not within a document ready function. This means that it will not run when the page loads. You will need to wrap your code in a document ready function, like this:\n$(document).ready(function() {\n // your code here\n});\n\nYou are using jQuery's .noConflict() function, which is meant to be used when multiple libraries are being used on the same page. This may be causing issues with the code, as it is not necessary in this case. You can remove the .noConflict() call and just use $ as the shorthand for jQuery.\nThe print(ref_code) line in your code is not being executed, as it is not within a function. This may be causing issues with the code, as it is not being called. You will need to move this line of code into a function, like this:\nfunction printRefCode() {\n print(ref_code);\n}\n\nThe $.ajax() call is not being executed, as it is not within a function. This may be causing issues with the code, as it is not being called. You will need to move this line of code into a function, like this:\nfunction submitForm() {\n $.ajax({\n type: 'POST',\n url: '/order-tracking/',\n data: formData,\n encode: true\n });\n}\n\nI hope this helps you out! And good luck on the assignment!\n"
] |
[
0
] |
[] |
[] |
[
"ajax",
"javascript",
"jquery",
"python"
] |
stackoverflow_0074667191_ajax_javascript_jquery_python.txt
|
Q:
Ruby method gsub with string '+'
I've found interesting thing in ruby. Do anybody know why is behavior?
tried '+'.gsub!('+', '\+') and expected "\\+" but got ""(empty string)
A:
gsub is implemented, after some indirection, as rb_sub_str_bang in C, which calls rb_reg_regsub.
Now, gsub is supposed to allow the replacement string to contain backreferences. That is, if you pass a regular expression as the first argument and that regex defines a capture group, then your replacement string can include \1 to indicate that that capture group should be placed at that position.
That behavior evidently still happens if you pass an ordinary, non-regex string as the pattern. Your verbatim string obviously won't have any capture groups, so it's a bit silly in this case. But trying to replace, for instance, + with \1 in the string + will give the empty string, since \1 says to go get the first capture group, which doesn't exist and hence is vacuously "".
Now, you might be thinking: + isn't a number. And you'd be right. You're replacing + with \+. There are several other backreferences allowed in your replacement string. I couldn't find any official documentation where these are written down, but the source code does quite fine. To summarize the code:
Digits \1 through \9 refer to numbered capture groups.
\k<...> refers to a named capture group, with the name in angled brackets.
\0 or \& refer to the whole substring that was matched, so (\0) as a replacement string would enclose the match in parentheses.
A backslash followed by a backtick (I have no idea how to write that using StackOverflow's markdown) refers to the entire string up to the match.
\' refers to the entire string following the match.
\+ refers to the final capture group, i.e. the one with the highest number.
\\ is a literal backslash.
(Most of these are based on Perl variables of a similar name)
So, in your examples,
\+ as the replacement string says "take the last capture group". There is no capture group, so you get the empty string.
\- is not a valid backreference, so it's replaced verbatim.
\ok is, likewise, not a backreference, so it's replaced verbatim.
In \\+, Ruby eats the first backslash sequence, so the actual string at runtime is \+, equivalent to the first example.
For \\\+, Ruby processes the first backslash sequence, so we get \\+ by the time the replacement function sees it. \\ is a literal backslash, and + is no longer part of an escape sequence, so we get \+.
|
Ruby method gsub with string '+'
|
I've found interesting thing in ruby. Do anybody know why is behavior?
tried '+'.gsub!('+', '\+') and expected "\\+" but got ""(empty string)
|
[
"gsub is implemented, after some indirection, as rb_sub_str_bang in C, which calls rb_reg_regsub.\nNow, gsub is supposed to allow the replacement string to contain backreferences. That is, if you pass a regular expression as the first argument and that regex defines a capture group, then your replacement string can include \\1 to indicate that that capture group should be placed at that position.\nThat behavior evidently still happens if you pass an ordinary, non-regex string as the pattern. Your verbatim string obviously won't have any capture groups, so it's a bit silly in this case. But trying to replace, for instance, + with \\1 in the string + will give the empty string, since \\1 says to go get the first capture group, which doesn't exist and hence is vacuously \"\".\nNow, you might be thinking: + isn't a number. And you'd be right. You're replacing + with \\+. There are several other backreferences allowed in your replacement string. I couldn't find any official documentation where these are written down, but the source code does quite fine. To summarize the code:\n\nDigits \\1 through \\9 refer to numbered capture groups.\n\\k<...> refers to a named capture group, with the name in angled brackets.\n\\0 or \\& refer to the whole substring that was matched, so (\\0) as a replacement string would enclose the match in parentheses.\nA backslash followed by a backtick (I have no idea how to write that using StackOverflow's markdown) refers to the entire string up to the match.\n\\' refers to the entire string following the match.\n\\+ refers to the final capture group, i.e. the one with the highest number.\n\n\n\\\\ is a literal backslash.\n\n(Most of these are based on Perl variables of a similar name)\nSo, in your examples,\n\n\\+ as the replacement string says \"take the last capture group\". There is no capture group, so you get the empty string.\n\\- is not a valid backreference, so it's replaced verbatim.\n\\ok is, likewise, not a backreference, so it's replaced verbatim.\nIn \\\\+, Ruby eats the first backslash sequence, so the actual string at runtime is \\+, equivalent to the first example.\nFor \\\\\\+, Ruby processes the first backslash sequence, so we get \\\\+ by the time the replacement function sees it. \\\\ is a literal backslash, and + is no longer part of an escape sequence, so we get \\+.\n\n"
] |
[
4
] |
[] |
[] |
[
"gsub",
"methods",
"ruby"
] |
stackoverflow_0074670523_gsub_methods_ruby.txt
|
Q:
Disable clicking in one mapbox layer, when the other is visible
There are two layers in a mapbox map inside a react app. I am new to both. I want to disable clicking in one layer, when the other is visible. I control the visibility of each layer from a checkbox value via react.
I have this code
export default function Map () {
const [checkedLayer, setCheckedLayer] = useState(true);
const [checkedOtherLayer, setCheckedOtherLayer] = useState(true);
//when a checkbox is on or off make layer visible or not
const handleVisibility = (event) => {
let visible ; let layer;
event.target.checked ? visible = 'visible' : visible = 'none'
if (event.target.id === 'mylayer') {
setCheckedLayer(event.target.checked);
layer = 'mylayer';
}
if (event.target.id === 'myotherlayer') {
setCheckedOtherLayer(event.target.checked);
layer = 'myotherlayer';
}
map.current.setLayoutProperty(layer, 'visibility', visible);
};
useEffect(() => {
if (map.current) return; // initialize map only once
map.current = new mapboxgl.Map({
container: mapContainer.current,
style: 'mapbox://styles/mapbox/satellite-streets-v11',
center: [lng, lat],
zoom: zoom
});//map
map.current.on('load', () => {
//...set layers and sources
});//load
map.current.on('click', 'mylayer', (e) => {
console.log('other layer visibility ', map.current.getLayoutProperty('myotherlayer', 'visibility'));
// I want to do something like
// if map.current.getLayoutProperty('myotherlayer', 'visibility')) == 'visible'
// return
// but the above console.log keeps giving "undefined"
// map.current.getLayoutProperty('mylayer', 'visibility') works
});
},[checkedLayer, checkedOtherLayer]);//useEffect
return (
<div>
<Checkbox
id="mylayer"
checked={checkedLayer}
onChange={handleVisibility}
inputProps={{ 'aria-label': 'controlled' }}
/>
<Checkbox
id="myotherlayer"
checked={checkedOtherLayer}
onChange={handleVisibility}
inputProps={{ 'aria-label': 'controlled' }}
/>
<div ref={mapContainer} className="map-container"> </div>
</div>
)
}
When mylayer is clicked I try to check the value of the visibility of myotherlayer and if it is visible, return, so nothing is executed inside 'click', 'mylayer' function. But the value of map.current.getLayoutProperty('myotherlayer', 'visibility')); is undefined.
What am I doing wrong here?
Thanks
A:
It looks like you are trying to access the value of map.current.getLayoutProperty('myotherlayer', 'visibility') outside of the map.current.on('load', ...) callback function. This is likely causing the value to be undefined, because the map.current.on('load', ...) callback function hasn't been called yet, so the layers have not yet been added to the map.
You can fix this by moving the code that checks the value of map.current.getLayoutProperty('myotherlayer', 'visibility') inside the map.current.on('load', ...) callback function, so that it is executed after the layers have been added to the map.
Here is an example of how you could update your code to do this:
export default function Map () {
// Other code here
useEffect(() => {
if (map.current) return; // initialize map only once
// Initialize the map
map.current = new mapboxgl.Map({
container: mapContainer.current,
style: 'mapbox://styles/mapbox/satellite-streets-v11',
center: [lng, lat],
zoom: zoom
});
// Add event listener for when the map is loaded
map.current.on('load', () => {
// Add layers and sources
// Add event listener for when 'mylayer' is clicked
map.current.on('click', 'mylayer', (e) => {
// Check the visibility of 'myotherlayer'
if (map.current.getLayoutProperty('myotherlayer', 'visibility') == 'visible') {
// 'myotherlayer' is visible, so return
return;
}
// Do something when 'mylayer' is clicked
});
});
},[checkedLayer, checkedOtherLayer]);
// Other code here
}
A:
It looks like you are trying to check the visibility of a layer in your Mapbox map when another layer is clicked, but you are encountering an issue where the visibility value is undefined. This is likely happening because the mapboxgl.Map#setLayoutProperty method is asynchronous, which means that the setLayoutProperty call that sets the visibility of the myotherlayer layer may not have completed before you try to retrieve its visibility value in the click event handler for the mylayer layer.
To fix this issue, you can use the mapboxgl.Map#on method to listen for the 'data' event on the myotherlayer layer, which will be triggered when the setLayoutProperty call completes. This can be done like this:
// In the 'click' event handler for the 'mylayer' layer
map.current.on('data', 'myotherlayer', () => {
const visibility = map.current.getLayoutProperty('myotherlayer', 'visibility');
if (visibility === 'visible') return;
// Execute the rest of the code in the 'click' event handler for the 'mylayer' layer
...
});
With this change, the code in the click event handler for the mylayer layer will only be executed when the myotherlayer layer is not visible. I hope this helps! Let me know if you have any other questions.
|
Disable clicking in one mapbox layer, when the other is visible
|
There are two layers in a mapbox map inside a react app. I am new to both. I want to disable clicking in one layer, when the other is visible. I control the visibility of each layer from a checkbox value via react.
I have this code
export default function Map () {
const [checkedLayer, setCheckedLayer] = useState(true);
const [checkedOtherLayer, setCheckedOtherLayer] = useState(true);
//when a checkbox is on or off make layer visible or not
const handleVisibility = (event) => {
let visible ; let layer;
event.target.checked ? visible = 'visible' : visible = 'none'
if (event.target.id === 'mylayer') {
setCheckedLayer(event.target.checked);
layer = 'mylayer';
}
if (event.target.id === 'myotherlayer') {
setCheckedOtherLayer(event.target.checked);
layer = 'myotherlayer';
}
map.current.setLayoutProperty(layer, 'visibility', visible);
};
useEffect(() => {
if (map.current) return; // initialize map only once
map.current = new mapboxgl.Map({
container: mapContainer.current,
style: 'mapbox://styles/mapbox/satellite-streets-v11',
center: [lng, lat],
zoom: zoom
});//map
map.current.on('load', () => {
//...set layers and sources
});//load
map.current.on('click', 'mylayer', (e) => {
console.log('other layer visibility ', map.current.getLayoutProperty('myotherlayer', 'visibility'));
// I want to do something like
// if map.current.getLayoutProperty('myotherlayer', 'visibility')) == 'visible'
// return
// but the above console.log keeps giving "undefined"
// map.current.getLayoutProperty('mylayer', 'visibility') works
});
},[checkedLayer, checkedOtherLayer]);//useEffect
return (
<div>
<Checkbox
id="mylayer"
checked={checkedLayer}
onChange={handleVisibility}
inputProps={{ 'aria-label': 'controlled' }}
/>
<Checkbox
id="myotherlayer"
checked={checkedOtherLayer}
onChange={handleVisibility}
inputProps={{ 'aria-label': 'controlled' }}
/>
<div ref={mapContainer} className="map-container"> </div>
</div>
)
}
When mylayer is clicked I try to check the value of the visibility of myotherlayer and if it is visible, return, so nothing is executed inside 'click', 'mylayer' function. But the value of map.current.getLayoutProperty('myotherlayer', 'visibility')); is undefined.
What am I doing wrong here?
Thanks
|
[
"It looks like you are trying to access the value of map.current.getLayoutProperty('myotherlayer', 'visibility') outside of the map.current.on('load', ...) callback function. This is likely causing the value to be undefined, because the map.current.on('load', ...) callback function hasn't been called yet, so the layers have not yet been added to the map.\nYou can fix this by moving the code that checks the value of map.current.getLayoutProperty('myotherlayer', 'visibility') inside the map.current.on('load', ...) callback function, so that it is executed after the layers have been added to the map.\nHere is an example of how you could update your code to do this:\nexport default function Map () {\n // Other code here\n\n useEffect(() => { \n if (map.current) return; // initialize map only once\n\n // Initialize the map\n map.current = new mapboxgl.Map({\n container: mapContainer.current, \n style: 'mapbox://styles/mapbox/satellite-streets-v11',\n center: [lng, lat],\n zoom: zoom\n });\n\n // Add event listener for when the map is loaded\n map.current.on('load', () => { \n // Add layers and sources\n\n // Add event listener for when 'mylayer' is clicked\n map.current.on('click', 'mylayer', (e) => {\n // Check the visibility of 'myotherlayer'\n if (map.current.getLayoutProperty('myotherlayer', 'visibility') == 'visible') {\n // 'myotherlayer' is visible, so return\n return;\n }\n\n // Do something when 'mylayer' is clicked\n });\n });\n },[checkedLayer, checkedOtherLayer]);\n\n // Other code here\n}\n\n",
"It looks like you are trying to check the visibility of a layer in your Mapbox map when another layer is clicked, but you are encountering an issue where the visibility value is undefined. This is likely happening because the mapboxgl.Map#setLayoutProperty method is asynchronous, which means that the setLayoutProperty call that sets the visibility of the myotherlayer layer may not have completed before you try to retrieve its visibility value in the click event handler for the mylayer layer.\nTo fix this issue, you can use the mapboxgl.Map#on method to listen for the 'data' event on the myotherlayer layer, which will be triggered when the setLayoutProperty call completes. This can be done like this:\n// In the 'click' event handler for the 'mylayer' layer\nmap.current.on('data', 'myotherlayer', () => {\n const visibility = map.current.getLayoutProperty('myotherlayer', 'visibility');\n if (visibility === 'visible') return;\n\n // Execute the rest of the code in the 'click' event handler for the 'mylayer' layer\n ...\n});\n\nWith this change, the code in the click event handler for the mylayer layer will only be executed when the myotherlayer layer is not visible. I hope this helps! Let me know if you have any other questions.\n"
] |
[
0,
0
] |
[] |
[] |
[
"mapbox",
"mapbox_gl_js",
"react_hooks",
"reactjs"
] |
stackoverflow_0074575016_mapbox_mapbox_gl_js_react_hooks_reactjs.txt
|
Q:
How to convert uint8 in brackets to (r, g, b) value
Hey guys i found my self stuck on this. I am making an obs spotify app that shows you album cover, name of the artist, and now i would like to add average color output but i need it in rgb.
this is the average code with this output: [112.62674316 103.23660889 98.91593262]
src_img = cv2.imread('icon.jpeg')
average_color_row = np.average(src_img, axis=0)
average_color = np.average(average_color_row, axis=0)
print(average_color)
d_img = np.ones((312,312,3), dtype=np.uint8)
d_img[:,:] = average_color
And i would like it to be converted to (122, 103, 98) yeah and im not also shure if thats right :)
Thanks for help
Tried converting with cv2
and of course searching the internet for alternatives
A:
It looks like the code you posted is using the NumPy library to calculate the average color of an image. The output you're seeing, [112.62674316 103.23660889 98.91593262], is an array of floating point values representing the average values of the red, green, and blue channels of the image, respectively.
To convert this array to a tuple of integers, you can use the NumPy round function to round each value to the nearest integer, and then use the astype function to convert the resulting array to a tuple of integers. Here's how you could do that:
# Calculate the average color of the image
src_img = cv2.imread('icon.jpeg')
average_color_row = np.average(src_img, axis=0)
average_color = np.average(average_color_row, axis=0)
# Round the average color values to the nearest integer
average_color = np.round(average_color)
# Convert the rounded values to a tuple of integers
average_color = average_color.astype(np.int)
# Print the resulting tuple
print(average_color)
This should give you the output you're looking for: (122, 103, 98).
|
How to convert uint8 in brackets to (r, g, b) value
|
Hey guys i found my self stuck on this. I am making an obs spotify app that shows you album cover, name of the artist, and now i would like to add average color output but i need it in rgb.
this is the average code with this output: [112.62674316 103.23660889 98.91593262]
src_img = cv2.imread('icon.jpeg')
average_color_row = np.average(src_img, axis=0)
average_color = np.average(average_color_row, axis=0)
print(average_color)
d_img = np.ones((312,312,3), dtype=np.uint8)
d_img[:,:] = average_color
And i would like it to be converted to (122, 103, 98) yeah and im not also shure if thats right :)
Thanks for help
Tried converting with cv2
and of course searching the internet for alternatives
|
[
"It looks like the code you posted is using the NumPy library to calculate the average color of an image. The output you're seeing, [112.62674316 103.23660889 98.91593262], is an array of floating point values representing the average values of the red, green, and blue channels of the image, respectively.\nTo convert this array to a tuple of integers, you can use the NumPy round function to round each value to the nearest integer, and then use the astype function to convert the resulting array to a tuple of integers. Here's how you could do that:\n# Calculate the average color of the image\nsrc_img = cv2.imread('icon.jpeg')\naverage_color_row = np.average(src_img, axis=0)\naverage_color = np.average(average_color_row, axis=0)\n\n# Round the average color values to the nearest integer\naverage_color = np.round(average_color)\n\n# Convert the rounded values to a tuple of integers\naverage_color = average_color.astype(np.int)\n\n# Print the resulting tuple\nprint(average_color)\n\nThis should give you the output you're looking for: (122, 103, 98).\n"
] |
[
0
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0074670693_numpy_python.txt
|
Q:
Automatically Show ShapeSheet of Current Shape
I do a lot of Visio ShapeSheet editing and it would save me a tremendous amount of time to automatically switch to the current shape's sheet when I select a new shape. Let's assume I only have 1 ShapeSheet open, only select 1 Shape, and have all the windows docked on the Visio app (I don't have RegEdit powers to change this).
So far, I've got the following VBA code in ThisDocument:
Private WithEvents vsoWin as Visio.Window
Private Sub ThisDocument_RunModeEntered(ByRef doc as IVDocument)
'Just assume this is the correct window
Set vsoWin = ActiveWindow
End Sub
Private Sub vsoWin_SelectionChanged(ByRef win as IVWindow)
'If nothing is selected, leave
If vsoWin.Selection.Count < 1 Then Exit Sub
'Look for a ShapeSheet (Window.SubType = 3)
For each oWin in Application.Windows
If oWin.Subtype = 3 Then
Application.ScreenUpdating = False 'Pause screen to prevent jitter
oWin.Close 'Delete old ShapeSheet
vsoWin.Selection(1).OpenSheetWindow 'Make new ShapeSheet
Application.ScreenUpdating = True 'Update visuals
Exit For 'Stop looking for ShapeSheets
End If
Next
Exit Sub
(The above code is written from memory since I don't have access to Visio at the moment. Please forgive any minor errors)
This code works, but I'm hoping for a less jittery result. Application.ScreenUpdating = False doesn't seem to do anything in this case: I still briefly witness the old ShapeSheet closing, the drawing window resizing, then the new ShapeSheet opening. Swapping the order (open new window > close old window) is a little less chaotic, but not great. Using Application.Minimize to hide the swap instead is slightly better on the eyes, but still not a smooth transition.
My question: Is there a smoother way to display the active shape's ShapeSheet?
A:
This code works at my side! I just add variable which related with Visio Application - vsoApp.
Private WithEvents vsoWin As Visio.Window
Private WithEvents vsoApp As Visio.Application
Sub st()
Set vsoWin = ActiveWindow ' initialize Window variable
Set vsoApp = Application ' initialize Application variable
End Sub
Private Sub ThisDocument_RunModeEntered(ByRef doc As IVDocument)
'Just assume this is the correct window
Set vsoWin = ActiveWindow
End Sub
Private Sub vsoApp_SelectionChanged(ByVal Window As IVWindow)
'If nothing is selected, leave
If vsoWin.Selection.Count < 1 Then Exit Sub
'Look for a ShapeSheet (Window.SubType = 3)
For Each oWin In Application.Windows
If oWin.SubType = 3 Then
Application.ScreenUpdating = False 'Pause screen to prevent jitter
oWin.Close 'Delete old ShapeSheet
vsoWin.Selection(1).OpenSheetWindow 'Make new ShapeSheet
Application.ScreenUpdating = True 'Update visuals
Exit For 'Stop looking for ShapeSheets
End If
Next
End Sub
My workaround:
Press Alt+F8 keys and run St sub-routine.
Open ShapeSheet window for selected shape.
Select another shapes and so on...
|
Automatically Show ShapeSheet of Current Shape
|
I do a lot of Visio ShapeSheet editing and it would save me a tremendous amount of time to automatically switch to the current shape's sheet when I select a new shape. Let's assume I only have 1 ShapeSheet open, only select 1 Shape, and have all the windows docked on the Visio app (I don't have RegEdit powers to change this).
So far, I've got the following VBA code in ThisDocument:
Private WithEvents vsoWin as Visio.Window
Private Sub ThisDocument_RunModeEntered(ByRef doc as IVDocument)
'Just assume this is the correct window
Set vsoWin = ActiveWindow
End Sub
Private Sub vsoWin_SelectionChanged(ByRef win as IVWindow)
'If nothing is selected, leave
If vsoWin.Selection.Count < 1 Then Exit Sub
'Look for a ShapeSheet (Window.SubType = 3)
For each oWin in Application.Windows
If oWin.Subtype = 3 Then
Application.ScreenUpdating = False 'Pause screen to prevent jitter
oWin.Close 'Delete old ShapeSheet
vsoWin.Selection(1).OpenSheetWindow 'Make new ShapeSheet
Application.ScreenUpdating = True 'Update visuals
Exit For 'Stop looking for ShapeSheets
End If
Next
Exit Sub
(The above code is written from memory since I don't have access to Visio at the moment. Please forgive any minor errors)
This code works, but I'm hoping for a less jittery result. Application.ScreenUpdating = False doesn't seem to do anything in this case: I still briefly witness the old ShapeSheet closing, the drawing window resizing, then the new ShapeSheet opening. Swapping the order (open new window > close old window) is a little less chaotic, but not great. Using Application.Minimize to hide the swap instead is slightly better on the eyes, but still not a smooth transition.
My question: Is there a smoother way to display the active shape's ShapeSheet?
|
[
"This code works at my side! I just add variable which related with Visio Application - vsoApp.\nPrivate WithEvents vsoWin As Visio.Window\nPrivate WithEvents vsoApp As Visio.Application\n\nSub st()\nSet vsoWin = ActiveWindow ' initialize Window variable\nSet vsoApp = Application ' initialize Application variable\nEnd Sub\n\nPrivate Sub ThisDocument_RunModeEntered(ByRef doc As IVDocument)\n 'Just assume this is the correct window\n Set vsoWin = ActiveWindow\nEnd Sub\n\nPrivate Sub vsoApp_SelectionChanged(ByVal Window As IVWindow)\n 'If nothing is selected, leave\n \n If vsoWin.Selection.Count < 1 Then Exit Sub\n\n 'Look for a ShapeSheet (Window.SubType = 3)\n For Each oWin In Application.Windows\n If oWin.SubType = 3 Then\n Application.ScreenUpdating = False 'Pause screen to prevent jitter\n oWin.Close 'Delete old ShapeSheet\n vsoWin.Selection(1).OpenSheetWindow 'Make new ShapeSheet\n Application.ScreenUpdating = True 'Update visuals\n Exit For 'Stop looking for ShapeSheets\n End If\n Next\n\nEnd Sub\n\nMy workaround:\n\nPress Alt+F8 keys and run St sub-routine.\nOpen ShapeSheet window for selected shape.\nSelect another shapes and so on...\n\n\n"
] |
[
1
] |
[] |
[] |
[
"optimization",
"shapesheet",
"vba",
"visio"
] |
stackoverflow_0074660772_optimization_shapesheet_vba_visio.txt
|
Q:
Creating a Readable stream from emitted data chunks
Short backstory: I am trying to create a Readable stream based on data chunks that are emitted back to my server from the client side with WebSockets. Here's a class I've created to "simulate" that behavior:
class DataEmitter extends EventEmitter {
constructor() {
super();
const data = ['foo', 'bar', 'baz', 'hello', 'world', 'abc', '123'];
// Every second, emit an event with a chunk of data
const interval = setInterval(() => {
this.emit('chunk', data.splice(0, 1)[0]);
// Once there are no more items, emit an event
// notifying that that is the case
if (!data.length) {
this.emit('done');
clearInterval(interval);
}
}, 1e3);
}
}
In this post, the dataEmitter in question will have been created like this.
// Our data is being emitted through events in chunks from some place.
// This is just to simulate that. We cannot change the flow - only listen
// for the events and do something with the chunks.
const dataEmitter = new DataEmitter();
Right, so I initially tried this:
const readable = new Readable();
dataEmitter.on('chunk', (data) => {
readable.push(data);
});
dataEmitter.once('done', () => {
readable.push(null);
});
But that results in this error:
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _read() method is not implemented
So I did this, implementing read() as an empty function:
const readable = new Readable({
read() {},
});
dataEmitter.on('chunk', (data) => {
readable.push(data);
});
dataEmitter.once('done', () => {
readable.push(null);
});
And it works when piping into a write stream, or sending the stream to my test API server. The resulting .txt file looks exactly as it should:
foobarbazhelloworldabc123
However, I feel like there's something quite wrong and hacky with my solution. I attempted to put the listener registration logic (.on('chunk', ...) and .once('done', ...)) within the read() implementation; however, read() seems to get called multiple times, and that results in the listeners being registered multiple times.
The Node.js documentation says this about the _read() method:
When readable._read() is called, if data is available from the resource, the implementation should begin pushing that data into the read queue using the this.push(dataChunk) method. _read() will be called again after each call to this.push(dataChunk) once the stream is ready to accept more data. _read() may continue reading from the resource and pushing data until readable.push() returns false. Only when _read() is called again after it has stopped should it resume pushing additional data into the queue.
After dissecting this, it seems that the consumer of the stream calls upon .read() when it's ready to read more data. And when it is called, data should be pushed into the stream. But, if it is not called, the stream should not have data pushed into it until the method is called again (???). So wait, does the consumer call .read() when it is ready for more data, or does it call it after each time .push() is called? Or both?? The docs seem to contradict themselves.
Implementing .read() on Readable is straightforward when you've got a basic resource to stream, but what would be the proper way of implementing it in this case?
And also, would someone be able to explain in better terms what the .read() method is on a deeper level, and how it should be implemented?
Thanks!
Response to the answer:
I did try registering the listeners within the read() implementation, but because it is called multiple times by the consumer, it registers the listeners multiple times.
Observing this code:
const readable = new Readable({
read() {
console.log('called');
dataEmitter.on('chunk', (data) => {
readable.push(data);
});
dataEmitter.once('done', () => {
readable.push(null);
});
},
});
readable.pipe(createWriteStream('./data.txt'));
The resulting file looks like this:
foobarbarbazbazbazhellohellohellohelloworldworldworldworldworldabcabcabcabcabcabc123123123123123123123
Which makes sense, because the listeners are being registered multiple times.
A:
In general, the _read() method of a Readable stream is used to implement the logic for how the stream should read data from its source. When a consumer of the stream calls the read() method, the _read() method will be called to provide data to the stream. This data will be pushed into the stream's buffer, where it can be read by the consumer.
In your specific case, you are using events to provide data to the stream, rather than a traditional data source like a file or network connection. In this case, you can still use the _read method to implement the logic for reading data from the events, but you will need to register event listeners within the _read() method to ensure that they are only registered once, rather than multiple times.
Here is an example of how you might implement the _read() method in your DataEmitter stream:
const readable = new Readable({
_read() {
// Register event listeners for the 'chunk' and 'done' events
dataEmitter.on('chunk', (data) => {
readable.push(data);
});
dataEmitter.once('done', () => {
readable.push(null);
});
},
});
In this example, the _read() method is called whenever the stream's consumer calls the read() method. This ensures that the event listeners are only registered once, and that data from the 'chunk' events is pushed into the stream as it is received.
As for the deeper meaning of the read() method on a Readable stream, this method is used by the consumer of the stream to request data from the stream. When the consumer calls read(), the _read() method is called to provide data to the stream, which is then pushed into the stream's buffer. The consumer can then access this data by reading from the stream. This allows the consumer to control the flow of data from the stream, and ensure that it only receives data when it is ready to process it.
Update:
In your code, you are creating a readable stream using the Readable class, but you are not implementing the _read() method. This is why you are seeing the error Error [ERR_METHOD_NOT_IMPLEMENTED]: The _read() method is not implemented.
To fix this error, you can implement the _read() method in your Readable class. The _read() method should be responsible for pushing data into the stream when the consumer is ready to receive it. In your case, you can register listeners for the 'chunk' and 'done' events on the dataEmitter within the _read() method. When the 'chunk' event is emitted, you can push the data into the stream using the this.push() method. When the 'done' event is emitted, you can call this.push(null) to signal the end of the stream.
Here is an example of how you can implement the _read() method in your Readable class:
class DataEmitter extends EventEmitter {
constructor() {
super();
const data = ["foo", "bar", "baz", "hello", "world", "abc", "123"];
// Every second, emit an event with a chunk of data
const interval = setInterval(() => {
this.emit("chunk", data.splice(0, 1)[0]);
// Once there are no more items, emit an event
// notifying that that is the case
if (!data.length) {
this.emit("done");
clearInterval(interval);
}
}, 1e3);
}
}
class MyReadable extends Readable {
constructor(dataEmitter) {
super();
this.dataEmitter = dataEmitter;
}
_read() {
this.dataEmitter.on("chunk", (data) => {
this.push(data);
});
this.dataEmitter.once("done", () => {
this.push(null);
});
}
}
const dataEmitter = new DataEmitter();
const myReadable = new MyReadable(dataEmitter);
// Pipe the readable stream into a write stream
myReadable.pipe(createWriteStream(...));
The _read() method is called by the consumer of the stream when it is ready to receive more data. It is the responsibility of the _read() method to push data into the stream using the this.push() method. When the _read() method is called again after it has stopped pushing data, it should resume pushing data into the stream.
Hope this helps!
A:
Seems like the only purpose of actually implementing the read() method is to only start receiving the chunks and pushing them into the stream when the consumer is ready for that.
Based on these conclusions, I've come up with this solution.
class MyReadable extends Readable {
// Keep track of whether or not the listeners have already
// been added to the data emitter.
#registered = false;
_read() {
// If the listeners have already been registered, do
// absolutely nothing.
if (this.#registered) return;
// "Notify" the client via websockets that we're ready
// to start streaming the data chunks.
const emitter = new DataEmitter();
const handler = (chunk: string) => {
this.push(chunk);
};
emitter.on('chunk', handler);
emitter.once('done', () => {
this.push(null);
// Clean up the listener once it's done (this is
// assuming the #emitter object will still be used
// in the future).
emitter.off('chunk', handler);
});
// Mark the listeners as registered.
this.#registered = true;
}
}
const readable = new MyReadable();
readable.pipe(createWriteStream('./data.txt'));
But this implementation doesn't allow for the consumer to control when things are pushed. I guess, however, in order to achieve that sort of control, you'd need to communicate with the resource emitting the chunks to tell it to stop until the read() method is called again.
|
Creating a Readable stream from emitted data chunks
|
Short backstory: I am trying to create a Readable stream based on data chunks that are emitted back to my server from the client side with WebSockets. Here's a class I've created to "simulate" that behavior:
class DataEmitter extends EventEmitter {
constructor() {
super();
const data = ['foo', 'bar', 'baz', 'hello', 'world', 'abc', '123'];
// Every second, emit an event with a chunk of data
const interval = setInterval(() => {
this.emit('chunk', data.splice(0, 1)[0]);
// Once there are no more items, emit an event
// notifying that that is the case
if (!data.length) {
this.emit('done');
clearInterval(interval);
}
}, 1e3);
}
}
In this post, the dataEmitter in question will have been created like this.
// Our data is being emitted through events in chunks from some place.
// This is just to simulate that. We cannot change the flow - only listen
// for the events and do something with the chunks.
const dataEmitter = new DataEmitter();
Right, so I initially tried this:
const readable = new Readable();
dataEmitter.on('chunk', (data) => {
readable.push(data);
});
dataEmitter.once('done', () => {
readable.push(null);
});
But that results in this error:
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _read() method is not implemented
So I did this, implementing read() as an empty function:
const readable = new Readable({
read() {},
});
dataEmitter.on('chunk', (data) => {
readable.push(data);
});
dataEmitter.once('done', () => {
readable.push(null);
});
And it works when piping into a write stream, or sending the stream to my test API server. The resulting .txt file looks exactly as it should:
foobarbazhelloworldabc123
However, I feel like there's something quite wrong and hacky with my solution. I attempted to put the listener registration logic (.on('chunk', ...) and .once('done', ...)) within the read() implementation; however, read() seems to get called multiple times, and that results in the listeners being registered multiple times.
The Node.js documentation says this about the _read() method:
When readable._read() is called, if data is available from the resource, the implementation should begin pushing that data into the read queue using the this.push(dataChunk) method. _read() will be called again after each call to this.push(dataChunk) once the stream is ready to accept more data. _read() may continue reading from the resource and pushing data until readable.push() returns false. Only when _read() is called again after it has stopped should it resume pushing additional data into the queue.
After dissecting this, it seems that the consumer of the stream calls upon .read() when it's ready to read more data. And when it is called, data should be pushed into the stream. But, if it is not called, the stream should not have data pushed into it until the method is called again (???). So wait, does the consumer call .read() when it is ready for more data, or does it call it after each time .push() is called? Or both?? The docs seem to contradict themselves.
Implementing .read() on Readable is straightforward when you've got a basic resource to stream, but what would be the proper way of implementing it in this case?
And also, would someone be able to explain in better terms what the .read() method is on a deeper level, and how it should be implemented?
Thanks!
Response to the answer:
I did try registering the listeners within the read() implementation, but because it is called multiple times by the consumer, it registers the listeners multiple times.
Observing this code:
const readable = new Readable({
read() {
console.log('called');
dataEmitter.on('chunk', (data) => {
readable.push(data);
});
dataEmitter.once('done', () => {
readable.push(null);
});
},
});
readable.pipe(createWriteStream('./data.txt'));
The resulting file looks like this:
foobarbarbazbazbazhellohellohellohelloworldworldworldworldworldabcabcabcabcabcabc123123123123123123123
Which makes sense, because the listeners are being registered multiple times.
|
[
"In general, the _read() method of a Readable stream is used to implement the logic for how the stream should read data from its source. When a consumer of the stream calls the read() method, the _read() method will be called to provide data to the stream. This data will be pushed into the stream's buffer, where it can be read by the consumer.\nIn your specific case, you are using events to provide data to the stream, rather than a traditional data source like a file or network connection. In this case, you can still use the _read method to implement the logic for reading data from the events, but you will need to register event listeners within the _read() method to ensure that they are only registered once, rather than multiple times.\nHere is an example of how you might implement the _read() method in your DataEmitter stream:\nconst readable = new Readable({\n _read() {\n // Register event listeners for the 'chunk' and 'done' events\n dataEmitter.on('chunk', (data) => {\n readable.push(data);\n });\n dataEmitter.once('done', () => {\n readable.push(null);\n });\n },\n});\n\nIn this example, the _read() method is called whenever the stream's consumer calls the read() method. This ensures that the event listeners are only registered once, and that data from the 'chunk' events is pushed into the stream as it is received.\nAs for the deeper meaning of the read() method on a Readable stream, this method is used by the consumer of the stream to request data from the stream. When the consumer calls read(), the _read() method is called to provide data to the stream, which is then pushed into the stream's buffer. The consumer can then access this data by reading from the stream. This allows the consumer to control the flow of data from the stream, and ensure that it only receives data when it is ready to process it.\nUpdate:\nIn your code, you are creating a readable stream using the Readable class, but you are not implementing the _read() method. This is why you are seeing the error Error [ERR_METHOD_NOT_IMPLEMENTED]: The _read() method is not implemented.\nTo fix this error, you can implement the _read() method in your Readable class. The _read() method should be responsible for pushing data into the stream when the consumer is ready to receive it. In your case, you can register listeners for the 'chunk' and 'done' events on the dataEmitter within the _read() method. When the 'chunk' event is emitted, you can push the data into the stream using the this.push() method. When the 'done' event is emitted, you can call this.push(null) to signal the end of the stream.\nHere is an example of how you can implement the _read() method in your Readable class:\nclass DataEmitter extends EventEmitter {\n constructor() {\n super();\n\n const data = [\"foo\", \"bar\", \"baz\", \"hello\", \"world\", \"abc\", \"123\"];\n // Every second, emit an event with a chunk of data\n const interval = setInterval(() => {\n this.emit(\"chunk\", data.splice(0, 1)[0]);\n\n // Once there are no more items, emit an event\n // notifying that that is the case\n if (!data.length) {\n this.emit(\"done\");\n clearInterval(interval);\n }\n }, 1e3);\n }\n}\n\nclass MyReadable extends Readable {\n constructor(dataEmitter) {\n super();\n this.dataEmitter = dataEmitter;\n }\n\n _read() {\n this.dataEmitter.on(\"chunk\", (data) => {\n this.push(data);\n });\n\n this.dataEmitter.once(\"done\", () => {\n this.push(null);\n });\n }\n}\n\nconst dataEmitter = new DataEmitter();\nconst myReadable = new MyReadable(dataEmitter);\n\n// Pipe the readable stream into a write stream\nmyReadable.pipe(createWriteStream(...));\n\nThe _read() method is called by the consumer of the stream when it is ready to receive more data. It is the responsibility of the _read() method to push data into the stream using the this.push() method. When the _read() method is called again after it has stopped pushing data, it should resume pushing data into the stream.\nHope this helps!\n",
"Seems like the only purpose of actually implementing the read() method is to only start receiving the chunks and pushing them into the stream when the consumer is ready for that.\nBased on these conclusions, I've come up with this solution.\nclass MyReadable extends Readable {\n // Keep track of whether or not the listeners have already\n // been added to the data emitter.\n #registered = false;\n\n _read() {\n // If the listeners have already been registered, do\n // absolutely nothing.\n if (this.#registered) return;\n\n // \"Notify\" the client via websockets that we're ready\n // to start streaming the data chunks.\n const emitter = new DataEmitter();\n\n const handler = (chunk: string) => {\n this.push(chunk);\n };\n\n emitter.on('chunk', handler);\n\n emitter.once('done', () => {\n this.push(null);\n // Clean up the listener once it's done (this is\n // assuming the #emitter object will still be used\n // in the future).\n emitter.off('chunk', handler);\n });\n\n // Mark the listeners as registered.\n this.#registered = true;\n }\n}\n\nconst readable = new MyReadable();\n\nreadable.pipe(createWriteStream('./data.txt'));\n\nBut this implementation doesn't allow for the consumer to control when things are pushed. I guess, however, in order to achieve that sort of control, you'd need to communicate with the resource emitting the chunks to tell it to stop until the read() method is called again.\n"
] |
[
1,
0
] |
[] |
[] |
[
"javascript",
"node.js",
"nodejs_stream",
"typescript"
] |
stackoverflow_0074670330_javascript_node.js_nodejs_stream_typescript.txt
|
Q:
GetValues SetValues Basic Syntax Question
I want eliminate formula information that is in an array of cells. My idea was to get the values of the cells as an array and then set the values back into the same place. I can't get it to work and have a feeling it due to my syntax. Any suggestions?
function getset() {
var ss = SpreadsheetApp.getActive();
var lr = sh.getLastRow();
var places = ss.getRange(2,11, lr-1).getValues();
ss.getRange(2,11, lr-1).setValues(places);
}
A:
This works for me
function getset() {
var ss = SpreadsheetApp.getActive();
const sh = ss.getActiveSheet();
var lr = sh.getLastRow();
var places = sh.getRange(2,11, lr-1).getValues();
sh.getRange(2,11, lr-1).setValues(places);
}
|
GetValues SetValues Basic Syntax Question
|
I want eliminate formula information that is in an array of cells. My idea was to get the values of the cells as an array and then set the values back into the same place. I can't get it to work and have a feeling it due to my syntax. Any suggestions?
function getset() {
var ss = SpreadsheetApp.getActive();
var lr = sh.getLastRow();
var places = ss.getRange(2,11, lr-1).getValues();
ss.getRange(2,11, lr-1).setValues(places);
}
|
[
"This works for me\nfunction getset() {\n var ss = SpreadsheetApp.getActive();\n const sh = ss.getActiveSheet();\n var lr = sh.getLastRow();\n var places = sh.getRange(2,11, lr-1).getValues();\n sh.getRange(2,11, lr-1).setValues(places);\n }\n\n"
] |
[
0
] |
[] |
[] |
[
"google_apps_script",
"google_sheets",
"google_sheets_api"
] |
stackoverflow_0074670622_google_apps_script_google_sheets_google_sheets_api.txt
|
Q:
I can't do queries with 3 tables in Sequelize (include doesn't work well)
First, sorry for my bad english. I have a Final Paper to do, but I have some problems to fix it. Always I do a query with 3 tables, some table return null. There is two problems I have:
The table Professor sometimes returns null
The table Aula always have the same id of Professor, so some Aulas can't show the Professor who are related.
Controller Code
static async buscarAulasPorEscola(req, res) {
try {
const todasAulas = await database.Escola.findAll({
include: {
model: database.Aula,
include: {
model: database.Professor
}
}
})
return res.status(200).json(todasAulas)
} catch(error) {
return res.status(500).json(error.message)
}
}
Here are some queries realiazed with the controller above:
Query-Part1
Query-Part2
Migrations and Models
https://ibb.co/album/k4rNgS
I try to realize there controller and show all includes, and fix this problem.
A:
You indicated fkprofessor in Professor.hasMany(Aula and at the same time you indicated id in Aula.belongsTo(Professor.
You either need to indicate id or fkprofessor in both of them in order to make them work properly and in the same way.
|
I can't do queries with 3 tables in Sequelize (include doesn't work well)
|
First, sorry for my bad english. I have a Final Paper to do, but I have some problems to fix it. Always I do a query with 3 tables, some table return null. There is two problems I have:
The table Professor sometimes returns null
The table Aula always have the same id of Professor, so some Aulas can't show the Professor who are related.
Controller Code
static async buscarAulasPorEscola(req, res) {
try {
const todasAulas = await database.Escola.findAll({
include: {
model: database.Aula,
include: {
model: database.Professor
}
}
})
return res.status(200).json(todasAulas)
} catch(error) {
return res.status(500).json(error.message)
}
}
Here are some queries realiazed with the controller above:
Query-Part1
Query-Part2
Migrations and Models
https://ibb.co/album/k4rNgS
I try to realize there controller and show all includes, and fix this problem.
|
[
"You indicated fkprofessor in Professor.hasMany(Aula and at the same time you indicated id in Aula.belongsTo(Professor.\nYou either need to indicate id or fkprofessor in both of them in order to make them work properly and in the same way.\n"
] |
[
0
] |
[] |
[] |
[
"express",
"javascript",
"node.js",
"sequelize.js"
] |
stackoverflow_0074667604_express_javascript_node.js_sequelize.js.txt
|
Q:
Switch storybook background through global parameter
I have the following globalTypes to enable a toolbar in storybook that lets me select the theme:
export const globalTypes = {
theme: {
name: 'Theme',
description: 'Global theme',
defaultValue: MyTheme.Light,
toolbar: {
icon: 'mirror',
items: [MyTheme.Light, MyTheme.Dark],
showName: true,
dynamicTitle: true,
},
},
};
This works fine and I can switch the theme through the toolbar:
Now I want to set the background color of the story (background-color of the body) according to the theme, but I cannot figure out how to do that for all stories globally.
I know how to configure different background colors, but I have no idea how to switch them based on the theme set in context.globals. How does this work?
A:
You can use decorators to set global view and se
Like here
import { useEffect } from "react";
import "./preview.css";
enum MyTheme {
Light = "light",
Dark = "dark",
Tomato = "tomato"
}
export const globalTypes = {
theme: {
name: "Theme",
description: "Global theme",
defaultValue: MyTheme.Light,
toolbar: {
icon: "mirror",
items: [
{
title: "light",
value: MyTheme.Light
},
{ title: "dark", value: MyTheme.Dark },
{ title: "tomato", value: MyTheme.Tomato }
],
showName: true,
dynamicTitle: true
}
}
};
const clearStyles = (element: HTMLElement) => {
for (const className of Object.values(MyTheme)) {
element.classList.remove(className);
}
};
const applyStyle = (element: HTMLElement, className: string) => {
element.classList.add(className);
};
const WithThemeProvider = (Story, context) => {
useEffect(() => {
const body = window.document.body;
clearStyles(body);
applyStyle(body, context.globals.theme);
return () => {
clearStyles(body);
};
}, [context.globals.theme]);
return <Story />;
};
export const decorators = [WithThemeProvider];
I know it might feel "dirty" to work directly with body. But it is suggested way for instance addons decorator.
A:
To set the background color of your story based on the theme selected in the toolbar, you can use the GlobalStyle component provided by @storybook/theming to set the body element's background-color CSS property.
First, you will need to import the GlobalStyle component and the useStorybookState hook from @storybook/theming, like this:
import { GlobalStyle, useStorybookState } from '@storybook/theming';
Next, you can use the useStorybookState hook to retrieve the current theme value from the global state, and then use the GlobalStyle component to set the background-color of the body element based on the selected theme.
Here is an example of how you can do this:
// Use the useStorybookState hook to retrieve the current theme from the global state
const { theme } = useStorybookState();
// Use the GlobalStyle component to set the background-color of the body element
return (
<>
<GlobalStyle background={theme === MyTheme.Light ? 'white' : 'black'} />
{/* Other components and elements in your story */}
</>
);
With this change, the background color of your story will be set to white when the MyTheme.Light theme is selected in the toolbar, and to black when the MyTheme.Dark theme is selected.
I hope this helps! Let me know if you have any other questions.
|
Switch storybook background through global parameter
|
I have the following globalTypes to enable a toolbar in storybook that lets me select the theme:
export const globalTypes = {
theme: {
name: 'Theme',
description: 'Global theme',
defaultValue: MyTheme.Light,
toolbar: {
icon: 'mirror',
items: [MyTheme.Light, MyTheme.Dark],
showName: true,
dynamicTitle: true,
},
},
};
This works fine and I can switch the theme through the toolbar:
Now I want to set the background color of the story (background-color of the body) according to the theme, but I cannot figure out how to do that for all stories globally.
I know how to configure different background colors, but I have no idea how to switch them based on the theme set in context.globals. How does this work?
|
[
"You can use decorators to set global view and se\nLike here\nimport { useEffect } from \"react\";\nimport \"./preview.css\";\n\nenum MyTheme {\n Light = \"light\",\n Dark = \"dark\",\n Tomato = \"tomato\"\n}\n\nexport const globalTypes = {\n theme: {\n name: \"Theme\",\n description: \"Global theme\",\n defaultValue: MyTheme.Light,\n toolbar: {\n icon: \"mirror\",\n items: [\n {\n title: \"light\",\n value: MyTheme.Light\n },\n { title: \"dark\", value: MyTheme.Dark },\n { title: \"tomato\", value: MyTheme.Tomato }\n ],\n showName: true,\n dynamicTitle: true\n }\n }\n};\n\nconst clearStyles = (element: HTMLElement) => {\n for (const className of Object.values(MyTheme)) {\n element.classList.remove(className);\n }\n};\n\nconst applyStyle = (element: HTMLElement, className: string) => {\n element.classList.add(className);\n};\n\nconst WithThemeProvider = (Story, context) => {\n useEffect(() => {\n const body = window.document.body;\n clearStyles(body);\n applyStyle(body, context.globals.theme);\n return () => {\n clearStyles(body);\n };\n }, [context.globals.theme]);\n\n return <Story />;\n};\nexport const decorators = [WithThemeProvider];\n\nI know it might feel \"dirty\" to work directly with body. But it is suggested way for instance addons decorator.\n",
"To set the background color of your story based on the theme selected in the toolbar, you can use the GlobalStyle component provided by @storybook/theming to set the body element's background-color CSS property.\nFirst, you will need to import the GlobalStyle component and the useStorybookState hook from @storybook/theming, like this:\nimport { GlobalStyle, useStorybookState } from '@storybook/theming';\n\nNext, you can use the useStorybookState hook to retrieve the current theme value from the global state, and then use the GlobalStyle component to set the background-color of the body element based on the selected theme.\nHere is an example of how you can do this:\n// Use the useStorybookState hook to retrieve the current theme from the global state\nconst { theme } = useStorybookState();\n\n// Use the GlobalStyle component to set the background-color of the body element\nreturn (\n <>\n <GlobalStyle background={theme === MyTheme.Light ? 'white' : 'black'} />\n {/* Other components and elements in your story */}\n </>\n);\n\nWith this change, the background color of your story will be set to white when the MyTheme.Light theme is selected in the toolbar, and to black when the MyTheme.Dark theme is selected.\nI hope this helps! Let me know if you have any other questions.\n"
] |
[
0,
0
] |
[] |
[] |
[
"reactjs",
"storybook"
] |
stackoverflow_0074577147_reactjs_storybook.txt
|
Q:
append new observables to array of observables?
I am trying to avoid the following:
switchMap(([action, state]) =>
from(TodosDB.getAll()).pipe(
map(
(todos) => onQueryTodoDone({ items: todos }),
catchError((err) => of(onQueryTodoFail({ error: err })))
)
)
),
to something more linear like like we do with combineLatestFrom in ngrx.
So far I tried to do the below. But the promise does not seem to work.
withLatestFrom(
from(TodosDB.getAll())
),
and
withLatestFrom(
from(TodosDB.getAll()).pipe(
map((todos) => onQueryTodoDone({ items: todos }))
)
)
Any ideas how to deal with this scenario without nesting pipe map in a switchMap?
PS: this might be obvious to you but I don't know much and I looked up on the internet and found withLatestFrom but not sure what I am missing.
EDIT: this is the best I got so far:
switchMap(([action, state]) =>
forkJoin([of(action), of(state), TodosDB.getAll()])
),
map(
([action, state, todos]) => onQueryTodoDone({ items: todos }),
catchError((err) => of(onQueryTodoFail({ error: err })))
),
The above is better but I have no idea if that can cause issues later. But hopefully I was able to communicate the idea. Which is append a promise result to the piped observable keep it's original structure
[Observable<Actions>,Observable<State>,Observable<FromPromise>]
A:
Joining a few dots here and taking a bit of a guess I would say the problem stems from TodosDB.getAll returning a Promise.
With a promise based function you want to lazily evaluate it, as such a function is executed immediately when it is called, unlike an observable based function which requires a subscription.
This is why the switchMap based solutions work, because the body of the switchMap is not evaluated until the source emits.
In your shortened version using withLatestFrom, there is no lazy evaluation, the getAll call is probably evaluated once and once only when the effect is set up.
You can use the defer operator to convert your promise based function to one that behaves more appropriately with the rxjs observable based operators.
withLatestFrom(defer(() => this.getAll())), // use of defer
map(([[action, state], todos]) => [action, state, todos]), // refine the shape of the data to your requirements
...
Stackblitz: https://stackblitz.com/edit/angular-ivy-qkwqyw?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html
Note: The concatLatestFrom ngrx operator also looks like it may be of use but I couldn't get it to work how I wanted.
|
append new observables to array of observables?
|
I am trying to avoid the following:
switchMap(([action, state]) =>
from(TodosDB.getAll()).pipe(
map(
(todos) => onQueryTodoDone({ items: todos }),
catchError((err) => of(onQueryTodoFail({ error: err })))
)
)
),
to something more linear like like we do with combineLatestFrom in ngrx.
So far I tried to do the below. But the promise does not seem to work.
withLatestFrom(
from(TodosDB.getAll())
),
and
withLatestFrom(
from(TodosDB.getAll()).pipe(
map((todos) => onQueryTodoDone({ items: todos }))
)
)
Any ideas how to deal with this scenario without nesting pipe map in a switchMap?
PS: this might be obvious to you but I don't know much and I looked up on the internet and found withLatestFrom but not sure what I am missing.
EDIT: this is the best I got so far:
switchMap(([action, state]) =>
forkJoin([of(action), of(state), TodosDB.getAll()])
),
map(
([action, state, todos]) => onQueryTodoDone({ items: todos }),
catchError((err) => of(onQueryTodoFail({ error: err })))
),
The above is better but I have no idea if that can cause issues later. But hopefully I was able to communicate the idea. Which is append a promise result to the piped observable keep it's original structure
[Observable<Actions>,Observable<State>,Observable<FromPromise>]
|
[
"Joining a few dots here and taking a bit of a guess I would say the problem stems from TodosDB.getAll returning a Promise.\nWith a promise based function you want to lazily evaluate it, as such a function is executed immediately when it is called, unlike an observable based function which requires a subscription.\nThis is why the switchMap based solutions work, because the body of the switchMap is not evaluated until the source emits.\nIn your shortened version using withLatestFrom, there is no lazy evaluation, the getAll call is probably evaluated once and once only when the effect is set up.\nYou can use the defer operator to convert your promise based function to one that behaves more appropriately with the rxjs observable based operators.\nwithLatestFrom(defer(() => this.getAll())), // use of defer\nmap(([[action, state], todos]) => [action, state, todos]), // refine the shape of the data to your requirements\n...\n\n\nStackblitz: https://stackblitz.com/edit/angular-ivy-qkwqyw?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html\nNote: The concatLatestFrom ngrx operator also looks like it may be of use but I couldn't get it to work how I wanted.\n"
] |
[
0
] |
[] |
[] |
[
"javascript",
"rxjs"
] |
stackoverflow_0074661098_javascript_rxjs.txt
|
Q:
Is there a way to extract the variables from `lmfit` report?
I'm using the python package lmfit to fit my dataset with this model:
def GaussianFit(results, highest_num, Peak_shot, nuni, dif = None):
...
Gauss_mod = GaussianModel(prefix='gauss_')
Const_mod = ConstantModel(prefix='const_')
mod = Gauss_mod + Const_mod
pars = mod.make_params(gauss_center = ig, gauss_sigma = 1/12)
out = mod.fit(y_sel, pars, x = x_sel, weights = get_weights(last_sel,Peak_shot,nuni))
print(out.fit_report())
And the fit report looks like:
[[Model]]
(Model(gaussian, prefix='gauss_') + Model(constant, prefix='const_'))
[[Fit Statistics]]
# fitting method = leastsq
# function evals = 101
# data points = 18
# variables = 4
chi-square = 2.1571e-05
reduced chi-square = 1.5408e-06
Akaike info crit = -237.421693
Bayesian info crit = -233.860206
[[Variables]]
gauss_amplitude: 0.02133733 +/- 0.01122602 (52.61%) (init = 0.25)
gauss_center: 0.98316682 +/- 0.02152806 (2.19%) (init = 1.041587)
gauss_sigma: 0.11847360 +/- 0.04182091 (35.30%) (init = 0.08333333)
const_c: 0.09532047 +/- 0.01831759 (19.22%) (init = 0)
gauss_fwhm: 0.27898399 +/- 0.09848070 (35.30%) == '2.3548200*gauss_sigma'
I was wondering if it is possible to extract the gauss_center and its error with two variables, instead of directly copying and pasting these results. Thanks!
A:
Yes, it is possible to extract the gauss_center and its error from the fit results. The lmfit package provides several methods for accessing the fit results, including params, best_values, and best_fit.
To extract the gauss_center and its error, you can use the params method of the fit result object, which returns a Parameters object containing the fit results. This object has an attribute for each fitted parameter, and you can access the value and error of the gauss_center parameter using the .value and .stderr attributes, respectively.
Here is an example of how you could extract these values:
out = mod.fit(y_sel, pars, x = x_sel, weights = get_weights(last_sel,Peak_shot,nuni))
# Extract the value and error of the gauss_center parameter
gauss_center = out.params['gauss_center'].value
gauss_center_error = out.params['gauss_center'].stderr
print(f'gauss_center = {gauss_center:.6f} +/- {gauss_center_error:.6f}')
Alternatively, you can use the best_values method of the fit result object, which returns a dictionary-like object containing the best-fit values of the parameters. The best_fit method returns an array containing the best-fit model evaluated at the independent variable values used in the fit.
Here is an example of how you could use these methods:
out = mod.fit(y_sel, pars, x = x_sel, weights = get_weights(last_sel,Peak_shot,nuni))
# Extract the best-fit value of the gauss_center parameter
gauss_center = out.best_values['gauss_center']
# Evaluate the best-fit model at the independent variable values used in the fit
best_fit = out.best_fit
print(f'gauss_center = {gauss_center:.6f}')
I hope this helps!
|
Is there a way to extract the variables from `lmfit` report?
|
I'm using the python package lmfit to fit my dataset with this model:
def GaussianFit(results, highest_num, Peak_shot, nuni, dif = None):
...
Gauss_mod = GaussianModel(prefix='gauss_')
Const_mod = ConstantModel(prefix='const_')
mod = Gauss_mod + Const_mod
pars = mod.make_params(gauss_center = ig, gauss_sigma = 1/12)
out = mod.fit(y_sel, pars, x = x_sel, weights = get_weights(last_sel,Peak_shot,nuni))
print(out.fit_report())
And the fit report looks like:
[[Model]]
(Model(gaussian, prefix='gauss_') + Model(constant, prefix='const_'))
[[Fit Statistics]]
# fitting method = leastsq
# function evals = 101
# data points = 18
# variables = 4
chi-square = 2.1571e-05
reduced chi-square = 1.5408e-06
Akaike info crit = -237.421693
Bayesian info crit = -233.860206
[[Variables]]
gauss_amplitude: 0.02133733 +/- 0.01122602 (52.61%) (init = 0.25)
gauss_center: 0.98316682 +/- 0.02152806 (2.19%) (init = 1.041587)
gauss_sigma: 0.11847360 +/- 0.04182091 (35.30%) (init = 0.08333333)
const_c: 0.09532047 +/- 0.01831759 (19.22%) (init = 0)
gauss_fwhm: 0.27898399 +/- 0.09848070 (35.30%) == '2.3548200*gauss_sigma'
I was wondering if it is possible to extract the gauss_center and its error with two variables, instead of directly copying and pasting these results. Thanks!
|
[
"Yes, it is possible to extract the gauss_center and its error from the fit results. The lmfit package provides several methods for accessing the fit results, including params, best_values, and best_fit.\nTo extract the gauss_center and its error, you can use the params method of the fit result object, which returns a Parameters object containing the fit results. This object has an attribute for each fitted parameter, and you can access the value and error of the gauss_center parameter using the .value and .stderr attributes, respectively.\nHere is an example of how you could extract these values:\nout = mod.fit(y_sel, pars, x = x_sel, weights = get_weights(last_sel,Peak_shot,nuni))\n\n# Extract the value and error of the gauss_center parameter\ngauss_center = out.params['gauss_center'].value\ngauss_center_error = out.params['gauss_center'].stderr\n\nprint(f'gauss_center = {gauss_center:.6f} +/- {gauss_center_error:.6f}')\n\nAlternatively, you can use the best_values method of the fit result object, which returns a dictionary-like object containing the best-fit values of the parameters. The best_fit method returns an array containing the best-fit model evaluated at the independent variable values used in the fit.\nHere is an example of how you could use these methods:\nout = mod.fit(y_sel, pars, x = x_sel, weights = get_weights(last_sel,Peak_shot,nuni))\n\n# Extract the best-fit value of the gauss_center parameter\ngauss_center = out.best_values['gauss_center']\n\n# Evaluate the best-fit model at the independent variable values used in the fit\nbest_fit = out.best_fit\n\nprint(f'gauss_center = {gauss_center:.6f}')\n\nI hope this helps!\n"
] |
[
2
] |
[] |
[] |
[
"lmfit"
] |
stackoverflow_0074670696_lmfit.txt
|
Q:
Remove .html extension in url
Today I tried to remove html file extension from my website, for example:
example.com/page.html to example.com/page
I watched some tutorials, but nothing seems to work...
I created .htaccess file in root directory
Copied code (also tried different ones):
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html [NC,L]
It didn't work when I opened my website as file, with Live Server (VS Code extension) or actual website (hosted on Replit)
Any idea, why it doesn't work? Any help appreciated...
See whole repository
Edit: Someone said, I have to remove .html file extension. I get error that the file is not found
A:
Yo should do it in this way:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC, L]
A:
SOLVED
As someone said, .htaccess file doesn't work on Replit. I've done following:
Made folder for every .html file
Moved that file inside of the folder I made
Renamed the file to index.html
|
Remove .html extension in url
|
Today I tried to remove html file extension from my website, for example:
example.com/page.html to example.com/page
I watched some tutorials, but nothing seems to work...
I created .htaccess file in root directory
Copied code (also tried different ones):
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html [NC,L]
It didn't work when I opened my website as file, with Live Server (VS Code extension) or actual website (hosted on Replit)
Any idea, why it doesn't work? Any help appreciated...
See whole repository
Edit: Someone said, I have to remove .html file extension. I get error that the file is not found
|
[
"Yo should do it in this way:\nRewriteEngine on\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteRule ^([^\\.]+)$ $1.html [NC, L]\n\n",
"SOLVED\nAs someone said, .htaccess file doesn't work on Replit. I've done following:\n\nMade folder for every .html file\nMoved that file inside of the folder I made\nRenamed the file to index.html\n\n"
] |
[
1,
0
] |
[] |
[] |
[
".htaccess",
"html",
"web"
] |
stackoverflow_0074551623_.htaccess_html_web.txt
|
Q:
Spring Cloud PubSub as not shutdown properly error
I'm trying to implement Spring Cloud Pub/Sub, I followed the guide but how to take the exception low, this makes it start to consume a high level of processing, I researched a lot and they say to put the parameter awaitTerminated, but I couldn't find how to define this parameter.
Versions:
<spring-cloud-gcp.version>2.0.4</spring-cloud-gcp.version>
<spring-cloud.version>2020.0.4</spring-cloud.version>
Beans
@Bean
public DefaultPublisherFactory defaultPublisherFactory(GcpProjectIdProvider gcpProjectIdProvider) {
DefaultPublisherFactory factory = new DefaultPublisherFactory(gcpProjectIdProvider);
factory.setEnableMessageOrdering(true);
factory.setEndpoint("us-east1-pubsub.googleapis.com:443");
return factory;
}
@Bean
@ServiceActivator(inputChannel = "pubSubOutputChannel")
public MessageHandler messageSender(PubSubTemplate pubsubTemplate) {
PubSubMessageHandler adapter = new PubSubMessageHandler(pubsubTemplate, "noMatter");
adapter.setFailureCallback((cause, message) ->
System.err.println("Fail to send message " + message)
);
return adapter;
}
@MessagingGateway(defaultRequestChannel = "pubSubOutputChannel")
public interface PubSubOutboundGateway {
void sendToPubSub(@Header(GcpPubSubHeaders.TOPIC) String topic, String payload);
}
Exception
2021-12-22 10:01:08.246 ERROR 60276 --- [LoopGroup-80-34] i.g.i.ManagedChannelOrphanWrapper : *~*~*~ Channel ManagedChannelImpl{logId=869, target=us-east1-pubsub.googleapis.com:443} was not shutdown properly!!! ~*~*~*
Make sure to call shutdown()/shutdownNow() and wait until awaitTermination() returns true.
java.lang.RuntimeException: ManagedChannel allocation site
at io.grpc.internal.ManagedChannelOrphanWrapper$ManagedChannelReference.<init>(ManagedChannelOrphanWrapper.java:93) ~[grpc-core-1.39.0.jar:1.39.0]
at io.grpc.internal.ManagedChannelOrphanWrapper.<init>(ManagedChannelOrphanWrapper.java:53) ~[grpc-core-1.39.0.jar:1.39.0]
at io.grpc.internal.ManagedChannelOrphanWrapper.<init>(ManagedChannelOrphanWrapper.java:44) ~[grpc-core-1.39.0.jar:1.39.0]
at io.grpc.internal.ManagedChannelImplBuilder.build(ManagedChannelImplBuilder.java:634) ~[grpc-core-1.39.0.jar:1.39.0]
at io.grpc.internal.AbstractManagedChannelImplBuilder.build(AbstractManagedChannelImplBuilder.java:264) ~[grpc-core-1.39.0.jar:1.39.0]
at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.createSingleChannel(InstantiatingGrpcChannelProvider.java:360) ~[gax-grpc-1.66.0.jar:1.66.0]
at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.access$1800(InstantiatingGrpcChannelProvider.java:81) ~[gax-grpc-1.66.0.jar:1.66.0]
at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider$1.createSingleChannel(InstantiatingGrpcChannelProvider.java:231) ~[gax-grpc-1.66.0.jar:1.66.0]
at com.google.api.gax.grpc.ChannelPool.create(ChannelPool.java:72) ~[gax-grpc-1.66.0.jar:1.66.0]
at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.createChannel(InstantiatingGrpcChannelProvider.java:241) ~[gax-grpc-1.66.0.jar:1.66.0]
at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.getTransportChannel(InstantiatingGrpcChannelProvider.java:219) ~[gax-grpc-1.66.0.jar:1.66.0]
at com.google.api.gax.rpc.ClientContext.create(ClientContext.java:199) ~[gax-1.66.0.jar:1.66.0]
at com.google.cloud.pubsub.v1.stub.GrpcPublisherStub.create(GrpcPublisherStub.java:195) ~[google-cloud-pubsub-1.113.5.jar:1.113.5]
at com.google.cloud.pubsub.v1.Publisher.<init>(Publisher.java:188) ~[google-cloud-pubsub-1.113.5.jar:1.113.5]
at com.google.cloud.pubsub.v1.Publisher.<init>(Publisher.java:88) ~[google-cloud-pubsub-1.113.5.jar:1.113.5]
at com.google.cloud.pubsub.v1.Publisher$Builder.build(Publisher.java:829) ~[google-cloud-pubsub-1.113.5.jar:1.113.5]
A:
I solved the problem making it as simple as possible, I ended up deleting the Bean
DefaultPublisherFactory and solved the problem.
A:
I was getting this error because I wasn't shutting down SubscriptionAdminClient. I solved by using the object in a try-with-resources block:
try (SubscriptionAdminClient subscriptionAdminClient = createSubscriptionAdminClient()) {
subscriptionAdminClient.createSubscription(...);
...
} catch (IOException e) {
throw new RuntimeException("Failure...", e);
}
|
Spring Cloud PubSub as not shutdown properly error
|
I'm trying to implement Spring Cloud Pub/Sub, I followed the guide but how to take the exception low, this makes it start to consume a high level of processing, I researched a lot and they say to put the parameter awaitTerminated, but I couldn't find how to define this parameter.
Versions:
<spring-cloud-gcp.version>2.0.4</spring-cloud-gcp.version>
<spring-cloud.version>2020.0.4</spring-cloud.version>
Beans
@Bean
public DefaultPublisherFactory defaultPublisherFactory(GcpProjectIdProvider gcpProjectIdProvider) {
DefaultPublisherFactory factory = new DefaultPublisherFactory(gcpProjectIdProvider);
factory.setEnableMessageOrdering(true);
factory.setEndpoint("us-east1-pubsub.googleapis.com:443");
return factory;
}
@Bean
@ServiceActivator(inputChannel = "pubSubOutputChannel")
public MessageHandler messageSender(PubSubTemplate pubsubTemplate) {
PubSubMessageHandler adapter = new PubSubMessageHandler(pubsubTemplate, "noMatter");
adapter.setFailureCallback((cause, message) ->
System.err.println("Fail to send message " + message)
);
return adapter;
}
@MessagingGateway(defaultRequestChannel = "pubSubOutputChannel")
public interface PubSubOutboundGateway {
void sendToPubSub(@Header(GcpPubSubHeaders.TOPIC) String topic, String payload);
}
Exception
2021-12-22 10:01:08.246 ERROR 60276 --- [LoopGroup-80-34] i.g.i.ManagedChannelOrphanWrapper : *~*~*~ Channel ManagedChannelImpl{logId=869, target=us-east1-pubsub.googleapis.com:443} was not shutdown properly!!! ~*~*~*
Make sure to call shutdown()/shutdownNow() and wait until awaitTermination() returns true.
java.lang.RuntimeException: ManagedChannel allocation site
at io.grpc.internal.ManagedChannelOrphanWrapper$ManagedChannelReference.<init>(ManagedChannelOrphanWrapper.java:93) ~[grpc-core-1.39.0.jar:1.39.0]
at io.grpc.internal.ManagedChannelOrphanWrapper.<init>(ManagedChannelOrphanWrapper.java:53) ~[grpc-core-1.39.0.jar:1.39.0]
at io.grpc.internal.ManagedChannelOrphanWrapper.<init>(ManagedChannelOrphanWrapper.java:44) ~[grpc-core-1.39.0.jar:1.39.0]
at io.grpc.internal.ManagedChannelImplBuilder.build(ManagedChannelImplBuilder.java:634) ~[grpc-core-1.39.0.jar:1.39.0]
at io.grpc.internal.AbstractManagedChannelImplBuilder.build(AbstractManagedChannelImplBuilder.java:264) ~[grpc-core-1.39.0.jar:1.39.0]
at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.createSingleChannel(InstantiatingGrpcChannelProvider.java:360) ~[gax-grpc-1.66.0.jar:1.66.0]
at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.access$1800(InstantiatingGrpcChannelProvider.java:81) ~[gax-grpc-1.66.0.jar:1.66.0]
at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider$1.createSingleChannel(InstantiatingGrpcChannelProvider.java:231) ~[gax-grpc-1.66.0.jar:1.66.0]
at com.google.api.gax.grpc.ChannelPool.create(ChannelPool.java:72) ~[gax-grpc-1.66.0.jar:1.66.0]
at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.createChannel(InstantiatingGrpcChannelProvider.java:241) ~[gax-grpc-1.66.0.jar:1.66.0]
at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.getTransportChannel(InstantiatingGrpcChannelProvider.java:219) ~[gax-grpc-1.66.0.jar:1.66.0]
at com.google.api.gax.rpc.ClientContext.create(ClientContext.java:199) ~[gax-1.66.0.jar:1.66.0]
at com.google.cloud.pubsub.v1.stub.GrpcPublisherStub.create(GrpcPublisherStub.java:195) ~[google-cloud-pubsub-1.113.5.jar:1.113.5]
at com.google.cloud.pubsub.v1.Publisher.<init>(Publisher.java:188) ~[google-cloud-pubsub-1.113.5.jar:1.113.5]
at com.google.cloud.pubsub.v1.Publisher.<init>(Publisher.java:88) ~[google-cloud-pubsub-1.113.5.jar:1.113.5]
at com.google.cloud.pubsub.v1.Publisher$Builder.build(Publisher.java:829) ~[google-cloud-pubsub-1.113.5.jar:1.113.5]
|
[
"I solved the problem making it as simple as possible, I ended up deleting the Bean\nDefaultPublisherFactory and solved the problem.\n",
"I was getting this error because I wasn't shutting down SubscriptionAdminClient. I solved by using the object in a try-with-resources block:\ntry (SubscriptionAdminClient subscriptionAdminClient = createSubscriptionAdminClient()) {\n subscriptionAdminClient.createSubscription(...);\n ...\n} catch (IOException e) {\n throw new RuntimeException(\"Failure...\", e);\n}\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"google_cloud_pubsub",
"java",
"spring_cloud_gcp"
] |
stackoverflow_0070449568_google_cloud_pubsub_java_spring_cloud_gcp.txt
|
Q:
how to get color code on my code FOR EXAMPLE (Debug.Log) to be in a color?
s
I want someone to tell me how to put colors on the code so its easier for me to code.
A:
I think you forgot to select unity c# components when installing visual studio,
try again with visual code
A:
If you are talking about Intellisense / syntax highlighting, you need to make sure that you installed Visual Studio Tools for Unity (Note this is needed for Visual Studio only and you may already have it installed).
Then follow these steps:
Close Visual Studio
In Unity, go to Edit > Preferences > External Tools
Click on the External Script Editor dropdown (this should be on which ever Visual Studio editor you are using or any other supported editor).
Make sure Embedded packages and Local Packages is checked under Generate csproj files for:
Click on Regenerate project files
Open any C# script and check if syntax highlighting is working.
In the worst case, if that does not work, you can close Unity and delete everything except the Assets/ and Project Settings/ folders (as well as anything you explicitly added) in your project's root directory. Unity will regenerate the project folders and files again when you open the project in the editor. It may just be that some of your project files were corrupt.
Also, in case I misinterpreted your question and you are talking about coloring the output in the console window within the editor, you can try using rich text which I believe is supported by Unity's console window in the latest versions.
Example:
Debug.Log("<color=red>this is red text</color>");
For more info on that:
https://docs.unity3d.com/Packages/[email protected]/manual/StyledText.html
|
how to get color code on my code FOR EXAMPLE (Debug.Log) to be in a color?
|
s
I want someone to tell me how to put colors on the code so its easier for me to code.
|
[
"I think you forgot to select unity c# components when installing visual studio,\ntry again with visual code\n",
"If you are talking about Intellisense / syntax highlighting, you need to make sure that you installed Visual Studio Tools for Unity (Note this is needed for Visual Studio only and you may already have it installed).\nThen follow these steps:\n\nClose Visual Studio\nIn Unity, go to Edit > Preferences > External Tools\nClick on the External Script Editor dropdown (this should be on which ever Visual Studio editor you are using or any other supported editor).\nMake sure Embedded packages and Local Packages is checked under Generate csproj files for:\nClick on Regenerate project files\nOpen any C# script and check if syntax highlighting is working.\n\nIn the worst case, if that does not work, you can close Unity and delete everything except the Assets/ and Project Settings/ folders (as well as anything you explicitly added) in your project's root directory. Unity will regenerate the project folders and files again when you open the project in the editor. It may just be that some of your project files were corrupt.\nAlso, in case I misinterpreted your question and you are talking about coloring the output in the console window within the editor, you can try using rich text which I believe is supported by Unity's console window in the latest versions.\nExample:\nDebug.Log(\"<color=red>this is red text</color>\");\n\nFor more info on that:\nhttps://docs.unity3d.com/Packages/[email protected]/manual/StyledText.html\n"
] |
[
0,
0
] |
[] |
[] |
[
"unity3d",
"visual_studio"
] |
stackoverflow_0074670273_unity3d_visual_studio.txt
|
Q:
HackerRank Bon Appétit problem failing two test cases
This is regarding the HackerRank Bon Appétit problem. I have written code using BigDecimal in Java. All test cases except two are failing and I am not sure why. The problem statement is that two people Bill and Anna are at a restaurant. Bill orders stuff which anna might be allergic to. So, for example if the bill amount array is [6,2,4] and anna does not have/avoids bill[2], the bill should be split such as (6 + 2)/2 if bill did it correctly. If Bill did not split the bill correctly, anna should get a refund at the end. For example if bill calculated it as (6 + 2 + 4)/2 = 16 and anna should get a refund of 4. If anna is charged the same amount as was calculated, you print "Bon Appetit" or else you print the extra amount that Anna was charged.
What I have done?
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class BonAppetit {
// Complete the bonAppetit function below.
static void bonAppetit(List<Integer> billList, Integer avoidedItemIndex, Integer chargedToAnna) {
List<BigInteger> billListBigInteger = new ArrayList<>();
for(Integer bill : billList) {
billListBigInteger.add(BigInteger.valueOf(bill));
}
BigInteger avoidedItem = BigInteger.valueOf(billList.get(avoidedItemIndex));
BigInteger annasCharge = BigInteger.valueOf(chargedToAnna);
BigInteger sum = BigInteger.ZERO;
for(int i=0;i<billListBigInteger.size();i++) {
if(i != avoidedItemIndex) {
sum = sum.add(billListBigInteger.get(i));
}
}
//Since there are only two people
BigInteger split = sum.divide(BigInteger.valueOf(2));
if(split.equals(annasCharge)) {
System.out.println("Bon Appetit");
} else {
System.out.println(annasCharge.subtract(split).intValue());
}
}
public static void main(String[] args) throws IOException {
List<Integer> billList = new ArrayList<>();
File inputFile = new File("BonAppettitTestCase");
if(!inputFile.exists()) {
System.out.println("FIle not found, can't continue, exiting");
return;
}
String line;
BufferedReader fileBufferedReader = new BufferedReader(new FileReader(inputFile));
while((line = fileBufferedReader.readLine()) != null) {
String[] splitNumberString = line.split(",");
for(String number : splitNumberString) {
billList.add(Integer.valueOf(number));
}
}
bonAppetit(billList, 2814, 249990732);
}
}
The test case which fails has the following numbers as shown in the attached file in the list. It contains 100000 numbers which is why I am attaching another file with this detail so that if you create a project to parse out the numbers, it will be easy for you.
The first argument to the bonAppetit function is the billList. I have created a comma separated list comma separated list of numbers so that you can add them to a list and use the same. The second argument is the index which Anna avoids to eat. The third argument is the amount that anna was charged. Other test cases are passing, but this one is failing and I don't understand why. Maybe BigInteger is not really required here, but I still used it. Please point me in the right direction in solving this problem for all test cases. The correct answer to this problem is 4009 Thank you!
A:
I don't even know why you rushed to use BigInteger...
The problem is simple , count the sum then substract the unwanted food k, split it , if it equals to b then it's 'Bon Appetit' else he will refund her half the unwanted element k he overcharger her with.
something like this
static void bonAppetit(List<Integer> bill, int k, int b) {
int sum=0;
for(int i=0;i<bill.size();i++){
sum+=bill.get(i);
}
sum-=bill.get(k);
sum=sum/2;
if(sum==b){
System.out.println("Bon Appetit");
}else{
System.out.println(bill.get(k)/2);
}
}
A:
They have updated the problem on Hackerrank with more test cases that require you to use BigInt. Here's how I solved it:
function bonAppetit(bill, k, b) {
let sum = BigInt(0);
for (let i = 0; i < bill.length; ++i) {
sum += BigInt(bill[i]);
}
sum -= BigInt(bill[k]);
const anna = sum / BigInt(2);
console.log(BigInt(b) === anna ? "Bon Appetit" : Number((BigInt(b) - anna)));
}
|
HackerRank Bon Appétit problem failing two test cases
|
This is regarding the HackerRank Bon Appétit problem. I have written code using BigDecimal in Java. All test cases except two are failing and I am not sure why. The problem statement is that two people Bill and Anna are at a restaurant. Bill orders stuff which anna might be allergic to. So, for example if the bill amount array is [6,2,4] and anna does not have/avoids bill[2], the bill should be split such as (6 + 2)/2 if bill did it correctly. If Bill did not split the bill correctly, anna should get a refund at the end. For example if bill calculated it as (6 + 2 + 4)/2 = 16 and anna should get a refund of 4. If anna is charged the same amount as was calculated, you print "Bon Appetit" or else you print the extra amount that Anna was charged.
What I have done?
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class BonAppetit {
// Complete the bonAppetit function below.
static void bonAppetit(List<Integer> billList, Integer avoidedItemIndex, Integer chargedToAnna) {
List<BigInteger> billListBigInteger = new ArrayList<>();
for(Integer bill : billList) {
billListBigInteger.add(BigInteger.valueOf(bill));
}
BigInteger avoidedItem = BigInteger.valueOf(billList.get(avoidedItemIndex));
BigInteger annasCharge = BigInteger.valueOf(chargedToAnna);
BigInteger sum = BigInteger.ZERO;
for(int i=0;i<billListBigInteger.size();i++) {
if(i != avoidedItemIndex) {
sum = sum.add(billListBigInteger.get(i));
}
}
//Since there are only two people
BigInteger split = sum.divide(BigInteger.valueOf(2));
if(split.equals(annasCharge)) {
System.out.println("Bon Appetit");
} else {
System.out.println(annasCharge.subtract(split).intValue());
}
}
public static void main(String[] args) throws IOException {
List<Integer> billList = new ArrayList<>();
File inputFile = new File("BonAppettitTestCase");
if(!inputFile.exists()) {
System.out.println("FIle not found, can't continue, exiting");
return;
}
String line;
BufferedReader fileBufferedReader = new BufferedReader(new FileReader(inputFile));
while((line = fileBufferedReader.readLine()) != null) {
String[] splitNumberString = line.split(",");
for(String number : splitNumberString) {
billList.add(Integer.valueOf(number));
}
}
bonAppetit(billList, 2814, 249990732);
}
}
The test case which fails has the following numbers as shown in the attached file in the list. It contains 100000 numbers which is why I am attaching another file with this detail so that if you create a project to parse out the numbers, it will be easy for you.
The first argument to the bonAppetit function is the billList. I have created a comma separated list comma separated list of numbers so that you can add them to a list and use the same. The second argument is the index which Anna avoids to eat. The third argument is the amount that anna was charged. Other test cases are passing, but this one is failing and I don't understand why. Maybe BigInteger is not really required here, but I still used it. Please point me in the right direction in solving this problem for all test cases. The correct answer to this problem is 4009 Thank you!
|
[
"I don't even know why you rushed to use BigInteger...\nThe problem is simple , count the sum then substract the unwanted food k, split it , if it equals to b then it's 'Bon Appetit' else he will refund her half the unwanted element k he overcharger her with.\nsomething like this \n static void bonAppetit(List<Integer> bill, int k, int b) {\n int sum=0;\n for(int i=0;i<bill.size();i++){\n sum+=bill.get(i);\n }\n sum-=bill.get(k);\n sum=sum/2;\n\n if(sum==b){\n System.out.println(\"Bon Appetit\"); \n }else{\n System.out.println(bill.get(k)/2);\n }\n\n}\n\n",
"They have updated the problem on Hackerrank with more test cases that require you to use BigInt. Here's how I solved it:\nfunction bonAppetit(bill, k, b) {\n let sum = BigInt(0);\n\n for (let i = 0; i < bill.length; ++i) {\n sum += BigInt(bill[i]);\n }\n\n sum -= BigInt(bill[k]);\n const anna = sum / BigInt(2);\n\n console.log(BigInt(b) === anna ? \"Bon Appetit\" : Number((BigInt(b) - anna)));\n}\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"java"
] |
stackoverflow_0055203753_java.txt
|
Q:
Can I call a function in react return?
Is there a way I can call a function in the return section of React? kind of like how in JS I can just call a function by functionName() ?
WHAT EXACTLY AM I TRYING TO ACCOMPLISH?
What I am wanting to do in this bakery game is when the player hits $5, the "Purchase Easy Bake Oven" pops up and it will cost them $25 to purchase (At this time I do not necessarily care about the math mathing, I just care for functionality). Once the player decides to purchase, this section disappears and is replaced with "Easy bake Oven" With a button that says $5 where at this point, every time the button is clicked my total increases by 5.
WHAT HAVE I TRIED?
I feel like this should be done with an onClick event to switch from const [showEZBake, setShowEZBake] = useState(false) to useState(True). I currently have a Turnary (or whatever you call it), but I feel like this is incorrect because I need to change the state as stated before. I have also attempted to create an if statement inside of a function where I would add an h1 element, but that did not work. Even if it did, my main issue would still be there and that is how to call a function inside of a return.
SUMMARY:
I want the "Purchase Oven" text and $5 button to be replaced with Oven and $2 button AFTER the button was clicked.
import React, {useState, useEffect} from 'react'
const App = () => {
// ======================================
// HOOKS
// ======================================
const [score, setScore] = useState(0)
// ======================================
// FUNCTIONS
// ======================================
// EARN REVENUE FUNCTIONS
const earn1 = () => {
setScore(score + 1)
}
const earn5 = () => {
setScore(score + 5)
}
const reveal = () => {
// setShowEZBake(false)
if (score >= 5) {
return (
<h1>TEST</h1>
)
} else {
}
}
const upgrade = () => {
if (score >= 5) {
<><h3>Purchase Easy Bake Oven</h3> <button>$5</button></>
}
else {
}
}
const [showEZBake, setShowEZBake] = useState(false)
// ======================================
// DISPLAY
// ======================================
return (
<div>
<h1>Bakery</h1>
<h2>Revenue {score}</h2>
<h3>No Bake Pudding</h3><button onClick={earn1}>$1</button>
{
score >= 5 ? <><h3>Purchase Easy Bake Oven</h3> <button onClick={reveal}>$5</button></>
:
null
}
<h3></h3>
</div>
)
}
export default App
A:
You can do this with using an arrow function.
const App = () => {
const [score, setScore] = useState(0)
const earn1 = () => {
setScore(score + 1)
}
const earn5 = () => {
setScore(score + 5)
}
const upgrade = () => {
if (score >= 5) {
setShowEZBake(true)
}
}
const [showEZBake, setShowEZBake] = useState(false)
return (
<div>
<h1>Bakery</h1>
<h2>Revenue {score}</h2>
<h3>No Bake Pudding</h3><button onClick={earn1}>$1</button>
{showEZBake ? (
<>
<h3>Easy Bake Oven</h3>
<button onClick={earn5}>$5</button>
</>
) : (
<>
<h3>Purchase Easy Bake Oven</h3>
<button onClick={upgrade}>$5</button>
</>
)}
</div>
)
}
The upgrade function is called when the user clicks the "Purchase Easy Bake Oven" button. If the score is greater than or equal to 5, then the upgrade function sets the showEZBake state to true, which causes the "Easy Bake Oven" button to be displayed instead of the "Purchase Easy Bake Oven" button.
A:
In React, you can call a function inside the return section by simply referencing the function name, just like in JavaScript. In your code, you have a button that calls the reveal function when it is clicked. This function is supposed to return an <h1> element with the text "TEST", but it is not currently doing that because you are not returning anything from the reveal function.
To fix this, you can add a return statement at the beginning of the reveal function to return the <h1> element if the score is greater than or equal to 5, and return null otherwise. Here is an example of how you could do this:
const reveal = () => {
// If the score is greater than or equal to 5, return the <h1> element
if (score >= 5) {
return (
<h1>TEST</h1>
)
} else {
// Otherwise, return null
return null
}
}
After you have updated the reveal function to return the <h1> element, you can call this function in the return section of your component like this:
return (
<div>
<h1>Bakery</h1>
<h2>Revenue {score}</h2>
<h3>No Bake Pudding</h3><button onClick={earn1}>$1</button>
{
// Call the reveal function here to display the <h1> element
reveal()
}
<h3></h3>
</div>
)
This will cause the <h1> element to be displayed when the reveal function is called, which will happen when the button is clicked.
|
Can I call a function in react return?
|
Is there a way I can call a function in the return section of React? kind of like how in JS I can just call a function by functionName() ?
WHAT EXACTLY AM I TRYING TO ACCOMPLISH?
What I am wanting to do in this bakery game is when the player hits $5, the "Purchase Easy Bake Oven" pops up and it will cost them $25 to purchase (At this time I do not necessarily care about the math mathing, I just care for functionality). Once the player decides to purchase, this section disappears and is replaced with "Easy bake Oven" With a button that says $5 where at this point, every time the button is clicked my total increases by 5.
WHAT HAVE I TRIED?
I feel like this should be done with an onClick event to switch from const [showEZBake, setShowEZBake] = useState(false) to useState(True). I currently have a Turnary (or whatever you call it), but I feel like this is incorrect because I need to change the state as stated before. I have also attempted to create an if statement inside of a function where I would add an h1 element, but that did not work. Even if it did, my main issue would still be there and that is how to call a function inside of a return.
SUMMARY:
I want the "Purchase Oven" text and $5 button to be replaced with Oven and $2 button AFTER the button was clicked.
import React, {useState, useEffect} from 'react'
const App = () => {
// ======================================
// HOOKS
// ======================================
const [score, setScore] = useState(0)
// ======================================
// FUNCTIONS
// ======================================
// EARN REVENUE FUNCTIONS
const earn1 = () => {
setScore(score + 1)
}
const earn5 = () => {
setScore(score + 5)
}
const reveal = () => {
// setShowEZBake(false)
if (score >= 5) {
return (
<h1>TEST</h1>
)
} else {
}
}
const upgrade = () => {
if (score >= 5) {
<><h3>Purchase Easy Bake Oven</h3> <button>$5</button></>
}
else {
}
}
const [showEZBake, setShowEZBake] = useState(false)
// ======================================
// DISPLAY
// ======================================
return (
<div>
<h1>Bakery</h1>
<h2>Revenue {score}</h2>
<h3>No Bake Pudding</h3><button onClick={earn1}>$1</button>
{
score >= 5 ? <><h3>Purchase Easy Bake Oven</h3> <button onClick={reveal}>$5</button></>
:
null
}
<h3></h3>
</div>
)
}
export default App
|
[
"You can do this with using an arrow function.\nconst App = () => {\n const [score, setScore] = useState(0)\n\n const earn1 = () => {\n setScore(score + 1)\n }\n\n const earn5 = () => {\n setScore(score + 5)\n }\n\n const upgrade = () => {\n if (score >= 5) {\n setShowEZBake(true)\n }\n }\n\n const [showEZBake, setShowEZBake] = useState(false)\n\n return (\n <div>\n <h1>Bakery</h1>\n <h2>Revenue {score}</h2>\n <h3>No Bake Pudding</h3><button onClick={earn1}>$1</button>\n\n {showEZBake ? (\n <>\n <h3>Easy Bake Oven</h3>\n <button onClick={earn5}>$5</button>\n </>\n ) : (\n <>\n <h3>Purchase Easy Bake Oven</h3>\n <button onClick={upgrade}>$5</button>\n </>\n )}\n </div>\n )\n}\n\nThe upgrade function is called when the user clicks the \"Purchase Easy Bake Oven\" button. If the score is greater than or equal to 5, then the upgrade function sets the showEZBake state to true, which causes the \"Easy Bake Oven\" button to be displayed instead of the \"Purchase Easy Bake Oven\" button.\n",
"In React, you can call a function inside the return section by simply referencing the function name, just like in JavaScript. In your code, you have a button that calls the reveal function when it is clicked. This function is supposed to return an <h1> element with the text \"TEST\", but it is not currently doing that because you are not returning anything from the reveal function.\nTo fix this, you can add a return statement at the beginning of the reveal function to return the <h1> element if the score is greater than or equal to 5, and return null otherwise. Here is an example of how you could do this:\nconst reveal = () => {\n // If the score is greater than or equal to 5, return the <h1> element\n if (score >= 5) {\n return (\n <h1>TEST</h1>\n )\n } else {\n // Otherwise, return null\n return null\n }\n}\n\nAfter you have updated the reveal function to return the <h1> element, you can call this function in the return section of your component like this:\nreturn (\n <div>\n <h1>Bakery</h1>\n <h2>Revenue {score}</h2>\n <h3>No Bake Pudding</h3><button onClick={earn1}>$1</button>\n \n {\n // Call the reveal function here to display the <h1> element\n reveal()\n }\n <h3></h3>\n </div>\n)\n\nThis will cause the <h1> element to be displayed when the reveal function is called, which will happen when the button is clicked.\n"
] |
[
1,
1
] |
[] |
[] |
[
"jsx",
"reactjs"
] |
stackoverflow_0074670717_jsx_reactjs.txt
|
Q:
How can i use .kv file in different folders?
I don't know how to use .kv file so i just want to summary example. For example let we have 2 folders.
These folders: src and design.
src folder contain: main.py
design folder contain: main.kv
I want to know just simple example in this situation. How can i access from main.py file to main.kv file. I researched but i didn't understand very well. Please just give me a simple example.
A:
you can use the Builder object to load all of the .kv files you want.
# useful for creating paths from multiple parts
from pathlib import Path, PurePath
#
from kivy.lang import Builder
# load_file can be called multiple times
Builder.load_file(str(PurePath("c:/", "users", "public", "my_lib.kv")))
Builder.load_file(str(PurePath("c:/", "users", "public", "my_wigdet.kv")))
I don't know the reason but in at least one of my apps, I had to load the one .kv file for the main app in a different way.
main_gui_app = App() # substitute your own app creation..
main_gui_app.kv_file = str(Path(*your_path, "main_app.kv"))
main_qui_app.run()
|
How can i use .kv file in different folders?
|
I don't know how to use .kv file so i just want to summary example. For example let we have 2 folders.
These folders: src and design.
src folder contain: main.py
design folder contain: main.kv
I want to know just simple example in this situation. How can i access from main.py file to main.kv file. I researched but i didn't understand very well. Please just give me a simple example.
|
[
"you can use the Builder object to load all of the .kv files you want.\n # useful for creating paths from multiple parts\n from pathlib import Path, PurePath\n #\n from kivy.lang import Builder\n # load_file can be called multiple times\n Builder.load_file(str(PurePath(\"c:/\", \"users\", \"public\", \"my_lib.kv\")))\n Builder.load_file(str(PurePath(\"c:/\", \"users\", \"public\", \"my_wigdet.kv\")))\n\nI don't know the reason but in at least one of my apps, I had to load the one .kv file for the main app in a different way.\nmain_gui_app = App() # substitute your own app creation..\nmain_gui_app.kv_file = str(Path(*your_path, \"main_app.kv\"))\nmain_qui_app.run()\n\n"
] |
[
0
] |
[] |
[] |
[
"kivy",
"kivy_language",
"python"
] |
stackoverflow_0074667825_kivy_kivy_language_python.txt
|
Q:
check if a variable contains img tagname
I have a variable which stores user html input, this input might be a text or an image. I want to check if the user have entred an image or a simple text
example of user entry
this.userEntries = <p> < img src=" nature.png"></p>
txtOrImg: function () {
// expected logic
if userEntries includes tagname('img') return ... else return ...
}
A:
Use DOMParser() and its parseFromString() Method. Then traverse it using Element.querySelector() to get a desired child Element
const data = `<p><img src="nature.png"></p>`;
const doc = new DOMParser().parseFromString(data, "text/html");
const img = doc.querySelector("img");
if (img) {
console.log("Has image!", img);
} else {
console.log("No image");
}
|
check if a variable contains img tagname
|
I have a variable which stores user html input, this input might be a text or an image. I want to check if the user have entred an image or a simple text
example of user entry
this.userEntries = <p> < img src=" nature.png"></p>
txtOrImg: function () {
// expected logic
if userEntries includes tagname('img') return ... else return ...
}
|
[
"Use DOMParser() and its parseFromString() Method. Then traverse it using Element.querySelector() to get a desired child Element\n\n\nconst data = `<p><img src=\"nature.png\"></p>`;\n\nconst doc = new DOMParser().parseFromString(data, \"text/html\");\nconst img = doc.querySelector(\"img\");\n\nif (img) {\n console.log(\"Has image!\", img);\n} else {\n console.log(\"No image\");\n}\n\n\n\n"
] |
[
2
] |
[] |
[] |
[
"javascript",
"vue.js",
"vuejs2"
] |
stackoverflow_0074670707_javascript_vue.js_vuejs2.txt
|
Q:
Clean way to send data struct from python to arduino?
I'm working on a robot and I'd like to somehow send a command using pySerial to the arduino.
The command would look like {MOVE, 60, 70} or {REQUEST_DATA}, where I'd have the arduino read in the first value, if it's "MOVE" then it drives some motors with speed 60 and 70, and if it's "REQUEST_DATA" it would respond with some data like battery status, gps location etc.
Sending this as a string of characters and then parsing is really a huge pain! I've tried days (!frustration!) without it working properly. Is there a way to serialize a data structure like {'MOVE', 70, 40}, send the bytes to the arduino and reconstruct into a struct there? (Using struct.pack() maybe? But I don't yet know how to "unpack" in the arduino).
I've looked at serial communication on arduino and people seem to just do it the 'frustrating' way - sending single chars. Plus all talk about sending struct from arduino to python, and not the other way round.
A:
There are a number of ways to tackle this problem, and the best solution depends on exactly what data you're sending back and forth.
The simplest solution is to represent commands a single bytes (e.g., M for MOVE or R for REQUEST_DATA), because this way you only need to read a single byte on the arduino side to determine the command. Once you know that, you should know how much additional data you need to read in order to get the necessary parameters.
For example, here's a simple program that understands two commands:
A command to move to a given position
A command to turn the built-in LED on or off
The code looks like this:
#define CMD_MOVE 'M'
#define CMD_LED 'L'
struct Position {
int8_t xpos, ypos;
};
struct LEDState {
byte state;
};
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
// We need this so our Python code knows when the arduino is
// ready to receive data.
Serial.println("READY");
}
void loop() {
char cmd;
size_t nb;
if (Serial.available()) {
cmd = Serial.read();
switch (cmd) {
case CMD_MOVE:
struct Position pos;
nb = Serial.readBytes((char *)&pos, sizeof(struct Position));
Serial.print("Moving to position ");
Serial.print(pos.xpos);
Serial.print(",");
Serial.println(pos.ypos);
break;
case CMD_LED:
struct LEDState led;
nb = Serial.readBytes((char *)&led, sizeof(struct LEDState));
if (led.state) {
digitalWrite(LED_BUILTIN, HIGH);
} else {
digitalWrite(LED_BUILTIN, LOW);
}
Serial.print("LED is ");
Serial.println(led.state ? "on" : "off");
break;
}
}
}
A fragment of Python code that interacts with the above might look like this (assuming that port is a serial.Serial object):
print("waiting for arduino...")
line=b""
while not b"READY" in line:
line = port.readline()
port.write(struct.pack('bbb', ord('M'), 10, -10))
res = port.readline()
print(res)
for i in range(10):
port.write(struct.pack('bb', ord('L'), i%2))
res = port.readline()
print(res)
time.sleep(0.5)
port.write(struct.pack('bbb', ord('M'), -10, 10))
res = port.readline()
print(res)
Running the above Python code, with the Arduino code loaded on my Uno, produces:
waiting for arduino...
b'Moving to position -10,10\r\n'
b'LED is off\r\n'
b'LED is on\r\n'
b'LED is off\r\n'
b'LED is on\r\n'
b'LED is off\r\n'
b'LED is on\r\n'
b'LED is off\r\n'
b'LED is on\r\n'
b'LED is off\r\n'
b'LED is on\r\n'
b'Moving to position 10,-10\r\n'
This is simple to implement and doesn't require much in the way of decoding on the Arduino side.
For more complex situations, you may want to investigate more complex serialization solutions: for example, you can send JSON to the arduino and use something like https://arduinojson.org/ to deserialize it on the Arduino side, but that's going to be a much more complex solution.
In most cases, the speed at which this works is going to be limited by the speed of the serial port: the default speed of 9600bps is relatively slow, and you're going to notice that with larger amounts of data. Using higher serial port speeds will make things noticeably faster: I'm too lazy to look up the max. speed supported by the Arduino, but my UNO works at least as fast as 115200bps.
|
Clean way to send data struct from python to arduino?
|
I'm working on a robot and I'd like to somehow send a command using pySerial to the arduino.
The command would look like {MOVE, 60, 70} or {REQUEST_DATA}, where I'd have the arduino read in the first value, if it's "MOVE" then it drives some motors with speed 60 and 70, and if it's "REQUEST_DATA" it would respond with some data like battery status, gps location etc.
Sending this as a string of characters and then parsing is really a huge pain! I've tried days (!frustration!) without it working properly. Is there a way to serialize a data structure like {'MOVE', 70, 40}, send the bytes to the arduino and reconstruct into a struct there? (Using struct.pack() maybe? But I don't yet know how to "unpack" in the arduino).
I've looked at serial communication on arduino and people seem to just do it the 'frustrating' way - sending single chars. Plus all talk about sending struct from arduino to python, and not the other way round.
|
[
"There are a number of ways to tackle this problem, and the best solution depends on exactly what data you're sending back and forth.\nThe simplest solution is to represent commands a single bytes (e.g., M for MOVE or R for REQUEST_DATA), because this way you only need to read a single byte on the arduino side to determine the command. Once you know that, you should know how much additional data you need to read in order to get the necessary parameters.\nFor example, here's a simple program that understands two commands:\n\nA command to move to a given position\nA command to turn the built-in LED on or off\n\nThe code looks like this:\n#define CMD_MOVE 'M'\n#define CMD_LED 'L'\n\nstruct Position {\n int8_t xpos, ypos;\n};\n\nstruct LEDState {\n byte state;\n};\n\nvoid setup() {\n Serial.begin(9600);\n pinMode(LED_BUILTIN, OUTPUT);\n\n // We need this so our Python code knows when the arduino is\n // ready to receive data.\n Serial.println(\"READY\");\n}\n\nvoid loop() {\n char cmd;\n size_t nb;\n\n if (Serial.available()) {\n cmd = Serial.read();\n switch (cmd) {\n case CMD_MOVE:\n struct Position pos;\n nb = Serial.readBytes((char *)&pos, sizeof(struct Position));\n Serial.print(\"Moving to position \");\n Serial.print(pos.xpos);\n Serial.print(\",\");\n Serial.println(pos.ypos);\n break;\n case CMD_LED:\n struct LEDState led;\n nb = Serial.readBytes((char *)&led, sizeof(struct LEDState));\n if (led.state) {\n digitalWrite(LED_BUILTIN, HIGH);\n } else {\n digitalWrite(LED_BUILTIN, LOW);\n }\n Serial.print(\"LED is \");\n Serial.println(led.state ? \"on\" : \"off\");\n\n break;\n }\n }\n}\n\nA fragment of Python code that interacts with the above might look like this (assuming that port is a serial.Serial object):\nprint(\"waiting for arduino...\")\nline=b\"\"\nwhile not b\"READY\" in line:\n line = port.readline()\n\nport.write(struct.pack('bbb', ord('M'), 10, -10))\nres = port.readline()\nprint(res)\n\nfor i in range(10):\n port.write(struct.pack('bb', ord('L'), i%2))\n res = port.readline()\n print(res)\n time.sleep(0.5)\n\nport.write(struct.pack('bbb', ord('M'), -10, 10))\nres = port.readline()\nprint(res)\n\nRunning the above Python code, with the Arduino code loaded on my Uno, produces:\nwaiting for arduino...\nb'Moving to position -10,10\\r\\n'\nb'LED is off\\r\\n'\nb'LED is on\\r\\n'\nb'LED is off\\r\\n'\nb'LED is on\\r\\n'\nb'LED is off\\r\\n'\nb'LED is on\\r\\n'\nb'LED is off\\r\\n'\nb'LED is on\\r\\n'\nb'LED is off\\r\\n'\nb'LED is on\\r\\n'\nb'Moving to position 10,-10\\r\\n'\n\nThis is simple to implement and doesn't require much in the way of decoding on the Arduino side.\nFor more complex situations, you may want to investigate more complex serialization solutions: for example, you can send JSON to the arduino and use something like https://arduinojson.org/ to deserialize it on the Arduino side, but that's going to be a much more complex solution.\n\nIn most cases, the speed at which this works is going to be limited by the speed of the serial port: the default speed of 9600bps is relatively slow, and you're going to notice that with larger amounts of data. Using higher serial port speeds will make things noticeably faster: I'm too lazy to look up the max. speed supported by the Arduino, but my UNO works at least as fast as 115200bps.\n"
] |
[
1
] |
[] |
[] |
[
"arduino",
"pyserial",
"python",
"serial_communication"
] |
stackoverflow_0074669524_arduino_pyserial_python_serial_communication.txt
|
Q:
Understanding and managing c++ program crash handling in windows
I have a c++ program compiled with MinGW which links to libmicrohttpd to run a webserver. It normally functions correctly, but I am trying to do some robustness testing and for my current test I have tried to disable the network interface. This results in the program crashing with the dialog box: "MyProgram.exe has stopped working - A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available."
Rather than debug the program and potentially its dependencies, for my purposes, it would be fine if it would just crash silently without making the dialog box (I have another component that is meant to restart it). Is this possible to do via some sort of manifest or Windows API call?
A:
It turns out there is a Windows API function called SetErrorMode. Passing the parameter SEM_NOGPFAULTERRORBOX will prevent the error dialog from being displayed on a crash.
There is also the RegisterApplicationRestart function which can be used to have Windows restart an application in the event of a crash (or other configurable reasons).
|
Understanding and managing c++ program crash handling in windows
|
I have a c++ program compiled with MinGW which links to libmicrohttpd to run a webserver. It normally functions correctly, but I am trying to do some robustness testing and for my current test I have tried to disable the network interface. This results in the program crashing with the dialog box: "MyProgram.exe has stopped working - A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available."
Rather than debug the program and potentially its dependencies, for my purposes, it would be fine if it would just crash silently without making the dialog box (I have another component that is meant to restart it). Is this possible to do via some sort of manifest or Windows API call?
|
[
"It turns out there is a Windows API function called SetErrorMode. Passing the parameter SEM_NOGPFAULTERRORBOX will prevent the error dialog from being displayed on a crash.\nThere is also the RegisterApplicationRestart function which can be used to have Windows restart an application in the event of a crash (or other configurable reasons).\n"
] |
[
0
] |
[] |
[] |
[
"c++",
"crash",
"mingw",
"windows"
] |
stackoverflow_0074658837_c++_crash_mingw_windows.txt
|
Q:
Why do my PDB's for my VB6 project not match the generated dll?
I have a VB6 project and have enabled it to generate pdb files (this shows how to do that). However I can't debug with them and when I check them with symcheck I get this output:
>SYMCHK: MyFile.dll FAILED - MyFile.pdb mismatched or not found
>SYMCHK: FAILED files = 1
>SYMCHK: PASSED + IGNORED files = 0
I've checked with the verbose output that its finding the pdb (even moving it to a directory that its checking) but it just doesn't seem to want to match.
What might cause this and what can I do about it?
A:
You can try setting the compatibility of your VB6 project.
It is clearly explained here:
http://www.techrepublic.com/article/demystifying-version-compatibility-settings-in-visual-basic/
Maybe the change in the associated GUID causes the pdb mismatch.
A:
There are a few potential reasons why the PDB file for your VB6 project might not match the generated DLL. Here are a few possibilities:
You might not be generating the PDB file correctly. To generate a
PDB file for your VB6 project, you need to enable the "Generate
Symbolic Debug Info" option in the Project Properties dialog.
Your PDB file might be out of date. This can happen if you have made
changes to your code and then re-built the DLL without regenerating
the PDB file. To fix this, you can try regenerating the PDB file by
building your project again and making sure the "Generate Symbolic
Debug Info" option is still enabled.
Your PDB file might have become corrupted. This can happen if your
computer crashed or if the file was otherwise damaged. In this case,
you will need to regenerate the PDB file as described above.
You might be using the wrong PDB file. If you have multiple versions
of your DLL, you might be trying to use the PDB file for the wrong
version. Make sure you are using the correct PDB file for the
version of the DLL you are trying to debug.
If you are still having trouble getting your PDB file to match your
DLL, you might want to try using the SYMCHK tool with the /V option
to get more detailed information about why the PDB file is not
matching. This can help you identify the specific problem and take
steps to fix it.
|
Why do my PDB's for my VB6 project not match the generated dll?
|
I have a VB6 project and have enabled it to generate pdb files (this shows how to do that). However I can't debug with them and when I check them with symcheck I get this output:
>SYMCHK: MyFile.dll FAILED - MyFile.pdb mismatched or not found
>SYMCHK: FAILED files = 1
>SYMCHK: PASSED + IGNORED files = 0
I've checked with the verbose output that its finding the pdb (even moving it to a directory that its checking) but it just doesn't seem to want to match.
What might cause this and what can I do about it?
|
[
"You can try setting the compatibility of your VB6 project.\nIt is clearly explained here:\nhttp://www.techrepublic.com/article/demystifying-version-compatibility-settings-in-visual-basic/\nMaybe the change in the associated GUID causes the pdb mismatch.\n",
"There are a few potential reasons why the PDB file for your VB6 project might not match the generated DLL. Here are a few possibilities:\n\nYou might not be generating the PDB file correctly. To generate a\nPDB file for your VB6 project, you need to enable the \"Generate\nSymbolic Debug Info\" option in the Project Properties dialog.\nYour PDB file might be out of date. This can happen if you have made\nchanges to your code and then re-built the DLL without regenerating\nthe PDB file. To fix this, you can try regenerating the PDB file by\nbuilding your project again and making sure the \"Generate Symbolic\nDebug Info\" option is still enabled.\nYour PDB file might have become corrupted. This can happen if your\ncomputer crashed or if the file was otherwise damaged. In this case,\nyou will need to regenerate the PDB file as described above.\nYou might be using the wrong PDB file. If you have multiple versions\nof your DLL, you might be trying to use the PDB file for the wrong\nversion. Make sure you are using the correct PDB file for the\nversion of the DLL you are trying to debug.\nIf you are still having trouble getting your PDB file to match your\nDLL, you might want to try using the SYMCHK tool with the /V option\nto get more detailed information about why the PDB file is not\nmatching. This can help you identify the specific problem and take\nsteps to fix it.\n\n"
] |
[
0,
0
] |
[
"I experienced the same issue with Visual Studio (it was on a c# project). Because you didn't provide many information about your environment setup it's hard to tell the exact causes of the problem. \nBecause I have no experience with Visual Basic IDE I will propose causes of the problem with Visual Studio. Depending on your projects and setup this could be applicable or not to your VB IDE. Just try to apply them to it.\nSo here is a non exhaustive list of potential issues that may be causing this behavior with visual studio: \n\nThe dlls used by your program are cached ones\n\n\nThis can occur if your executable is using cached version of the dll (this is also known as shadow-copying). Often these files are in a temporary folder.\nTo fix it, one has to simply delete these temporary files.\n\nYour debugger is trying to load modules and symbols at the wrong place\n\n\nFor instance Visual Studio can be set to load modules at a specific place.\nTo fix it one has to fix the place where modules are loaded (Ctrl + D + M usually).\n\nYour clean/rebuild operation only rebuild the output project.\n\n\nVisual studio may rebuild only your output project while you wanted to rebuild all of your solution.\nTo fix it, one has to check it is correctly rebuilding the whole solution.\nNote that your clean operation may not delete references that are referenced by the project but not relevant to it. These files will remain in the output folders until you delete them.\n\nVisual Studio has entered a unstable state and probably need to be restarted.\n\n\nI count no more the numerous times where a simple restart of my Visual Studio instance fixed most of the weird compile-time behavior.\nTo fix it one has to simply restart Visual Studio.\n\n\nUsually a kind of bullet-proof way to go when you encounter this is to : \n\nclean the solution\ndelete every bin and obj folders in each of your projects\ndelete any temporary folder used for shadow-copy\nperform a rebuild\n\n"
] |
[
-1
] |
[
"debug_symbols",
"pdb_files",
"vb6"
] |
stackoverflow_0035182686_debug_symbols_pdb_files_vb6.txt
|
Q:
C++ pushing even numbers in an even stack and odd numbers in an odd stack
I'm trying to verify if the current element is even and push it into an even stack and if not to push it into an odd stack without using the library. I want to push 6 into the even stack delete it from the first stack using pop and so on
| Odd stack| First Stack | | Even stack|
| -------- | 4 | | 6 |
| 5 | 12 | | 12 |
| 3 | 3 | | 4 |
| | 5 | | |
| | 6 | | |
#include <conio.h>
#include <fstream>
#include <iostream>
using namespace std;
struct nod {
int info;
nod* next;
};
nod* l;
int n;
nod* push(int info, nod* l) {
nod* aux;
aux = new nod;
aux->info = info;
aux->next = l;
return aux;
}
nod* pop(nod* l) {
nod *aux1, *aux2;
if (l != NULL) {
aux1 = l;
aux2 = l->next;
cout << "\nVoi sterge nodul care contine:" << aux1->info << endl;
delete aux1;
return aux2;
} else {
cout << "\n Stiva este goala. Nu am ce sa sterg." << endl;
return NULL;
}
}
// creating stack
void creare_stiva() {
nod* a;
int info;
ifstream f("in.txt");
f >> n;
for (int i = 0; i < n; i++) {
f >> info;
l = push(info, l);
}
}
// displaying stack
void afisare_stiva(nod* a) {
a = l;
if (a == NULL)
cout << "Lista nu exista";
else {
cout << "\nElementele listei sunt: ";
while (a) {
cout << a->info << " | ";
a = a->next;
}
}
}
int main() {
creare_stiva();
afisare_stiva(l);
cout << endl;
return 0;
}
I tried testing if the element is odd or even but i don't know how to push it in an even stack and then delete it
How do I create 2 stacks, one even and one odd to then put the elements from the first stack and then delete them as I go?
void testing() {
int info;
while (l) {
if (l -> info % 2 == 0) {
l = push(info, l)
l = l -> next;
} else {
l = l -> next;
}
}
}
A:
First, create 2 stacks and name them like oddStack and evenStack. Then check if the number is odd or even. If the number is even, push it to evenStack; if the number is odd, push it to oddStack.
|
C++ pushing even numbers in an even stack and odd numbers in an odd stack
|
I'm trying to verify if the current element is even and push it into an even stack and if not to push it into an odd stack without using the library. I want to push 6 into the even stack delete it from the first stack using pop and so on
| Odd stack| First Stack | | Even stack|
| -------- | 4 | | 6 |
| 5 | 12 | | 12 |
| 3 | 3 | | 4 |
| | 5 | | |
| | 6 | | |
#include <conio.h>
#include <fstream>
#include <iostream>
using namespace std;
struct nod {
int info;
nod* next;
};
nod* l;
int n;
nod* push(int info, nod* l) {
nod* aux;
aux = new nod;
aux->info = info;
aux->next = l;
return aux;
}
nod* pop(nod* l) {
nod *aux1, *aux2;
if (l != NULL) {
aux1 = l;
aux2 = l->next;
cout << "\nVoi sterge nodul care contine:" << aux1->info << endl;
delete aux1;
return aux2;
} else {
cout << "\n Stiva este goala. Nu am ce sa sterg." << endl;
return NULL;
}
}
// creating stack
void creare_stiva() {
nod* a;
int info;
ifstream f("in.txt");
f >> n;
for (int i = 0; i < n; i++) {
f >> info;
l = push(info, l);
}
}
// displaying stack
void afisare_stiva(nod* a) {
a = l;
if (a == NULL)
cout << "Lista nu exista";
else {
cout << "\nElementele listei sunt: ";
while (a) {
cout << a->info << " | ";
a = a->next;
}
}
}
int main() {
creare_stiva();
afisare_stiva(l);
cout << endl;
return 0;
}
I tried testing if the element is odd or even but i don't know how to push it in an even stack and then delete it
How do I create 2 stacks, one even and one odd to then put the elements from the first stack and then delete them as I go?
void testing() {
int info;
while (l) {
if (l -> info % 2 == 0) {
l = push(info, l)
l = l -> next;
} else {
l = l -> next;
}
}
}
|
[
"First, create 2 stacks and name them like oddStack and evenStack. Then check if the number is odd or even. If the number is even, push it to evenStack; if the number is odd, push it to oddStack.\n"
] |
[
0
] |
[] |
[] |
[
"c++",
"stack"
] |
stackoverflow_0074670511_c++_stack.txt
|
Q:
how to read from cursor which has invalid date format in one row and ignore the problematic entry
sample table data
{ _id: 1, modified: 2020-07-25T14:10:26.000+00:00, created : 2020-07-20T14:10:26.000+00:00}
{ _id: 2, modified: 2020-07-29T07:55:55.485.000+00:00, created : 201244-01-01T14:10:26.000+00:00}
{ _id: 3, modified: 2020-08-01T01:00:12.002.000+00:00, created : 2020-07-01T01:00:12.002.000+00:00}
used below sample code to read the data from table
using pymongo==3.12.0
db = "testdb"
table = "test"
filter = "modified"
query = {'modified': {'$gt': datetime.datetime(2020, 07, 22, 6, 35, 51, 859000), '$lte': datetime.datetime(2022, 12, 1, 2, 44, 41, 424501)}}
cursor = db[table].find(query).sort(filter, 1).skip(1000).limit(1000)
for docs in cursor:
print(docs)
I am getting InvalidBson exception year 201244 out of range in _id = 2 which has problematic created and it couldn't proceed further
I would like to know how to read from cursor in loop and ignore the invalid bson formatted data from cursor
Traceback (most recent call last):
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 1027, in decode_all
docs.append(_elements_to_dict(data,
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 471, in _elements_to_dict
key, value, position = _element_to_dict(data, view, position, obj_end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 446, in _element_to_dict
value, position = _ELEMENT_GETTER[element_type](data, view, position,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 246, in _get_object
obj = _elements_to_dict(data, view, position + 4, end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 471, in _elements_to_dict
key, value, position = _element_to_dict(data, view, position, obj_end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 446, in _element_to_dict
value, position = _ELEMENT_GETTER[element_type](data, view, position,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 277, in _get_array
value, position = getter[element_type](
^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 246, in _get_object
obj = _elements_to_dict(data, view, position + 4, end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 471, in _elements_to_dict
key, value, position = _element_to_dict(data, view, position, obj_end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 446, in _element_to_dict
value, position = _ELEMENT_GETTER[element_type](data, view, position,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 352, in _get_date
return _millis_to_datetime(
^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 898, in _millis_to_datetime
return EPOCH_NAIVE + datetime.timedelta(seconds=seconds,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
OverflowError: date value out of range
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\sample.py", line 173, in run
^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pymongo\cursor.py", line 1238, in next
if len(self.__data) or self._refresh():
^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pymongo\cursor.py", line 1155, in _refresh
self.__send_message(q)
File "C:\Python\Python311\Lib\site-packages\pymongo\cursor.py", line 1044, in __send_message
response = client._run_operation(
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pymongo\mongo_client.py", line 1424, in _run_operation
return self._retryable_read(
^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pymongo\mongo_client.py", line 1525, in _retryable_read
return func(session, server, sock_info, secondary_ok)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pymongo\mongo_client.py", line 1420, in _cmd
return server.run_operation(
^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pymongo\server.py", line 123, in run_operation
docs = unpack_res(reply, operation.cursor_id,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pymongo\cursor.py", line 1109, in _unpack_response
return response.unpack_response(cursor_id, codec_options, user_fields,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pymongo\message.py", line 1600, in unpack_response
return bson._decode_all_selective(
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 1099, in _decode_all_selective
return decode_all(data, codec_options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 1039, in decode_all
reraise(InvalidBSON, exc_value, exc_tb)
File "C:\Python\Python311\Lib\site-packages\bson\py3compat.py", line 53, in reraise
raise exctype(str(value)).with_traceback(trace)
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 1027, in decode_all
docs.append(_elements_to_dict(data,
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 471, in _elements_to_dict
key, value, position = _element_to_dict(data, view, position, obj_end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 446, in _element_to_dict
value, position = _ELEMENT_GETTER[element_type](data, view, position,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 246, in _get_object
obj = _elements_to_dict(data, view, position + 4, end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 471, in _elements_to_dict
key, value, position = _element_to_dict(data, view, position, obj_end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 446, in _element_to_dict
value, position = _ELEMENT_GETTER[element_type](data, view, position,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 277, in _get_array
value, position = getter[element_type](
^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 246, in _get_object
obj = _elements_to_dict(data, view, position + 4, end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 471, in _elements_to_dict
key, value, position = _element_to_dict(data, view, position, obj_end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 446, in _element_to_dict
value, position = _ELEMENT_GETTER[element_type](data, view, position,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 352, in _get_date
return _millis_to_datetime(
^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 898, in _millis_to_datetime
return EPOCH_NAIVE + datetime.timedelta(seconds=seconds,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
bson.errors.InvalidBSON: date value out of range
I have tried handling through exception but couldn't ignore problematic entry from cursor
A:
PyMongo decodes BSON datetime values to instances of Python’s datetime.datetime. Instances of datetime.datetime are limited to years between datetime.MINYEAR (usually 1) and datetime.MAXYEAR (usually 9999). Some MongoDB drivers (e.g. the PHP driver) can store BSON datetimes with year values far outside those supported by datetime.datetime.
Best option is to fix those dates in the mongoDB collection from mongosh shell before fetching them via the pymongo driver since those dates are most probably invalid , but tolerated by mongoDB BSON.
|
how to read from cursor which has invalid date format in one row and ignore the problematic entry
|
sample table data
{ _id: 1, modified: 2020-07-25T14:10:26.000+00:00, created : 2020-07-20T14:10:26.000+00:00}
{ _id: 2, modified: 2020-07-29T07:55:55.485.000+00:00, created : 201244-01-01T14:10:26.000+00:00}
{ _id: 3, modified: 2020-08-01T01:00:12.002.000+00:00, created : 2020-07-01T01:00:12.002.000+00:00}
used below sample code to read the data from table
using pymongo==3.12.0
db = "testdb"
table = "test"
filter = "modified"
query = {'modified': {'$gt': datetime.datetime(2020, 07, 22, 6, 35, 51, 859000), '$lte': datetime.datetime(2022, 12, 1, 2, 44, 41, 424501)}}
cursor = db[table].find(query).sort(filter, 1).skip(1000).limit(1000)
for docs in cursor:
print(docs)
I am getting InvalidBson exception year 201244 out of range in _id = 2 which has problematic created and it couldn't proceed further
I would like to know how to read from cursor in loop and ignore the invalid bson formatted data from cursor
Traceback (most recent call last):
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 1027, in decode_all
docs.append(_elements_to_dict(data,
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 471, in _elements_to_dict
key, value, position = _element_to_dict(data, view, position, obj_end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 446, in _element_to_dict
value, position = _ELEMENT_GETTER[element_type](data, view, position,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 246, in _get_object
obj = _elements_to_dict(data, view, position + 4, end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 471, in _elements_to_dict
key, value, position = _element_to_dict(data, view, position, obj_end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 446, in _element_to_dict
value, position = _ELEMENT_GETTER[element_type](data, view, position,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 277, in _get_array
value, position = getter[element_type](
^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 246, in _get_object
obj = _elements_to_dict(data, view, position + 4, end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 471, in _elements_to_dict
key, value, position = _element_to_dict(data, view, position, obj_end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 446, in _element_to_dict
value, position = _ELEMENT_GETTER[element_type](data, view, position,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 352, in _get_date
return _millis_to_datetime(
^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 898, in _millis_to_datetime
return EPOCH_NAIVE + datetime.timedelta(seconds=seconds,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
OverflowError: date value out of range
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\sample.py", line 173, in run
^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pymongo\cursor.py", line 1238, in next
if len(self.__data) or self._refresh():
^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pymongo\cursor.py", line 1155, in _refresh
self.__send_message(q)
File "C:\Python\Python311\Lib\site-packages\pymongo\cursor.py", line 1044, in __send_message
response = client._run_operation(
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pymongo\mongo_client.py", line 1424, in _run_operation
return self._retryable_read(
^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pymongo\mongo_client.py", line 1525, in _retryable_read
return func(session, server, sock_info, secondary_ok)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pymongo\mongo_client.py", line 1420, in _cmd
return server.run_operation(
^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pymongo\server.py", line 123, in run_operation
docs = unpack_res(reply, operation.cursor_id,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pymongo\cursor.py", line 1109, in _unpack_response
return response.unpack_response(cursor_id, codec_options, user_fields,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pymongo\message.py", line 1600, in unpack_response
return bson._decode_all_selective(
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 1099, in _decode_all_selective
return decode_all(data, codec_options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 1039, in decode_all
reraise(InvalidBSON, exc_value, exc_tb)
File "C:\Python\Python311\Lib\site-packages\bson\py3compat.py", line 53, in reraise
raise exctype(str(value)).with_traceback(trace)
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 1027, in decode_all
docs.append(_elements_to_dict(data,
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 471, in _elements_to_dict
key, value, position = _element_to_dict(data, view, position, obj_end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 446, in _element_to_dict
value, position = _ELEMENT_GETTER[element_type](data, view, position,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 246, in _get_object
obj = _elements_to_dict(data, view, position + 4, end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 471, in _elements_to_dict
key, value, position = _element_to_dict(data, view, position, obj_end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 446, in _element_to_dict
value, position = _ELEMENT_GETTER[element_type](data, view, position,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 277, in _get_array
value, position = getter[element_type](
^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 246, in _get_object
obj = _elements_to_dict(data, view, position + 4, end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 471, in _elements_to_dict
key, value, position = _element_to_dict(data, view, position, obj_end, opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 446, in _element_to_dict
value, position = _ELEMENT_GETTER[element_type](data, view, position,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 352, in _get_date
return _millis_to_datetime(
^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\bson\__init__.py", line 898, in _millis_to_datetime
return EPOCH_NAIVE + datetime.timedelta(seconds=seconds,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
bson.errors.InvalidBSON: date value out of range
I have tried handling through exception but couldn't ignore problematic entry from cursor
|
[
"PyMongo decodes BSON datetime values to instances of Python’s datetime.datetime. Instances of datetime.datetime are limited to years between datetime.MINYEAR (usually 1) and datetime.MAXYEAR (usually 9999). Some MongoDB drivers (e.g. the PHP driver) can store BSON datetimes with year values far outside those supported by datetime.datetime.\nBest option is to fix those dates in the mongoDB collection from mongosh shell before fetching them via the pymongo driver since those dates are most probably invalid , but tolerated by mongoDB BSON.\n"
] |
[
0
] |
[] |
[] |
[
"mongodb",
"pymongo",
"pymongo_3.x",
"python_3.x"
] |
stackoverflow_0074669557_mongodb_pymongo_pymongo_3.x_python_3.x.txt
|
Q:
How to generate Pre Launch report for Flutter App?
I have a login screen which uses phone authentication for creating account.
I have used Firebase Phone auth for login and also have stored one number for testing purpose.
But don't know how to pass the number and OTP to generate Pre Launch Report.
They are asking for Username, Username Resource ID, Password , Password Resource ID.
Where to find Resource ID for username and password fields in flutter code.
A:
In the Google play console at the bottom of the left
Click on App content
Click on App access
Click on manage
Click on add new instructions
Add your all details here it should be test accounts
A:
To generate a pre-launch report for a Flutter app, you need to use the flutter analyze command. This command will analyze your Flutter app and generate a report with information about any potential issues that it finds.
To use the flutter analyze command, you need to first ensure that you have the latest version of the Flutter SDK installed on your system. You can check which version you have installed by running the flutter doctor command. If you need to update your Flutter installation, you can do so by following the instructions on the Flutter website.
Once you have the latest version of Flutter installed, you can run the flutter analyze command from the root directory of your Flutter app. This command will analyze your app's source code and generate a report with information about any potential issues that it finds.
Here is an example of how you might use the flutter analyze command to generate a pre-launch report for your app:
flutter analyze
After running this command, you should see a report with information about any potential issues that were found in your app's source code. This report will include information about issues with your app's layout, performance, security, and more.
To answer your specific question about the username and password resource IDs, these are IDs that are used to identify the input fields for the username and password in your app's user interface. In Flutter, these IDs are typically specified using the key property of the TextField widget. For example, you might define your username and password input fields like this:
TextField(
key: Key('username'),
decoration: InputDecoration(
labelText: 'Username',
),
),
TextField(
key: Key('password'),
decoration: InputDecoration(
labelText: 'Password',
),
),
In this code, we use the key property to specify a unique ID for each of the input fields. We can then use these IDs to identify the input fields in our pre-launch report.
For more information about the flutter analyze command and how to use it to generate pre-launch reports for your Flutter apps, you can refer to the Flutter documentation. This will give you more detailed information about how the flutter analyze command works and how to interpret the reports that it generates.
|
How to generate Pre Launch report for Flutter App?
|
I have a login screen which uses phone authentication for creating account.
I have used Firebase Phone auth for login and also have stored one number for testing purpose.
But don't know how to pass the number and OTP to generate Pre Launch Report.
They are asking for Username, Username Resource ID, Password , Password Resource ID.
Where to find Resource ID for username and password fields in flutter code.
|
[
"In the Google play console at the bottom of the left\n\nClick on App content\n\n\n\nClick on App access\n\n\n\nClick on manage\n\n\n\nClick on add new instructions\n\n\nAdd your all details here it should be test accounts\n",
"To generate a pre-launch report for a Flutter app, you need to use the flutter analyze command. This command will analyze your Flutter app and generate a report with information about any potential issues that it finds.\nTo use the flutter analyze command, you need to first ensure that you have the latest version of the Flutter SDK installed on your system. You can check which version you have installed by running the flutter doctor command. If you need to update your Flutter installation, you can do so by following the instructions on the Flutter website.\nOnce you have the latest version of Flutter installed, you can run the flutter analyze command from the root directory of your Flutter app. This command will analyze your app's source code and generate a report with information about any potential issues that it finds.\nHere is an example of how you might use the flutter analyze command to generate a pre-launch report for your app:\nflutter analyze\n\nAfter running this command, you should see a report with information about any potential issues that were found in your app's source code. This report will include information about issues with your app's layout, performance, security, and more.\nTo answer your specific question about the username and password resource IDs, these are IDs that are used to identify the input fields for the username and password in your app's user interface. In Flutter, these IDs are typically specified using the key property of the TextField widget. For example, you might define your username and password input fields like this:\nTextField(\n key: Key('username'),\n decoration: InputDecoration(\n labelText: 'Username',\n ),\n),\nTextField(\n key: Key('password'),\n decoration: InputDecoration(\n labelText: 'Password',\n ),\n),\n\nIn this code, we use the key property to specify a unique ID for each of the input fields. We can then use these IDs to identify the input fields in our pre-launch report.\nFor more information about the flutter analyze command and how to use it to generate pre-launch reports for your Flutter apps, you can refer to the Flutter documentation. This will give you more detailed information about how the flutter analyze command works and how to interpret the reports that it generates.\n"
] |
[
0,
0
] |
[] |
[] |
[
"flutter",
"google_play",
"google_play_console"
] |
stackoverflow_0063781150_flutter_google_play_google_play_console.txt
|
Q:
ERROR org.apache.hadoop.conf.Configuration: error parsing conf mapred-site.xml
at org.apache.hadoop.hdfs.server.datanode.DataNode.main(DataNode.java:2924)
Caused by: com.ctc.wstx.exc.WstxParsingException: Unexpected close tag </name>; expected </nafme>.
at [row,col,system-id]: [39,40,"file:/opt/module/hadoop-3.1.3/etc/hadoop/mapred-site.xml"]
at com.ctc.wstx.sr.StreamScanner.constructWfcException(StreamScanner.java:621)
at com.ctc.wstx.sr.StreamScanner.throwParseError(StreamScanner.java:491)
at com.ctc.wstx.sr.StreamScanner.throwParseError(StreamScanner.java:475)
at com.ctc.wstx.sr.BasicStreamReader.reportWrongEndElem(BasicStreamReader.java:3365)
at com.ctc.wstx.sr.BasicStreamReader.readEndElem(BasicStreamReader.java:3292)
at com.ctc.wstx.sr.BasicStreamReader.nextFromTree(BasicStreamReader.java:2911)
at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1123)
at org.apache.hadoop.conf.Configuration$Parser.parseNext(Configuration.java:3320)
at org.apache.hadoop.conf.Configuration$Parser.parse(Configuration.java:3114)
at org.apache.hadoop.conf.Configuration.loadResource(Configuration.java:3007)
... 14 more
2022-12-02 13:21:18,536 INFO org.apache.hadoop.util.ExitUtil: Exiting with status 1: java.lang.RuntimeException: com.ctc.wstx.exc.WstxParsingException: Unexpected close tag </name>; expected </nafme>.
at [row,col,system-id]: [39,40,"file:/opt/module/hadoop-3.1.3/etc/hadoop/mapred-site.xml"]
2022-12-02 13:21:18,551 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: SHUTDOWN_MSG:
/************************************************************
SHUTDOWN_MSG: Shutting down DataNode at hadoop162/192.168.10.162
************************************************************/
2022-12-02 13:21:18,597 ERROR org.apache.hadoop.conf.Configuration: error parsing conf mapred-site.xml
com.ctc.wstx.exc.WstxParsingException: Unexpected close tag </name>; expected </nafme>.
at [row,col,system-id]: [39,40,"file:/opt/module/hadoop-3.1.3/etc/hadoop/mapred-site.xml"]
at com.ctc.wstx.sr.StreamScanner.constructWfcException(StreamScanner.java:621)
at com.ctc.wstx.sr.StreamScanner.throwParseError(StreamScanner.java:491)
at com.ctc.wstx.sr.StreamScanner.throwParseError(StreamScanner.java:475)
at com.ctc.wstx.sr.BasicStreamReader.reportWrongEndElem(BasicStreamReader.java:3365)
at com.ctc.wstx.sr.BasicStreamReader.readEndElem(BasicStreamReader.java:3292)
at com.ctc.wstx.sr.BasicStreamReader.nextFromTree(BasicStreamReader.java:2911)
at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1123)
at org.apache.hadoop.conf.Configuration$Parser.parseNext(Configuration.java:3320)
at org.apache.hadoop.conf.Configuration$Parser.parse(Configuration.java:3114)
at org.apache.hadoop.conf.Configuration.loadResource(Configuration.java:3007)
at org.apache.hadoop.conf.Configuration.loadResources(Configuration.java:2968)
at org.apache.hadoop.conf.Configuration.getProps(Configuration.java:2848)
at org.apache.hadoop.conf.Configuration.get(Configuration.java:1200)
at org.apache.hadoop.conf.Configuration.getTimeDuration(Configuration.java:1812)
at org.apache.hadoop.conf.Configuration.getTimeDuration(Configuration.java:1789)
at org.apache.hadoop.util.ShutdownHookManager.getShutdownTimeout(ShutdownHookManager.java:183)
at org.apache.hadoop.util.ShutdownHookManager.shutdownExecutor(ShutdownHookManager.java:145)
at org.apache.hadoop.util.ShutdownHookManager.access$300(ShutdownHookManager.java:65)
at org.apache.hadoop.util.ShutdownHookManager$1.run(ShutdownHookManager.java:102)
/opt/module/hadoop-3.1.3/logs » xcall atguigu@hadoop162
========== hadoop162 =========
3642 Jps
========== hadoop163 =========
3047 NodeManager
2603 DataNode
2893 ResourceManager
3503 Jps
========== hadoop164 =========
1191 DataNode
1368 NodeManager
1597 Jps
/opt/module/hadoop-3.1.3/logs » atguigu@hadoop162
enter image description here
there is an exception ,I can't start hadoop ,
022-12-02 13:21:18,597 ERROR org.apache.hadoop.conf.Configuration: error parsing conf mapred-site.xml
com.ctc.wstx.exc.WstxParsingException: Unexpected close tag </name>; expected </nafme>.
at [row,col,system-id]: [39,40,"file:/opt/module/hadoop-3.1.3/etc/hadoop/mapred-site.xml"]
A:
As the error says, you have mismatched XML tags.
nafme isn't a valid property tag
|
ERROR org.apache.hadoop.conf.Configuration: error parsing conf mapred-site.xml
|
at org.apache.hadoop.hdfs.server.datanode.DataNode.main(DataNode.java:2924)
Caused by: com.ctc.wstx.exc.WstxParsingException: Unexpected close tag </name>; expected </nafme>.
at [row,col,system-id]: [39,40,"file:/opt/module/hadoop-3.1.3/etc/hadoop/mapred-site.xml"]
at com.ctc.wstx.sr.StreamScanner.constructWfcException(StreamScanner.java:621)
at com.ctc.wstx.sr.StreamScanner.throwParseError(StreamScanner.java:491)
at com.ctc.wstx.sr.StreamScanner.throwParseError(StreamScanner.java:475)
at com.ctc.wstx.sr.BasicStreamReader.reportWrongEndElem(BasicStreamReader.java:3365)
at com.ctc.wstx.sr.BasicStreamReader.readEndElem(BasicStreamReader.java:3292)
at com.ctc.wstx.sr.BasicStreamReader.nextFromTree(BasicStreamReader.java:2911)
at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1123)
at org.apache.hadoop.conf.Configuration$Parser.parseNext(Configuration.java:3320)
at org.apache.hadoop.conf.Configuration$Parser.parse(Configuration.java:3114)
at org.apache.hadoop.conf.Configuration.loadResource(Configuration.java:3007)
... 14 more
2022-12-02 13:21:18,536 INFO org.apache.hadoop.util.ExitUtil: Exiting with status 1: java.lang.RuntimeException: com.ctc.wstx.exc.WstxParsingException: Unexpected close tag </name>; expected </nafme>.
at [row,col,system-id]: [39,40,"file:/opt/module/hadoop-3.1.3/etc/hadoop/mapred-site.xml"]
2022-12-02 13:21:18,551 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: SHUTDOWN_MSG:
/************************************************************
SHUTDOWN_MSG: Shutting down DataNode at hadoop162/192.168.10.162
************************************************************/
2022-12-02 13:21:18,597 ERROR org.apache.hadoop.conf.Configuration: error parsing conf mapred-site.xml
com.ctc.wstx.exc.WstxParsingException: Unexpected close tag </name>; expected </nafme>.
at [row,col,system-id]: [39,40,"file:/opt/module/hadoop-3.1.3/etc/hadoop/mapred-site.xml"]
at com.ctc.wstx.sr.StreamScanner.constructWfcException(StreamScanner.java:621)
at com.ctc.wstx.sr.StreamScanner.throwParseError(StreamScanner.java:491)
at com.ctc.wstx.sr.StreamScanner.throwParseError(StreamScanner.java:475)
at com.ctc.wstx.sr.BasicStreamReader.reportWrongEndElem(BasicStreamReader.java:3365)
at com.ctc.wstx.sr.BasicStreamReader.readEndElem(BasicStreamReader.java:3292)
at com.ctc.wstx.sr.BasicStreamReader.nextFromTree(BasicStreamReader.java:2911)
at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1123)
at org.apache.hadoop.conf.Configuration$Parser.parseNext(Configuration.java:3320)
at org.apache.hadoop.conf.Configuration$Parser.parse(Configuration.java:3114)
at org.apache.hadoop.conf.Configuration.loadResource(Configuration.java:3007)
at org.apache.hadoop.conf.Configuration.loadResources(Configuration.java:2968)
at org.apache.hadoop.conf.Configuration.getProps(Configuration.java:2848)
at org.apache.hadoop.conf.Configuration.get(Configuration.java:1200)
at org.apache.hadoop.conf.Configuration.getTimeDuration(Configuration.java:1812)
at org.apache.hadoop.conf.Configuration.getTimeDuration(Configuration.java:1789)
at org.apache.hadoop.util.ShutdownHookManager.getShutdownTimeout(ShutdownHookManager.java:183)
at org.apache.hadoop.util.ShutdownHookManager.shutdownExecutor(ShutdownHookManager.java:145)
at org.apache.hadoop.util.ShutdownHookManager.access$300(ShutdownHookManager.java:65)
at org.apache.hadoop.util.ShutdownHookManager$1.run(ShutdownHookManager.java:102)
/opt/module/hadoop-3.1.3/logs » xcall atguigu@hadoop162
========== hadoop162 =========
3642 Jps
========== hadoop163 =========
3047 NodeManager
2603 DataNode
2893 ResourceManager
3503 Jps
========== hadoop164 =========
1191 DataNode
1368 NodeManager
1597 Jps
/opt/module/hadoop-3.1.3/logs » atguigu@hadoop162
enter image description here
there is an exception ,I can't start hadoop ,
022-12-02 13:21:18,597 ERROR org.apache.hadoop.conf.Configuration: error parsing conf mapred-site.xml
com.ctc.wstx.exc.WstxParsingException: Unexpected close tag </name>; expected </nafme>.
at [row,col,system-id]: [39,40,"file:/opt/module/hadoop-3.1.3/etc/hadoop/mapred-site.xml"]
|
[
"As the error says, you have mismatched XML tags.\nnafme isn't a valid property tag\n"
] |
[
0
] |
[] |
[] |
[
"hadoop",
"mapreduce"
] |
stackoverflow_0074656862_hadoop_mapreduce.txt
|
Q:
How to capture link clicks in iframe and redirect them into the same iframe JavaScript
I have an iframe in my page whose code I can't control. This iframe has link with the target attribute being blank:
<a href = "https://www.example.com" target = "top">Go to example!</a>
An iframe such as youtube has these links as reccomemdations when you pause:
<iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ">
</iframe>
Is there any way to redirect these links to stay inside of the iframe, instead of creating a new popup?
A:
You can use the window.onclick event and check the target attribute of the event to determine if the clicked element is a link. If it is, you can use the event.preventDefault() method to prevent the default action (opening the link in a new window) and instead set the iframe's src attribute to the link's href value using the event.target.href property.
Here is an example of how this could be implemented:
// Get the iframe element
const iframe = document.querySelector('iframe');
// Add an onclick event listener to the window
window.onclick = (event) => {
// Check if the clicked element is a link
if (event.target.tagName === 'A') {
// Prevent the default action (opening the link in a new window)
event.preventDefault();
// Set the iframe's src attribute to the link's href value
iframe.src = event.target.href;
}
};
It is important to note that this solution will only work if the iframe's content is on the same domain as the parent page, as it would be a security risk to allow links from other domains to be opened in the iframe. If the content of the iframe is on a different domain, you will need to use a different solution, such as using the postMessage method to communicate between the parent page and the iframe.
|
How to capture link clicks in iframe and redirect them into the same iframe JavaScript
|
I have an iframe in my page whose code I can't control. This iframe has link with the target attribute being blank:
<a href = "https://www.example.com" target = "top">Go to example!</a>
An iframe such as youtube has these links as reccomemdations when you pause:
<iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ">
</iframe>
Is there any way to redirect these links to stay inside of the iframe, instead of creating a new popup?
|
[
"You can use the window.onclick event and check the target attribute of the event to determine if the clicked element is a link. If it is, you can use the event.preventDefault() method to prevent the default action (opening the link in a new window) and instead set the iframe's src attribute to the link's href value using the event.target.href property.\nHere is an example of how this could be implemented:\n// Get the iframe element\nconst iframe = document.querySelector('iframe');\n\n// Add an onclick event listener to the window\nwindow.onclick = (event) => {\n // Check if the clicked element is a link\n if (event.target.tagName === 'A') {\n // Prevent the default action (opening the link in a new window)\n event.preventDefault();\n\n // Set the iframe's src attribute to the link's href value\n iframe.src = event.target.href;\n }\n};\n\nIt is important to note that this solution will only work if the iframe's content is on the same domain as the parent page, as it would be a security risk to allow links from other domains to be opened in the iframe. If the content of the iframe is on a different domain, you will need to use a different solution, such as using the postMessage method to communicate between the parent page and the iframe.\n"
] |
[
0
] |
[] |
[] |
[
"html",
"hyperlink",
"iframe",
"javascript",
"redirect"
] |
stackoverflow_0074670685_html_hyperlink_iframe_javascript_redirect.txt
|
Q:
How to CI/CD deploy static Dockerized React build files to S3
I currently have a React application that I have a AWS CodePipeline set up for that does the following.
Detect changes in GitHub repository
Build the "build" files (with CodeBuild) using buildspec.yaml file
Push "build" files to S3 bucket
The S3 bucket is configured to serve the static files to my domain.
This setup is great because it's cheap, I don't need to have an EC2 server always up and running serving these static files, which is completely unnecessary.
Recently however I've Dockerized this application, which is fantastic for me when I'm working on it from different machines.
However now that it's Dockerized it seems like it would be a better idea to have a docker container build the "build" files and push them to the S3 bucket, to ensure that the files being built on my machine are identical to the ones being pushed to the S3 Bucket.
Ideally I would like to have this all be automated when I push to the repo like it currently is.
I've seen a lot of tutorials about how to automate the creation of docker images getting pushed to AWS ECR and then using ECS (Fargate) to run the container. However to me this is just the same thing as running my app on an EC2 server... why do I want to do all this and then have a container continuously running on a server? Now it would just be a ECS server...
So what I am asking is, how can I create an automated CI/CD pipeline that builds the static files using a docker container, and then pushes them to S3, as I currently have it?
Here is current CodeBuild buildspec.yaml file for reference
version: 0.2
phases:
install:
runtime-versions:
nodejs: 12
commands:
# install yarn
- npm install yarn
# install dependencies
- yarn
# so that build commands work
- yarn add eslint-config-react-app
build:
commands:
# run build script
- yarn build
artifacts:
# include all files required to run application
# we include only the static build files
files:
- '**/*'
base-directory: 'build'
A:
To automate the build process of your Dockerized React application, you can use the same AWS CodePipeline you currently have set up, but you will need to make some changes to the CodeBuild project to use a Docker build environment instead of the default one.
To do this, you will need to first create a Dockerfile for your React application that will be used to build the Docker image for your application. This Dockerfile should include all the necessary instructions for building your application, such as copying the source code into the image and installing any dependencies.
Once you have created the Dockerfile, you can update your buildspec.yaml file to use a Docker build environment and specify the Dockerfile to be used. The updated buildspec.yaml file might look something like this:
version: 0.2
phases:
install:
runtime-version:
docker: 19
commands:
# build the Docker image for the application
- docker build -t my-react-app:latest -f Dockerfile .
build:
commands:
# run the Docker container with the built image to build the static files
- docker run my-react-app:latest yarn build
artifacts:
files:
- '**/*'
base-directory: 'build'
In this example, the build phase will build the Docker image for your application using the instructions in the Dockerfile, and then run the container to build the static files for your React application.
Once you have updated your buildspec.yaml file, you can commit the changes to your GitHub repository and the CodePipeline will automatically detect the changes and run the updated build process using the Docker build environment. This will ensure that the static files built by the Docker container are identical to the ones pushed to the S3 bucket.
It is important to note that in order to use a Docker build environment in CodeBuild, you will need to use a build image that includes the Docker runtime, such as the aws/codebuild/standard:4.0 image. You can specify the build image to use in the CodeBuild project settings.
|
How to CI/CD deploy static Dockerized React build files to S3
|
I currently have a React application that I have a AWS CodePipeline set up for that does the following.
Detect changes in GitHub repository
Build the "build" files (with CodeBuild) using buildspec.yaml file
Push "build" files to S3 bucket
The S3 bucket is configured to serve the static files to my domain.
This setup is great because it's cheap, I don't need to have an EC2 server always up and running serving these static files, which is completely unnecessary.
Recently however I've Dockerized this application, which is fantastic for me when I'm working on it from different machines.
However now that it's Dockerized it seems like it would be a better idea to have a docker container build the "build" files and push them to the S3 bucket, to ensure that the files being built on my machine are identical to the ones being pushed to the S3 Bucket.
Ideally I would like to have this all be automated when I push to the repo like it currently is.
I've seen a lot of tutorials about how to automate the creation of docker images getting pushed to AWS ECR and then using ECS (Fargate) to run the container. However to me this is just the same thing as running my app on an EC2 server... why do I want to do all this and then have a container continuously running on a server? Now it would just be a ECS server...
So what I am asking is, how can I create an automated CI/CD pipeline that builds the static files using a docker container, and then pushes them to S3, as I currently have it?
Here is current CodeBuild buildspec.yaml file for reference
version: 0.2
phases:
install:
runtime-versions:
nodejs: 12
commands:
# install yarn
- npm install yarn
# install dependencies
- yarn
# so that build commands work
- yarn add eslint-config-react-app
build:
commands:
# run build script
- yarn build
artifacts:
# include all files required to run application
# we include only the static build files
files:
- '**/*'
base-directory: 'build'
|
[
"To automate the build process of your Dockerized React application, you can use the same AWS CodePipeline you currently have set up, but you will need to make some changes to the CodeBuild project to use a Docker build environment instead of the default one.\nTo do this, you will need to first create a Dockerfile for your React application that will be used to build the Docker image for your application. This Dockerfile should include all the necessary instructions for building your application, such as copying the source code into the image and installing any dependencies.\nOnce you have created the Dockerfile, you can update your buildspec.yaml file to use a Docker build environment and specify the Dockerfile to be used. The updated buildspec.yaml file might look something like this:\nversion: 0.2\n\nphases:\n install:\n runtime-version:\n docker: 19\n\n commands:\n # build the Docker image for the application\n - docker build -t my-react-app:latest -f Dockerfile .\n\nbuild:\n commands:\n # run the Docker container with the built image to build the static files\n - docker run my-react-app:latest yarn build\n\nartifacts:\n files:\n - '**/*'\n base-directory: 'build'\n\nIn this example, the build phase will build the Docker image for your application using the instructions in the Dockerfile, and then run the container to build the static files for your React application.\nOnce you have updated your buildspec.yaml file, you can commit the changes to your GitHub repository and the CodePipeline will automatically detect the changes and run the updated build process using the Docker build environment. This will ensure that the static files built by the Docker container are identical to the ones pushed to the S3 bucket.\nIt is important to note that in order to use a Docker build environment in CodeBuild, you will need to use a build image that includes the Docker runtime, such as the aws/codebuild/standard:4.0 image. You can specify the build image to use in the CodeBuild project settings.\n"
] |
[
2
] |
[] |
[] |
[
"amazon_web_services",
"aws_codepipeline",
"continuous_integration",
"devops",
"docker"
] |
stackoverflow_0074670743_amazon_web_services_aws_codepipeline_continuous_integration_devops_docker.txt
|
Q:
The message event is deprecated use messageCreate instead
I am trying to update my discord bot from v12 to v13, the bot is running and all commands are loaded in the console, but this notification appears at the bottom and none of my commands are working. As an example, I shared a command with you, is there something missing or need to fix? I would be glad if you help.
const Discord = require('discord.js');
const ayarlar = require('../ayarlar.json');
exports.run = async (client, messageCreate, args) => {
let target = message.mentions.users.first() || message.author;
messageCreate.channel.send(new Discord.MessageEmbed()
.setColor(`${ayarlar.embedcolor}`)
.setAuthor(target.tag, target.displayAvatarURL({ dynamic: true }))
.setTitle('Avatar')
.setImage(target.displayAvatarURL({ dynamic: true, size: 512 })));
};
exports.conf = {
enabled: true,
guildOnly: false,
aliases: ['av'],
permLevel: 0
};
exports.help = {
name: 'avatar'
};
head of main.js
const {Client, Collection, Intents} = require("discord.js");
const chalk = require("chalk");
const ayarlar = require("./ayarlar.json");
var Jimp = require("jimp");
const fs = require("fs");
const http = require("http");
const express = require("express");
const db = require("quick.db");
const ms = require("ms");
const client = new Client({intents: [3805]});
const Discord = require('discord.js');
require("dotenv").config;
module.exports = client;
client.discord = Discord;
client.commands = new Collection();
client.slashCommands = new Collection();
client.config = require('./ayarlar.json');
A:
Try destructuring the message property from the messageCreate event:
const Discord = require('discord.js');
const ayarlar = require('../ayarlar.json');
exports.run = async (client, messageCreate, args) => {
// destructure the message property from the messageCreate event
const { message } = messageCreate;
let target = message.mentions.users.first() || message.author;
messageCreate.channel.send(new Discord.MessageEmbed()
.setColor(`${ayarlar.embedcolor}`)
.setAuthor(target.tag, target.displayAvatarURL({ dynamic: true }))
.setTitle('Avatar')
.setImage(target.displayAvatarURL({ dynamic: true, size: 512 })));
};
The other exports, exports.conf & exports.help, remain the same.
|
The message event is deprecated use messageCreate instead
|
I am trying to update my discord bot from v12 to v13, the bot is running and all commands are loaded in the console, but this notification appears at the bottom and none of my commands are working. As an example, I shared a command with you, is there something missing or need to fix? I would be glad if you help.
const Discord = require('discord.js');
const ayarlar = require('../ayarlar.json');
exports.run = async (client, messageCreate, args) => {
let target = message.mentions.users.first() || message.author;
messageCreate.channel.send(new Discord.MessageEmbed()
.setColor(`${ayarlar.embedcolor}`)
.setAuthor(target.tag, target.displayAvatarURL({ dynamic: true }))
.setTitle('Avatar')
.setImage(target.displayAvatarURL({ dynamic: true, size: 512 })));
};
exports.conf = {
enabled: true,
guildOnly: false,
aliases: ['av'],
permLevel: 0
};
exports.help = {
name: 'avatar'
};
head of main.js
const {Client, Collection, Intents} = require("discord.js");
const chalk = require("chalk");
const ayarlar = require("./ayarlar.json");
var Jimp = require("jimp");
const fs = require("fs");
const http = require("http");
const express = require("express");
const db = require("quick.db");
const ms = require("ms");
const client = new Client({intents: [3805]});
const Discord = require('discord.js');
require("dotenv").config;
module.exports = client;
client.discord = Discord;
client.commands = new Collection();
client.slashCommands = new Collection();
client.config = require('./ayarlar.json');
|
[
"Try destructuring the message property from the messageCreate event:\nconst Discord = require('discord.js');\nconst ayarlar = require('../ayarlar.json');\n\nexports.run = async (client, messageCreate, args) => {\n // destructure the message property from the messageCreate event\n const { message } = messageCreate;\n\n let target = message.mentions.users.first() || message.author;\n messageCreate.channel.send(new Discord.MessageEmbed()\n .setColor(`${ayarlar.embedcolor}`)\n .setAuthor(target.tag, target.displayAvatarURL({ dynamic: true }))\n .setTitle('Avatar')\n .setImage(target.displayAvatarURL({ dynamic: true, size: 512 })));\n}; \n\nThe other exports, exports.conf & exports.help, remain the same.\n"
] |
[
0
] |
[] |
[] |
[
"discord",
"discord.js",
"javascript",
"node.js",
"npm"
] |
stackoverflow_0074667130_discord_discord.js_javascript_node.js_npm.txt
|
Q:
How to check my statement but like individually if it is coded as one
This is a function i am currently using for registering of user account in php.
function checkpost($input, $mandatory, $pattern) {
$inputvalue=$_POST[$input];
if (empty($inputvalue)) {
printmessage("$input field is empty");
if ($mandatory) return false;
else printmessage("but $input is not mandatory");
}
if (strlen($pattern) > 0) { //Checks for Input Validation
$ismatch=preg_match($pattern,$inputvalue);
if (!$ismatch || $ismatch==0) { // If is not match or is match = 0
printmessage("$input field wrong format <br>");
if ($mandatory) return false;
// header("location: registerform.php");
}
}
return true;
}
$checkall=true;
$checkall=$checkall && checkpost("name",true,""); //Mandatory
$checkall=$checkall && checkpost("email",true,"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i");
$checkall=$checkall && checkpost("password",true,"/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/");
$checkall=$checkall && checkpost("nric",true,""); //Mandatory
$checkall=$checkall && checkpost("mobile",true,"");
$checkall=$checkall && checkpost("address",true,"");
I tried doing this way of method to check for the statement I have about but I am unsure how can i check like individually like email, password,nric. Is there something wrong with my ifelse cause when I do
// if (!$checkall) { The default error
// printmessage("Error checking inputs<br>Please return to the registration form");
// die();
// }
This will work but I want to check each individual field and print it out. Please help me I'm struggling right now
This is the one I tried but the regex statement suddenly does not work and it will print out the wrong echo statement even if the email format is correct. Seeking help please help me thank you in advance
if (!$checkall=$checkall && checkpost("email",true,"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i")) {
echo "Invalid email";
die();
}
elseif (!$checkall && checkpost("password",true,"")) {
echo "Invalid password";
die();
}
A:
You could reorder your code for some prettier logic by wrapping the validation into a try/catch block. This will validate each entry, but throw an exception on the first error. When one happens the helper variable $hasErrors is set to true. So you know after validation if any one failed or not.
$hasErrors = false;
try {
if (!checkpost("name", true, "")) throw new Exception("Name is missing");
if (!checkpost("email", true, "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i")) throw new Exception("Wrong email format");
if (!checkpost("password", true, "/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/")) throw new Exception("Password insecure");
if (!checkpost("nric", true, "")) throw new Exception("Nric?");;
if (!checkpost("mobile", true, "")) throw new Exception("Mobile missing");
if (!checkpost("address", true, "")) throw new Exception("Address missing");
} catch (Exception $e) {
$hasErrors = true;
echo "Error: " . $e->getMessage();
}
if (!$hasErrors) {
echo "Success";
}
Note: You don't need the message for exception at all or print it! I've added it for demonstration purpose.
|
How to check my statement but like individually if it is coded as one
|
This is a function i am currently using for registering of user account in php.
function checkpost($input, $mandatory, $pattern) {
$inputvalue=$_POST[$input];
if (empty($inputvalue)) {
printmessage("$input field is empty");
if ($mandatory) return false;
else printmessage("but $input is not mandatory");
}
if (strlen($pattern) > 0) { //Checks for Input Validation
$ismatch=preg_match($pattern,$inputvalue);
if (!$ismatch || $ismatch==0) { // If is not match or is match = 0
printmessage("$input field wrong format <br>");
if ($mandatory) return false;
// header("location: registerform.php");
}
}
return true;
}
$checkall=true;
$checkall=$checkall && checkpost("name",true,""); //Mandatory
$checkall=$checkall && checkpost("email",true,"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i");
$checkall=$checkall && checkpost("password",true,"/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/");
$checkall=$checkall && checkpost("nric",true,""); //Mandatory
$checkall=$checkall && checkpost("mobile",true,"");
$checkall=$checkall && checkpost("address",true,"");
I tried doing this way of method to check for the statement I have about but I am unsure how can i check like individually like email, password,nric. Is there something wrong with my ifelse cause when I do
// if (!$checkall) { The default error
// printmessage("Error checking inputs<br>Please return to the registration form");
// die();
// }
This will work but I want to check each individual field and print it out. Please help me I'm struggling right now
This is the one I tried but the regex statement suddenly does not work and it will print out the wrong echo statement even if the email format is correct. Seeking help please help me thank you in advance
if (!$checkall=$checkall && checkpost("email",true,"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i")) {
echo "Invalid email";
die();
}
elseif (!$checkall && checkpost("password",true,"")) {
echo "Invalid password";
die();
}
|
[
"You could reorder your code for some prettier logic by wrapping the validation into a try/catch block. This will validate each entry, but throw an exception on the first error. When one happens the helper variable $hasErrors is set to true. So you know after validation if any one failed or not.\n$hasErrors = false;\ntry {\n if (!checkpost(\"name\", true, \"\")) throw new Exception(\"Name is missing\");\n if (!checkpost(\"email\", true, \"/^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,})$/i\")) throw new Exception(\"Wrong email format\");\n if (!checkpost(\"password\", true, \"/^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$/\")) throw new Exception(\"Password insecure\");\n if (!checkpost(\"nric\", true, \"\")) throw new Exception(\"Nric?\");;\n if (!checkpost(\"mobile\", true, \"\")) throw new Exception(\"Mobile missing\");\n if (!checkpost(\"address\", true, \"\")) throw new Exception(\"Address missing\");\n} catch (Exception $e) {\n $hasErrors = true;\n echo \"Error: \" . $e->getMessage();\n}\n\nif (!$hasErrors) {\n echo \"Success\";\n}\n\nNote: You don't need the message for exception at all or print it! I've added it for demonstration purpose.\n"
] |
[
0
] |
[] |
[] |
[
"html",
"if_statement",
"php"
] |
stackoverflow_0074670377_html_if_statement_php.txt
|
Q:
Is there a way to connect NextJS app on my phone trough local network in development like Create React App does?
It does not provide a local network URL like CRA.
A:
The server is accessible on the local network, as long as the network is configured properly (and doesn't have something like client isolation enabled). All you need to do is find out which IP address your network's router is allocating to you. On Windows, this can be done by checking the results of ipconfig. On Linux, you can use ip addr. Then, when you want to access the app from another device, just use the IP found above followed by the port set in next.js.
For example, I have a machine whose network IP address is 192.168.1.2. On that machine, I have a Next app running on port 56381.
ready - started server on 0.0.0.0:56381, url: http://localhost:56381
I can access it on my phone by going to 192.168.1.2:56381.
|
Is there a way to connect NextJS app on my phone trough local network in development like Create React App does?
|
It does not provide a local network URL like CRA.
|
[
"The server is accessible on the local network, as long as the network is configured properly (and doesn't have something like client isolation enabled). All you need to do is find out which IP address your network's router is allocating to you. On Windows, this can be done by checking the results of ipconfig. On Linux, you can use ip addr. Then, when you want to access the app from another device, just use the IP found above followed by the port set in next.js.\nFor example, I have a machine whose network IP address is 192.168.1.2. On that machine, I have a Next app running on port 56381.\n\nready - started server on 0.0.0.0:56381, url: http://localhost:56381\n\n\nI can access it on my phone by going to 192.168.1.2:56381.\n"
] |
[
0
] |
[] |
[] |
[
"create_react_app",
"next.js",
"reactjs"
] |
stackoverflow_0074670714_create_react_app_next.js_reactjs.txt
|
Q:
How can I make the user input another password if it's not strong enough?
Right now with what I have, even if the password meets all the criteria it prints "Weak password try again!". It allows for another user input but it doesn't break and print "Strong password" if it is strong.
Code:
if (l>= and u>=1 and p>=1 and d>=1 and l+u+p+d==len(s)):
break
print("Strong password")
else:
print(input("Weak password, try again: "))
A:
while True:
passwordName = input("Password ? ")
if (l>= and u>=1 and p>=1 and d>=1 and l+u+p+d==len(s)):
print("Strong password")
break
else:
print("Weak password, try again")
|
How can I make the user input another password if it's not strong enough?
|
Right now with what I have, even if the password meets all the criteria it prints "Weak password try again!". It allows for another user input but it doesn't break and print "Strong password" if it is strong.
Code:
if (l>= and u>=1 and p>=1 and d>=1 and l+u+p+d==len(s)):
break
print("Strong password")
else:
print(input("Weak password, try again: "))
|
[
"while True:\n passwordName = input(\"Password ? \")\n if (l>= and u>=1 and p>=1 and d>=1 and l+u+p+d==len(s)):\n print(\"Strong password\")\n break\n\n else:\n print(\"Weak password, try again\")\n\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074670610_python.txt
|
Q:
Custom Sorting gglot2 in python
I am working on ggplt visualization, which plotting countries total expenditure from the highest to the lowest. Since there are many small values, I am aggregating several small categories into the "other" category. I am having trouble finding a way to move the "Other" Category to the end and keeping the rest sorted from in descending order
`
ggplot(df_sorted, aes(x = 'reorder(customer_country, Total_Expenditure, fun=sum)', y = 'Total_Expenditure', fill='Total_Expenditure'))\
+ geom_bar(stat="identity")\
+ scale_x_discrete()\
+ coord_flip()\
+scale_fill_cmap(cmap_name="RdYlGn")
`
enter image description here
Have Category Other at the bottom of the bar chart
A:
In general, you can custom sort your dataframe outside ggplot (just using some pandas) and no reordering inside the plot aesthetics will be necessary.
The code below demonstrates this for the diamonds dataset that comes with plotline, where one factor level ('Premium') is moved to the bottom while all others remain sorted.
Side note: Please include (at least a subset) of your actual dataframe in your next question for a fully reproducible example, or demonstrate the question/problem with a dataset provided by one of the libraries.
custom dataframe sorting
there is probably a more elegant way, but the important
from plotnine.data import diamonds
import pandas as pd
# this takes the job of reorder(.., fun=sum) and creates a sorted list of the factor
df = diamonds.groupby('cut', as_index=False).aggregate({'carat': 'sum'})
sorted_levels = df.sort_values('carat')['cut']
# custom reordering of the factor level of interest,
# here 'Premium' is moved to one end while the rest remains ordered
sorted_custom = ['Premium'] + [l for l in sorted_levels if not l == 'Premium']
# reorder dataframe based on these factor levels
df['cut'] = pd.Categorical(df['cut'], sorted_custom)
df = df.sort_values('cut')
plot (without further sorting)
from plotnine import ggplot, aes, geom_bar, scale_x_discrete, coord_flip, scale_fill_cmap
(
ggplot(df, aes(x = 'cut', y = 'carat', fill='carat'))\
+ geom_bar(stat='identity')\
+ scale_x_discrete()\
+ coord_flip()\
+ scale_fill_cmap(cmap_name="RdYlGn")
)
|
Custom Sorting gglot2 in python
|
I am working on ggplt visualization, which plotting countries total expenditure from the highest to the lowest. Since there are many small values, I am aggregating several small categories into the "other" category. I am having trouble finding a way to move the "Other" Category to the end and keeping the rest sorted from in descending order
`
ggplot(df_sorted, aes(x = 'reorder(customer_country, Total_Expenditure, fun=sum)', y = 'Total_Expenditure', fill='Total_Expenditure'))\
+ geom_bar(stat="identity")\
+ scale_x_discrete()\
+ coord_flip()\
+scale_fill_cmap(cmap_name="RdYlGn")
`
enter image description here
Have Category Other at the bottom of the bar chart
|
[
"In general, you can custom sort your dataframe outside ggplot (just using some pandas) and no reordering inside the plot aesthetics will be necessary.\nThe code below demonstrates this for the diamonds dataset that comes with plotline, where one factor level ('Premium') is moved to the bottom while all others remain sorted.\nSide note: Please include (at least a subset) of your actual dataframe in your next question for a fully reproducible example, or demonstrate the question/problem with a dataset provided by one of the libraries.\ncustom dataframe sorting\nthere is probably a more elegant way, but the important\nfrom plotnine.data import diamonds\nimport pandas as pd\n\n# this takes the job of reorder(.., fun=sum) and creates a sorted list of the factor\ndf = diamonds.groupby('cut', as_index=False).aggregate({'carat': 'sum'})\nsorted_levels = df.sort_values('carat')['cut']\n\n# custom reordering of the factor level of interest, \n# here 'Premium' is moved to one end while the rest remains ordered\nsorted_custom = ['Premium'] + [l for l in sorted_levels if not l == 'Premium']\n\n# reorder dataframe based on these factor levels\ndf['cut'] = pd.Categorical(df['cut'], sorted_custom)\ndf = df.sort_values('cut')\n\nplot (without further sorting)\n\nfrom plotnine import ggplot, aes, geom_bar, scale_x_discrete, coord_flip, scale_fill_cmap\n(\n ggplot(df, aes(x = 'cut', y = 'carat', fill='carat'))\\\n + geom_bar(stat='identity')\\\n + scale_x_discrete()\\\n + coord_flip()\\\n + scale_fill_cmap(cmap_name=\"RdYlGn\")\n)\n\n\n"
] |
[
0
] |
[] |
[] |
[
"ggplot2",
"plotnine",
"python"
] |
stackoverflow_0074668827_ggplot2_plotnine_python.txt
|
Q:
meaning of double star in pandas dataframe construstor
I want to know what is the meaning of double star in the following pandas dataframe constructor '
If i delete it, then complier raises an error:
Mixing dicts with non-Series may lead to ambiguous ordering.
bus_summary = pd.DataFrame(**{'columns': ['business id column', 'latitude', 'longitude'],
'data': {'business id column': {'50%': 75685.0, 'max': 102705.0, 'min': 19.0},
'latitude': {'50%': -9999.0, 'max': 37.824494, 'min': -9999.0},
'longitude': {'50%': -9999.0,
'max': 0.0,
'min': -9999.0}},
'index': ['min', '50%', 'max']})
I want to know what is the meaning of double star in the following pandas dataframe constructor
A:
The double star (**) is used in the pandas dataframe constructor to indicate that the argument being passed is a dictionary containing key-value pairs. This is commonly used as a shorthand way to pass a dictionary as an argument to a function or method. In this case, the double star allows the dictionary containing the data for the dataframe to be passed as an argument to the pandas dataframe constructor without having to explicitly unpack the dictionary.
|
meaning of double star in pandas dataframe construstor
|
I want to know what is the meaning of double star in the following pandas dataframe constructor '
If i delete it, then complier raises an error:
Mixing dicts with non-Series may lead to ambiguous ordering.
bus_summary = pd.DataFrame(**{'columns': ['business id column', 'latitude', 'longitude'],
'data': {'business id column': {'50%': 75685.0, 'max': 102705.0, 'min': 19.0},
'latitude': {'50%': -9999.0, 'max': 37.824494, 'min': -9999.0},
'longitude': {'50%': -9999.0,
'max': 0.0,
'min': -9999.0}},
'index': ['min', '50%', 'max']})
I want to know what is the meaning of double star in the following pandas dataframe constructor
|
[
"The double star (**) is used in the pandas dataframe constructor to indicate that the argument being passed is a dictionary containing key-value pairs. This is commonly used as a shorthand way to pass a dictionary as an argument to a function or method. In this case, the double star allows the dictionary containing the data for the dataframe to be passed as an argument to the pandas dataframe constructor without having to explicitly unpack the dictionary.\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074670749_pandas_python.txt
|
Q:
Matplotlib in Rmarkdown/RStudio fails when calling LaTeX on `\$` with Anaconda
Problem description
I am having to use Anaconda on Windows, and am trying to write an RMarkdown document, knitted into a pdf, where within the RMarkdown I am using some Python snippets. However, when I try make matplotlib use LaTeX (with the rc.params) I find it does not render but hits an error I cannot understand nor fix. The offending lines are
mpl.rcParams.update({"text.usetex": True})
...
plt.title(r'Some Latex with symbol \$')
It is LaTeX trying to interpret the \$ which is throwing issues. As far as I can tell this should be correctly escaped. If I remove the \$ everything works as expected, (or if I replace it with e.g. $e=mc^2$).
The error message
Quitting from lines 31-34 (example.Rmd)
Error in py_call_impl(callable, dots$args, dots$keywords) :
RuntimeError: Evaluation error: KeyError: b'tcrm1200'
Detailed traceback:
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\pyplot.py", line 722, in savefig
res = fig.savefig(*args, **kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\figure.py", line 2180, in savefig
self.canvas.print_figure(fname, **kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 88, in print_figure
super().print_figure(*args, **kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\backend_bases.py", line 2082, in print_figure
**kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\backends\backend_pdf.py", line 2503, in print_pdf
self.figure.draw(renderer)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\figure.py"
Calls: <Anonymous> ... py_capture_output -> force -> <Anonymous> -> py_call_impl
Execution halted
MWE
The following is a .Rmd file running on Rstudio 1.2.5001 (should be using Python 3.7 with Conda3, but I'm not so sure how to dig out the specifics on Windows...).
---
output: pdf_document
---
```{r}
library(reticulate)
```
```{python, echo=FALSE, include=FALSE}
import os
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = r'C:\Users\Harry\Anaconda3\Library\plugins\platforms'
```
```{python, echo=FALSE, include=FALSE}
import matplotlib as mpl
import matplotlib.pyplot as plt
# Setting some default plotting features to give nicer plots. This can be commented out for beginners.
rc_fonts = {
"text.usetex": True,
'text.latex.preview': True, # Gives correct legend alignment.
'mathtext.default': 'regular',
'figure.figsize': (6, 4),
"font.family": "serif",
"font.serif": "computer modern roman",
}
mpl.rcParams.update(rc_fonts)
```
```{python}
plt.plot([0, 2, 1, 4])
plt.title(r'Some Latex with symbol \$')
plt.show()
```
A:
It looks like the error is occurring when matplotlib is trying to save the figure as a pdf. The specific error is a KeyError with the key b'tcrm1200', which is related to the font matplotlib is trying to use for rendering the LaTeX text. The b prefix indicates that the key is a byte string, rather than a regular string.
One potential solution is to explicitly set the font to use for rendering the LaTeX text. You can do this by adding the following lines before the mpl.rcParams.update(rc_fonts) call:
mpl.rcParams['text.latex.preamble'] = r'\usepackage{tgheros}' # Use helvetica font
mpl.rcParams['font.family'] = 'sans-serif' # Use sans-serif font
mpl.rcParams['font.sans-serif'] = 'Helvetica'
This should solve the KeyError by explicitly setting the font matplotlib should use for rendering the LaTeX text.
|
Matplotlib in Rmarkdown/RStudio fails when calling LaTeX on `\$` with Anaconda
|
Problem description
I am having to use Anaconda on Windows, and am trying to write an RMarkdown document, knitted into a pdf, where within the RMarkdown I am using some Python snippets. However, when I try make matplotlib use LaTeX (with the rc.params) I find it does not render but hits an error I cannot understand nor fix. The offending lines are
mpl.rcParams.update({"text.usetex": True})
...
plt.title(r'Some Latex with symbol \$')
It is LaTeX trying to interpret the \$ which is throwing issues. As far as I can tell this should be correctly escaped. If I remove the \$ everything works as expected, (or if I replace it with e.g. $e=mc^2$).
The error message
Quitting from lines 31-34 (example.Rmd)
Error in py_call_impl(callable, dots$args, dots$keywords) :
RuntimeError: Evaluation error: KeyError: b'tcrm1200'
Detailed traceback:
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\pyplot.py", line 722, in savefig
res = fig.savefig(*args, **kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\figure.py", line 2180, in savefig
self.canvas.print_figure(fname, **kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 88, in print_figure
super().print_figure(*args, **kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\backend_bases.py", line 2082, in print_figure
**kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\backends\backend_pdf.py", line 2503, in print_pdf
self.figure.draw(renderer)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\figure.py"
Calls: <Anonymous> ... py_capture_output -> force -> <Anonymous> -> py_call_impl
Execution halted
MWE
The following is a .Rmd file running on Rstudio 1.2.5001 (should be using Python 3.7 with Conda3, but I'm not so sure how to dig out the specifics on Windows...).
---
output: pdf_document
---
```{r}
library(reticulate)
```
```{python, echo=FALSE, include=FALSE}
import os
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = r'C:\Users\Harry\Anaconda3\Library\plugins\platforms'
```
```{python, echo=FALSE, include=FALSE}
import matplotlib as mpl
import matplotlib.pyplot as plt
# Setting some default plotting features to give nicer plots. This can be commented out for beginners.
rc_fonts = {
"text.usetex": True,
'text.latex.preview': True, # Gives correct legend alignment.
'mathtext.default': 'regular',
'figure.figsize': (6, 4),
"font.family": "serif",
"font.serif": "computer modern roman",
}
mpl.rcParams.update(rc_fonts)
```
```{python}
plt.plot([0, 2, 1, 4])
plt.title(r'Some Latex with symbol \$')
plt.show()
```
|
[
"It looks like the error is occurring when matplotlib is trying to save the figure as a pdf. The specific error is a KeyError with the key b'tcrm1200', which is related to the font matplotlib is trying to use for rendering the LaTeX text. The b prefix indicates that the key is a byte string, rather than a regular string.\nOne potential solution is to explicitly set the font to use for rendering the LaTeX text. You can do this by adding the following lines before the mpl.rcParams.update(rc_fonts) call:\nmpl.rcParams['text.latex.preamble'] = r'\\usepackage{tgheros}' # Use helvetica font\nmpl.rcParams['font.family'] = 'sans-serif' # Use sans-serif font\nmpl.rcParams['font.sans-serif'] = 'Helvetica'\n\nThis should solve the KeyError by explicitly setting the font matplotlib should use for rendering the LaTeX text.\n"
] |
[
0
] |
[
"Just remove the backslash! The string is already protected in single quote format.\nplt.title(r'Some Latex with symbol $')\n\n",
"I think u should type in text in 'markdown' section of JupyterNotebook in Ananconda, type the python code in the 'codes' section of the notebook too and finally save it as PDF via LaTeX in the JupyterNotebook. This will solve your problems individually and give u the output I think u r looking for.\n"
] |
[
-2,
-4
] |
[
"latex",
"matplotlib",
"python",
"r",
"r_markdown"
] |
stackoverflow_0058502671_latex_matplotlib_python_r_r_markdown.txt
|
Q:
why I can't insert datagen in flink?
Flink SQL> CREATE TABLE sourceT (
> uuid varchar(20),
> name varchar(10),
> age int,
> ts timestamp(3),
> `partition` varchar(20)
> ) WITH (
> 'connector' = 'datagen',
> 'rows-per-second' = '1'
> );
[INFO] Execute statement succeed.
Flink SQL> create table t2(
> uuid varchar(20),
> name varchar(10),
> age int,
> ts timestamp(3),
> `partition` varchar(20)
> )
> with (
> 'connector' = 'hudi',
> 'path' = '/tmp/hudi_flink/t2',
> 'table.type' = 'MERGE_ON_READ'
> );
[INFO] Execute statement succeed.
Flink SQL> insert into t2 select * from sourceT;
[INFO] Submitting SQL update statement to the cluster...
2022-11-29 11:55:39,776 WARN org.apache.flink.yarn.configuration.YarnLogConfigUtil [] - The configuration directory ('/opt/module/flink-1.13.6/conf') already contains a LOG4J config file.If you want to use logback, then please delete or rename the log configuration file.
2022-11-29 11:55:40,018 INFO org.apache.hadoop.yarn.client.RMProxy [] - Connecting to ResourceManager at hadoop163/192.168.10.163:8032
2022-11-29 11:55:40,151 INFO org.apache.flink.yarn.YarnClusterDescriptor [] - No path for the flink jar passed. Using the location of class org.apache.flink.yarn.YarnClusterDescriptor to locate the jar
2022-11-29 11:55:40,224 INFO org.apache.flink.yarn.YarnClusterDescriptor [] - Found Web Interface hadoop163:45413 of application 'application_1669685396475_0006'.
[INFO] SQL update statement has been successfully submitted to the cluster:
Job ID: 9f2283c2f6d943c170068abe39747bc0
Flink SQL> select * from t2;
2022-11-29 11:55:57,226 INFO org.apache.hadoop.hdfs.protocol.datatransfer.sasl.SaslDataTransferClient [] - SASL encryption trust check: localHostTrusted = false, remoteHostTrusted = false
2022-11-29 11:55:57,516 INFO org.apache.hadoop.yarn.client.RMProxy [] - Connecting to ResourceManager at hadoop163/192.168.10.163:8032
2022-11-29 11:55:57,516 INFO org.apache.flink.yarn.YarnClusterDescriptor [] - No path for the flink jar passed. Using the location of class org.apache.flink.yarn.YarnClusterDescriptor to locate the jar
2022-11-29 11:55:57,520 INFO org.apache.flink.yarn.YarnClusterDescriptor [] - Found Web Interface hadoop163:45413 of application 'application_1669685396475_0006'.
[INFO] Result retrieval cancelled.
A:
Your query was submitted successfully to YARN.
You need to open the YARN UI to find any real cause for your query to get cancelled.
|
why I can't insert datagen in flink?
|
Flink SQL> CREATE TABLE sourceT (
> uuid varchar(20),
> name varchar(10),
> age int,
> ts timestamp(3),
> `partition` varchar(20)
> ) WITH (
> 'connector' = 'datagen',
> 'rows-per-second' = '1'
> );
[INFO] Execute statement succeed.
Flink SQL> create table t2(
> uuid varchar(20),
> name varchar(10),
> age int,
> ts timestamp(3),
> `partition` varchar(20)
> )
> with (
> 'connector' = 'hudi',
> 'path' = '/tmp/hudi_flink/t2',
> 'table.type' = 'MERGE_ON_READ'
> );
[INFO] Execute statement succeed.
Flink SQL> insert into t2 select * from sourceT;
[INFO] Submitting SQL update statement to the cluster...
2022-11-29 11:55:39,776 WARN org.apache.flink.yarn.configuration.YarnLogConfigUtil [] - The configuration directory ('/opt/module/flink-1.13.6/conf') already contains a LOG4J config file.If you want to use logback, then please delete or rename the log configuration file.
2022-11-29 11:55:40,018 INFO org.apache.hadoop.yarn.client.RMProxy [] - Connecting to ResourceManager at hadoop163/192.168.10.163:8032
2022-11-29 11:55:40,151 INFO org.apache.flink.yarn.YarnClusterDescriptor [] - No path for the flink jar passed. Using the location of class org.apache.flink.yarn.YarnClusterDescriptor to locate the jar
2022-11-29 11:55:40,224 INFO org.apache.flink.yarn.YarnClusterDescriptor [] - Found Web Interface hadoop163:45413 of application 'application_1669685396475_0006'.
[INFO] SQL update statement has been successfully submitted to the cluster:
Job ID: 9f2283c2f6d943c170068abe39747bc0
Flink SQL> select * from t2;
2022-11-29 11:55:57,226 INFO org.apache.hadoop.hdfs.protocol.datatransfer.sasl.SaslDataTransferClient [] - SASL encryption trust check: localHostTrusted = false, remoteHostTrusted = false
2022-11-29 11:55:57,516 INFO org.apache.hadoop.yarn.client.RMProxy [] - Connecting to ResourceManager at hadoop163/192.168.10.163:8032
2022-11-29 11:55:57,516 INFO org.apache.flink.yarn.YarnClusterDescriptor [] - No path for the flink jar passed. Using the location of class org.apache.flink.yarn.YarnClusterDescriptor to locate the jar
2022-11-29 11:55:57,520 INFO org.apache.flink.yarn.YarnClusterDescriptor [] - Found Web Interface hadoop163:45413 of application 'application_1669685396475_0006'.
[INFO] Result retrieval cancelled.
|
[
"Your query was submitted successfully to YARN.\nYou need to open the YARN UI to find any real cause for your query to get cancelled.\n"
] |
[
0
] |
[] |
[] |
[
"apache_flink",
"apache_hudi",
"hadoop_yarn",
"sql"
] |
stackoverflow_0074614259_apache_flink_apache_hudi_hadoop_yarn_sql.txt
|
Q:
Filling map with 2 keys from a string. Character and frequency c++
I am new to maps so an a little unsure of the best way to do this. This task is in relation to compression with huffman coding. Heres what I have.
#include <map>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
typedef map<char,int> huffmanMap;
void getFreq(string file, map<char, int> map)
{
map.clear();
for (string::iterator i = file.begin(); i != file.end(); ++i) {
++map[*i];
}
}
above is one method I found online but was unable to print anything
int main()
{
map<char, int> huffmanMap;
string fileline;
ifstream myfile;
myfile.open("text.txt",ios::out);
while(!myfile.eof()) {
getline(myfile, fileline); //get the line and put it in the fileline string
}
myfile.close();
I read in a from a text file to populate string fileline.
for (int i=0; i<fileline.length(); i++) {
char t = fileline[i];
huffmanMap[i]? huffmanMap[i]++ : huffmanMap[i]=1;
}
here is a second method I tried for populating the map, the char values are incorrect, symbols and smileyfaces..
getFreq(fileline,huffmanMap);
huffmanMap::iterator position;
for (position = huffmanMap.begin(); position != huffmanMap.end(); position++) {
cout << "key: \"" << position->first << endl;
cout << "value: " << position->second << endl;
}
This is how I tried to print map
system("pause");
return 0;
}
When I run my getFreq method the program crashes. I dont get any errors with either. With the second method the char values are nonsense.Note I have not had both methods running at the same time I just incuded them both to show what i have tried.
Any insight would be appreciated.Thanks. Be lenient im a beginner ;)
A:
Your code is all over the place, it's not very coherent so difficult to understand the flow.
Here are some low-lights:
This is wrong: myfile.open("text.txt",ios::out); - why would you open an input stream with out flag? it should simply be:
string fileline;
ifstream myfile("text.txt");
while(getline(myfile, fileline)) {
// now use fileline.
}
In the while loop, what you want to do is to iterate over the content and add it to your map? So now the code looks like:
string fileline;
ifstream myfile("text.txt");
while(getline(myfile, fileline)) {
getFreq(fileline, huffmanMap);
}
Next fix, this is wrong: you have a typedef and a variable of the same name!
typedef map<char,int> huffmanMap;
map<char, int> huffmanMap;
Use sensible naming
typedef map<char,int> huffmanMap_Type;
huffmanMap_Type huffmanMap;
Next fix, your getFreq method signature is wrong, you are passing the map by value (i.e. copy) rather than reference, hence you modification in the function is to a copy not the original!
wrong: void getFreq(string file, map<char, int> map)
correct: void getFreq(string file, huffmanMap_Type& map)
Next: why clear() in the above method? What if there is more than one line? No need for that surely?
That's enough for now, clean up your code and update your question if there are more issues.
A:
One fix and One improvement.
Fix is : make second parameter in getFreq reference:
void getFreq(string file, map<char, int> & map); //notice `&`
Improvement is : just write
huffmanMap[i]++;
instead of
huffmanMap[i]? huffmanMap[i]++ : huffmanMap[i]=1;
After all, by writing huffmanMap[i]? you're checking whether it's zero or not. If zero, then you make it one, which is same as huffmanMap[i]++.
A:
(An answer using C++ language features fom C++20.
But first, you were asking about getting getting the count (frequency) of letters in a text.
There is nearly a universal solution approach for this. We can use the std::unordered_map. It is described in the C++ reference here.
It is the std::unordered_maps very convienient index operator [] which makes counting very simple. This operator returns a reference to the value that is mapped to a key. So, it searched for the key and then returns the value. If the key does not exist, it inserts a new key/value pair and returns a reference to the value.
So, in any way, a reference to the value is returned. And this can be incremented. Example:
With a "std::unordered_map<char, int> mymap{};" and a text "aba", the follwoing can be done with the index operator:
mymap['a'] will search for an 'a' in the map. It is not found, so a new entry for 'a' with corresponding value=0 is created: The a reference to the value is returned. And, if we now increment that, we will increment the counter value. So, mymap['a']++, wiil insert a new gey/value pair 'a'/0, then increment it, resulting in 'a'/1
For 'b' the same as above will happen.
For the next 'a', an entry will be found in the map, an so a reference to the value (1) is returned. This is incremented and will then be 2
And so on and so on.
By using some modern language elements, a whole file can be read and its characters counted, with one simple for-loop:
for (const char c : rng::istream_view<char>(ifs)) counter[c]++;
Additional information:
For building a Huffmann tree, we can use a Min-Heap, which can be easily implemented with the existing std::priority_queue. Please read here abour it.
With 4 lines of code, the complete Huffmann tree can be build.
And the end, we put the result in a code book. Again a std::unordered_map and show the result to the user.
This could zhen be for example implemented like the below:
#include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>
#include <algorithm>
#include <queue>
#include <ranges>
#include <vector>
#include <utility>
namespace rng = std::ranges; // Abbreviation for the rnages namespace
using namespace std::string_literals; // And we want to use stding literals
// The Node of the Huffmann tree
struct Node {
char letter{ '\0' }; // The letter that we want to encode
std::size_t frequency{}; // The letters frequency in the source text
Node* left{}, *right{}; // The pointers to the children of this node
};
// Some abbreviations to reduce typing work and make code more readable
using Counter = std::unordered_map<char, std::size_t>;
struct Comp { bool operator ()(const Node* n1, const Node* n2) { return n1->frequency > n2->frequency; } };
using MinHeap = std::priority_queue<Node*, std::vector<Node*>, Comp>;
using CodeBook = std::unordered_map<char, std::string>;
// Traverse the Huffmann Tree and build the code book
void buildCodeBook(Node* root, std::string code, CodeBook& cb) {
if (root == nullptr) return;
if (root->letter != '\0') cb[root->letter] = code;
buildCodeBook(root->left, code + "0"s, cb);
buildCodeBook(root->right, code + "1"s, cb);
}
// Get the top most two Elements from the Min-Heap
std::pair<Node*, Node*> getFrom(MinHeap& mh) {
Node* left{ mh.top() }; mh.pop();
Node* right{ mh.top() }; mh.pop();
return { left, right };
}
// Demo function
int main() {
if (std::ifstream ifs{ "r:\\lorem.txt" }; ifs) {
// Define moste important resulting work products
Counter counter{};
MinHeap minHeap{};
CodeBook codeBook{};
// Read complete text from source file and count all characters ---------
for (const char c : rng::istream_view<char>(ifs)) counter[c]++;
// Build the Huffmann tree ----------------------------------------------
// First, create a min heap, based and the letters frequency
for (const auto& p : counter) minHeap.push(new Node{p.first, p.second});
// Compress the nodes
while (minHeap.size() > 1u) {
auto [left, right] = getFrom(minHeap);
minHeap.push(new Node{ '\0', left->frequency + right->frequency, left, right });
}
// And last but not least, generate the code book -----------------------
buildCodeBook(minHeap.top(), {}, codeBook);
// And, as debug output, show the code book -----------------------------
for (const auto& [letter, code] : codeBook) std::cout << '\'' << letter << "': " << code << '\n';
}
else std::cerr << "\n\n***Error: Could not open source text file\n\n";
}
|
Filling map with 2 keys from a string. Character and frequency c++
|
I am new to maps so an a little unsure of the best way to do this. This task is in relation to compression with huffman coding. Heres what I have.
#include <map>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
typedef map<char,int> huffmanMap;
void getFreq(string file, map<char, int> map)
{
map.clear();
for (string::iterator i = file.begin(); i != file.end(); ++i) {
++map[*i];
}
}
above is one method I found online but was unable to print anything
int main()
{
map<char, int> huffmanMap;
string fileline;
ifstream myfile;
myfile.open("text.txt",ios::out);
while(!myfile.eof()) {
getline(myfile, fileline); //get the line and put it in the fileline string
}
myfile.close();
I read in a from a text file to populate string fileline.
for (int i=0; i<fileline.length(); i++) {
char t = fileline[i];
huffmanMap[i]? huffmanMap[i]++ : huffmanMap[i]=1;
}
here is a second method I tried for populating the map, the char values are incorrect, symbols and smileyfaces..
getFreq(fileline,huffmanMap);
huffmanMap::iterator position;
for (position = huffmanMap.begin(); position != huffmanMap.end(); position++) {
cout << "key: \"" << position->first << endl;
cout << "value: " << position->second << endl;
}
This is how I tried to print map
system("pause");
return 0;
}
When I run my getFreq method the program crashes. I dont get any errors with either. With the second method the char values are nonsense.Note I have not had both methods running at the same time I just incuded them both to show what i have tried.
Any insight would be appreciated.Thanks. Be lenient im a beginner ;)
|
[
"Your code is all over the place, it's not very coherent so difficult to understand the flow.\nHere are some low-lights:\nThis is wrong: myfile.open(\"text.txt\",ios::out); - why would you open an input stream with out flag? it should simply be:\nstring fileline;\nifstream myfile(\"text.txt\"); \n\nwhile(getline(myfile, fileline)) {\n // now use fileline.\n}\n\nIn the while loop, what you want to do is to iterate over the content and add it to your map? So now the code looks like:\nstring fileline;\nifstream myfile(\"text.txt\"); \n\nwhile(getline(myfile, fileline)) {\n getFreq(fileline, huffmanMap);\n}\n\nNext fix, this is wrong: you have a typedef and a variable of the same name!\ntypedef map<char,int> huffmanMap;\n\nmap<char, int> huffmanMap;\n\nUse sensible naming\ntypedef map<char,int> huffmanMap_Type;\n\nhuffmanMap_Type huffmanMap;\n\nNext fix, your getFreq method signature is wrong, you are passing the map by value (i.e. copy) rather than reference, hence you modification in the function is to a copy not the original!\nwrong: void getFreq(string file, map<char, int> map)\ncorrect: void getFreq(string file, huffmanMap_Type& map)\nNext: why clear() in the above method? What if there is more than one line? No need for that surely?\nThat's enough for now, clean up your code and update your question if there are more issues.\n",
"One fix and One improvement.\nFix is : make second parameter in getFreq reference:\nvoid getFreq(string file, map<char, int> & map); //notice `&`\n\nImprovement is : just write\nhuffmanMap[i]++;\n\ninstead of \nhuffmanMap[i]? huffmanMap[i]++ : huffmanMap[i]=1;\n\nAfter all, by writing huffmanMap[i]? you're checking whether it's zero or not. If zero, then you make it one, which is same as huffmanMap[i]++.\n",
"(An answer using C++ language features fom C++20.\nBut first, you were asking about getting getting the count (frequency) of letters in a text.\nThere is nearly a universal solution approach for this. We can use the std::unordered_map. It is described in the C++ reference here.\nIt is the std::unordered_maps very convienient index operator [] which makes counting very simple. This operator returns a reference to the value that is mapped to a key. So, it searched for the key and then returns the value. If the key does not exist, it inserts a new key/value pair and returns a reference to the value.\nSo, in any way, a reference to the value is returned. And this can be incremented. Example:\nWith a \"std::unordered_map<char, int> mymap{};\" and a text \"aba\", the follwoing can be done with the index operator:\n\nmymap['a'] will search for an 'a' in the map. It is not found, so a new entry for 'a' with corresponding value=0 is created: The a reference to the value is returned. And, if we now increment that, we will increment the counter value. So, mymap['a']++, wiil insert a new gey/value pair 'a'/0, then increment it, resulting in 'a'/1\nFor 'b' the same as above will happen.\nFor the next 'a', an entry will be found in the map, an so a reference to the value (1) is returned. This is incremented and will then be 2\n\nAnd so on and so on.\nBy using some modern language elements, a whole file can be read and its characters counted, with one simple for-loop:\nfor (const char c : rng::istream_view<char>(ifs)) counter[c]++;\n\nAdditional information:\nFor building a Huffmann tree, we can use a Min-Heap, which can be easily implemented with the existing std::priority_queue. Please read here abour it.\nWith 4 lines of code, the complete Huffmann tree can be build.\nAnd the end, we put the result in a code book. Again a std::unordered_map and show the result to the user.\nThis could zhen be for example implemented like the below:\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <unordered_map>\n#include <algorithm>\n#include <queue>\n#include <ranges>\n#include <vector>\n#include <utility>\n\nnamespace rng = std::ranges; // Abbreviation for the rnages namespace\nusing namespace std::string_literals; // And we want to use stding literals\n\n// The Node of the Huffmann tree\nstruct Node { \n char letter{ '\\0' }; // The letter that we want to encode\n std::size_t frequency{}; // The letters frequency in the source text\n Node* left{}, *right{}; // The pointers to the children of this node\n};\n\n// Some abbreviations to reduce typing work and make code more readable\nusing Counter = std::unordered_map<char, std::size_t>;\nstruct Comp { bool operator ()(const Node* n1, const Node* n2) { return n1->frequency > n2->frequency; } }; \nusing MinHeap = std::priority_queue<Node*, std::vector<Node*>, Comp>;\nusing CodeBook = std::unordered_map<char, std::string>;\n\n// Traverse the Huffmann Tree and build the code book\nvoid buildCodeBook(Node* root, std::string code, CodeBook& cb) {\n if (root == nullptr) return;\n if (root->letter != '\\0') cb[root->letter] = code;\n buildCodeBook(root->left, code + \"0\"s, cb);\n buildCodeBook(root->right, code + \"1\"s, cb);\n}\n// Get the top most two Elements from the Min-Heap\nstd::pair<Node*, Node*> getFrom(MinHeap& mh) {\n Node* left{ mh.top() }; mh.pop();\n Node* right{ mh.top() }; mh.pop();\n return { left, right };\n}\n\n// Demo function\nint main() {\n if (std::ifstream ifs{ \"r:\\\\lorem.txt\" }; ifs) {\n\n // Define moste important resulting work products\n Counter counter{};\n MinHeap minHeap{};\n CodeBook codeBook{};\n\n // Read complete text from source file and count all characters ---------\n for (const char c : rng::istream_view<char>(ifs)) counter[c]++;\n\n // Build the Huffmann tree ----------------------------------------------\n // First, create a min heap, based and the letters frequency\n for (const auto& p : counter) minHeap.push(new Node{p.first, p.second});\n\n // Compress the nodes\n while (minHeap.size() > 1u) {\n auto [left, right] = getFrom(minHeap);\n minHeap.push(new Node{ '\\0', left->frequency + right->frequency, left, right });\n }\n // And last but not least, generate the code book -----------------------\n buildCodeBook(minHeap.top(), {}, codeBook);\n\n // And, as debug output, show the code book -----------------------------\n for (const auto& [letter, code] : codeBook) std::cout << '\\'' << letter << \"': \" << code << '\\n';\n }\n else std::cerr << \"\\n\\n***Error: Could not open source text file\\n\\n\";\n}\n\n"
] |
[
3,
2,
0
] |
[] |
[] |
[
"c++",
"huffman_code",
"maps"
] |
stackoverflow_0005272376_c++_huffman_code_maps.txt
|
Q:
How do I create a function that returns the histogram of a given data frame?
I need to create a function called histagram, the function receives 3 arguments: data frame, column name, and color number.
if all the arguments meet the criteria (valid data frame, color number an integer, and column name input must be character and the column must be of type numeric, the function returns a plot of histogram of the chosen column with the chosen color.
Also we need to change the "x - axis" so it will represent the column name input.
my script:
histagram = function(dataframe, columnName, colorNumber) {
if (!is.data.frame(dataframe)){
print("Please enter a Data frame structure")
} else if(!is.integer(as.integer(colorNumber))){
print("Enter a char columne name")
} else if(!is.character(columnName)){
print("Color must be a integer")
} else {
return(hist(dataframe$as.numeric(columnName), xlab = "columnName", col = as.integer(colorNumber)))
}
}
I tested the function to see if it worked:
histagram(dataframe = airdf, colorNumber = 7, columnName = "Temp")
I used the airquality data frame, which is a built-in data frame in R. airdf = airquality.
I'm getting an error message -
Error in dataframe$as.numeric(columnName) : attempt to apply non-function
Called from: hist(dataframe$as.numeric(columnName), xlab = "columnName", col = as.integer(colorNumber))
What needs to be changed in my code for it to work?
Many thanks!
A:
In addition to Martin Gal's comment, you should also remove the quotations around columnName under the xlab argument and consider adding something to the histogram title. If you don't specify the histogram title, it just says "Histogram of as.numeric(dataframe[, columnName])", which is a bit clunky.
data(airquality)
airdf <- airquality
histagram <- function(dataframe, columnName, colorNumber) {
if (!is.data.frame(dataframe)){
print("Please enter a Data frame structure")
} else if(!is.integer(as.integer(colorNumber))){
print("Enter a char columne name")
} else if(!is.character(columnName)){
print("Color must be a integer")
} else {
return(hist(as.numeric(dataframe[, columnName]), # <- from Martin Gal
main = paste("Histogram of", columnName), # <- dynamic title
xlab = columnName, # <- remove quotes here
col = as.integer(colorNumber)))
}
}
histagram(dataframe = airdf, colorNumber = 7, columnName = "Temp")
|
How do I create a function that returns the histogram of a given data frame?
|
I need to create a function called histagram, the function receives 3 arguments: data frame, column name, and color number.
if all the arguments meet the criteria (valid data frame, color number an integer, and column name input must be character and the column must be of type numeric, the function returns a plot of histogram of the chosen column with the chosen color.
Also we need to change the "x - axis" so it will represent the column name input.
my script:
histagram = function(dataframe, columnName, colorNumber) {
if (!is.data.frame(dataframe)){
print("Please enter a Data frame structure")
} else if(!is.integer(as.integer(colorNumber))){
print("Enter a char columne name")
} else if(!is.character(columnName)){
print("Color must be a integer")
} else {
return(hist(dataframe$as.numeric(columnName), xlab = "columnName", col = as.integer(colorNumber)))
}
}
I tested the function to see if it worked:
histagram(dataframe = airdf, colorNumber = 7, columnName = "Temp")
I used the airquality data frame, which is a built-in data frame in R. airdf = airquality.
I'm getting an error message -
Error in dataframe$as.numeric(columnName) : attempt to apply non-function
Called from: hist(dataframe$as.numeric(columnName), xlab = "columnName", col = as.integer(colorNumber))
What needs to be changed in my code for it to work?
Many thanks!
|
[
"In addition to Martin Gal's comment, you should also remove the quotations around columnName under the xlab argument and consider adding something to the histogram title. If you don't specify the histogram title, it just says \"Histogram of as.numeric(dataframe[, columnName])\", which is a bit clunky.\ndata(airquality)\nairdf <- airquality\n\nhistagram <- function(dataframe, columnName, colorNumber) {\n if (!is.data.frame(dataframe)){\n print(\"Please enter a Data frame structure\")\n } else if(!is.integer(as.integer(colorNumber))){\n print(\"Enter a char columne name\") \n } else if(!is.character(columnName)){\n print(\"Color must be a integer\") \n } else {\n return(hist(as.numeric(dataframe[, columnName]), # <- from Martin Gal\n main = paste(\"Histogram of\", columnName), # <- dynamic title \n xlab = columnName, # <- remove quotes here\n col = as.integer(colorNumber)))\n }\n} \n\nhistagram(dataframe = airdf, colorNumber = 7, columnName = \"Temp\")\n\n\n"
] |
[
0
] |
[] |
[] |
[
"function",
"r"
] |
stackoverflow_0074668734_function_r.txt
|
Q:
for loop runs once without accepting any input for array
The for loop in this code runs once without accepting input. Without the do-while loop, and the user input for the shopList array length, it runs without a problem.
import java.util.Arrays;
import java.util.Scanner;
/**
*
* @author cristian
*/
public class ShoppingList {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("How many items in this list?");
boolean okay;
do{
if (sc.hasNextDouble()) {
okay = true;
}else{
okay = false;
String word = sc.next(); //this may be the problem here
System.err.print( word + " is not a number\nTry again: ");
}
}while (!okay);
int l = sc.nextInt(); //the problem appeared the first time when I added this input
String[] shopList = new String[l]; //to give the length of this array
System.out.println("What do you want to buy?");
for (int x = 0 ; x < shopList.length; x++) { //this loop runs once without accepting input
System.out.print("Item: ");
String item = sc.nextLine();
if (item.equals("esc")) {
break;
}else{
shopList[x] = item;
//System.out.println(x);
}
}
System.out.println(Arrays.toString(shopList));
}
}
The problem first appeared when I added the "l" variable to the array length, to accept input from the user. Then I commented that out and added a do-while loop to make sure the input for the length was a number, which gave another problem.
What happens is that when both are not commented or if just the do-while loop is commented out, after I input the array length, it prints out "Item: Item:", it accepts one less item, and at the end it outputs the first item like I had just pressed enter, without writing anything.
If I instead comment out just the input for the array length the program waits for an input before running the loop, and uses that for the first item.
I think that for the do-while loop the problem is the "String word = sc.next();" but I'm not sure. As for the array length input, I have no idea. Can someone help please?
A:
It looks like the problem is with the nextLine() method in the for loop. When you call nextInt() to read the array length, it only reads the integer value and leaves the newline character in the input buffer. When the for loop starts and nextLine() is called, it reads this newline character and the loop continues without waiting for the user input.
To fix this, you can add a call to the nextLine() method after the call to nextInt() to consume the remaining newline character in the input buffer. For example:
int l = sc.nextInt();
sc.nextLine(); // consume remaining newline character
String[] shopList = new String[l];
Alternatively, you can change the for loop to use the nextInt() method instead of nextLine() to read the item index from the user. This will also consume the newline character in the input buffer. For example:
for (int x = 0 ; x < shopList.length; x++) {
System.out.print("Item: ");
int itemIndex = sc.nextInt();
if (itemIndex == "esc") {
break;
} else {
shopList[x] = itemIndex;
//System.out.println(x);
}
}
Hope this helps!
|
for loop runs once without accepting any input for array
|
The for loop in this code runs once without accepting input. Without the do-while loop, and the user input for the shopList array length, it runs without a problem.
import java.util.Arrays;
import java.util.Scanner;
/**
*
* @author cristian
*/
public class ShoppingList {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("How many items in this list?");
boolean okay;
do{
if (sc.hasNextDouble()) {
okay = true;
}else{
okay = false;
String word = sc.next(); //this may be the problem here
System.err.print( word + " is not a number\nTry again: ");
}
}while (!okay);
int l = sc.nextInt(); //the problem appeared the first time when I added this input
String[] shopList = new String[l]; //to give the length of this array
System.out.println("What do you want to buy?");
for (int x = 0 ; x < shopList.length; x++) { //this loop runs once without accepting input
System.out.print("Item: ");
String item = sc.nextLine();
if (item.equals("esc")) {
break;
}else{
shopList[x] = item;
//System.out.println(x);
}
}
System.out.println(Arrays.toString(shopList));
}
}
The problem first appeared when I added the "l" variable to the array length, to accept input from the user. Then I commented that out and added a do-while loop to make sure the input for the length was a number, which gave another problem.
What happens is that when both are not commented or if just the do-while loop is commented out, after I input the array length, it prints out "Item: Item:", it accepts one less item, and at the end it outputs the first item like I had just pressed enter, without writing anything.
If I instead comment out just the input for the array length the program waits for an input before running the loop, and uses that for the first item.
I think that for the do-while loop the problem is the "String word = sc.next();" but I'm not sure. As for the array length input, I have no idea. Can someone help please?
|
[
"It looks like the problem is with the nextLine() method in the for loop. When you call nextInt() to read the array length, it only reads the integer value and leaves the newline character in the input buffer. When the for loop starts and nextLine() is called, it reads this newline character and the loop continues without waiting for the user input.\nTo fix this, you can add a call to the nextLine() method after the call to nextInt() to consume the remaining newline character in the input buffer. For example:\nint l = sc.nextInt();\nsc.nextLine(); // consume remaining newline character\nString[] shopList = new String[l];\n\n\nAlternatively, you can change the for loop to use the nextInt() method instead of nextLine() to read the item index from the user. This will also consume the newline character in the input buffer. For example:\nfor (int x = 0 ; x < shopList.length; x++) {\n System.out.print(\"Item: \");\n int itemIndex = sc.nextInt();\n if (itemIndex == \"esc\") {\n break;\n } else {\n shopList[x] = itemIndex;\n //System.out.println(x);\n }\n}\n\nHope this helps!\n"
] |
[
1
] |
[] |
[] |
[
"arrays",
"java",
"loops",
"user_input"
] |
stackoverflow_0074670773_arrays_java_loops_user_input.txt
|
Q:
How to set the fill of SVGs that are imported from CDN?
I'm developing a website using Next JS and I want to display some SVG icons that I stored using Sanity. How do I display the SVG that I get from the Sanity CDN if I want to be able to dynamically change its fill color (e.g. change the color when the icon is hovered)? Or is this not possible?
Here's a summary of the my code, just to show you what I'm trying to do:
const [icon, setIcon] = useState('');
useEffect(() => {
const query = '*[_type == "socials"]'
client.fetch(query)
.then((data) => {
setIcon(urlFor(data.icon).width(24).url());
});
}, []);
<NextImage
useSkeleton
src={icon}
width='24'
height='24'
alt='name'
/>
Note: NextImage component above is basically a next/image component with a skeleton loading effect added to it.
With the code above, I was able to display the SVGs successfully, so no problem there. But, I can't seem to be able to add a hover effect to dynamically change the color of the displayed SVG. That's what I hope to get answers on.
Here's the displayed SVG icons:
I want to be able to change the color of those icons programmatically without having to change the SVGs that I already uploaded to Sanity.
A:
You can only style SVGs if they are inlined into the HTML, not through an <img> tag or external URL.
However, it might be possible to fetch the SVG markup from the image URL and inline it into the HTML. You'll need to get the original SVG URL (so you can't resize it with the .width() function).
Once you have the SVG URL (ends with .svg, going to the URL presents the SVG markup), you can fetch the data with fetch() or your preferred method, then use dangerouslySetInnerHTML to embed the returned SVG markup into a <div>. (Make sure you trust where the images are coming from, or you'll need to sanitize it.)
Styling the SVG will depend on how you're managing styles in your application and also the specific SVG, but you could do something like:
/* target svgs inside a div with class "inline-svg" */
div.inline-svg svg {
color: black;
width: 24px;
height: 24px;
}
div.inline-svg:hover svg {
color: red;
}
This will only work if your SVG has fill="currentColor" or stroke="currentColor" depending on how it's structured.
A:
If you are using Simple Icons, you can precise the color as mentioned in their GitHub page:
<img src="https://cdn.simpleicons.org/linkedin/00ccff99" width="32"/>
<img src="https://cdn.simpleicons.org/github/red" width="32"/>
Which gives:
Have fun!
|
How to set the fill of SVGs that are imported from CDN?
|
I'm developing a website using Next JS and I want to display some SVG icons that I stored using Sanity. How do I display the SVG that I get from the Sanity CDN if I want to be able to dynamically change its fill color (e.g. change the color when the icon is hovered)? Or is this not possible?
Here's a summary of the my code, just to show you what I'm trying to do:
const [icon, setIcon] = useState('');
useEffect(() => {
const query = '*[_type == "socials"]'
client.fetch(query)
.then((data) => {
setIcon(urlFor(data.icon).width(24).url());
});
}, []);
<NextImage
useSkeleton
src={icon}
width='24'
height='24'
alt='name'
/>
Note: NextImage component above is basically a next/image component with a skeleton loading effect added to it.
With the code above, I was able to display the SVGs successfully, so no problem there. But, I can't seem to be able to add a hover effect to dynamically change the color of the displayed SVG. That's what I hope to get answers on.
Here's the displayed SVG icons:
I want to be able to change the color of those icons programmatically without having to change the SVGs that I already uploaded to Sanity.
|
[
"You can only style SVGs if they are inlined into the HTML, not through an <img> tag or external URL.\nHowever, it might be possible to fetch the SVG markup from the image URL and inline it into the HTML. You'll need to get the original SVG URL (so you can't resize it with the .width() function).\nOnce you have the SVG URL (ends with .svg, going to the URL presents the SVG markup), you can fetch the data with fetch() or your preferred method, then use dangerouslySetInnerHTML to embed the returned SVG markup into a <div>. (Make sure you trust where the images are coming from, or you'll need to sanitize it.)\nStyling the SVG will depend on how you're managing styles in your application and also the specific SVG, but you could do something like:\n/* target svgs inside a div with class \"inline-svg\" */\ndiv.inline-svg svg {\n color: black;\n width: 24px;\n height: 24px;\n}\ndiv.inline-svg:hover svg {\n color: red;\n}\n\nThis will only work if your SVG has fill=\"currentColor\" or stroke=\"currentColor\" depending on how it's structured.\n",
"If you are using Simple Icons, you can precise the color as mentioned in their GitHub page:\n<img src=\"https://cdn.simpleicons.org/linkedin/00ccff99\" width=\"32\"/>\n<img src=\"https://cdn.simpleicons.org/github/red\" width=\"32\"/>\n\nWhich gives:\n \n\nHave fun!\n"
] |
[
3,
0
] |
[] |
[] |
[
"next.js",
"nextjs_image",
"sanity",
"svg",
"typescript"
] |
stackoverflow_0072592771_next.js_nextjs_image_sanity_svg_typescript.txt
|
Q:
Is there any standard variadic function for erasing multiple elements in a vector?
Take this vector:
std::vector<int> v = {1, 2, 3, 4, 5};
Let's say I want to remove some elements of a vector at some arbitrary indices: 0, 1, and 3. It's tedious to have to write something like this:
v.erase(v.begin());
v.erase(v.begin());
v.erase(v.begin() + 1);
Is there any standard function that takes in an arbitrary number of indices to erase from a vector? Something like this: v.erase(0, 1, 3);
A:
Yes and no.
There's nothing that deals with indices. There's also nothing that deals with arbitrary elements.
But you can erase multiple items that form a contiguous range at once. So you can coalesce your first two calls to erase into one (and probably about double the speed in the process).
// erase the first two elements
v.erase(v.begin(), v.begin() + 2);
|
Is there any standard variadic function for erasing multiple elements in a vector?
|
Take this vector:
std::vector<int> v = {1, 2, 3, 4, 5};
Let's say I want to remove some elements of a vector at some arbitrary indices: 0, 1, and 3. It's tedious to have to write something like this:
v.erase(v.begin());
v.erase(v.begin());
v.erase(v.begin() + 1);
Is there any standard function that takes in an arbitrary number of indices to erase from a vector? Something like this: v.erase(0, 1, 3);
|
[
"Yes and no.\nThere's nothing that deals with indices. There's also nothing that deals with arbitrary elements.\nBut you can erase multiple items that form a contiguous range at once. So you can coalesce your first two calls to erase into one (and probably about double the speed in the process).\n// erase the first two elements\nv.erase(v.begin(), v.begin() + 2);\n\n"
] |
[
1
] |
[
"If you want to erase first three element so for this you can run.\n std::vector<int> v = {1, 2, 3, 4, 5};\n v.erase(v.begin(),v.begin()+3);\n\nor,\nv.erase(v.begin(),v.end()-2);\n\n"
] |
[
-1
] |
[
"c++",
"vector"
] |
stackoverflow_0074669570_c++_vector.txt
|
Q:
Why do i keep getting an undefined variable error message in python?
So I keep getting error messages for cost_delivery not being defined, but the rest of the cost__ variables are ok, and theres no difference to how I've coded them? I am including my code below - any help would be appreciated!
price = float(input("Please enter the price of the package: "))
distance = float(input("Please enter the distance of delivery in kms: "))
air = 0.36
freight = 0.25
travel = input("Would you like to send your package via air or freight? ")
if travel == 'air':
cost_travel = air * distance
elif travel == 'frieght':
cost_travel = freight * distance
else:
print("Error. Enter either air or frieght.")
full_insurance = 50
lim_insurance = 25
insurance = input("Would you like full insurance or partial insurance?")
if insurance == 'full insurance':
cost_insurance = full_insurance
elif insurance == 'partial insurance':
cost_insurance = lim_insurance
else:
print("Error. Either enter full insurance or partial insurance.")
inc_gift = 15
no_gift = 0
gift = input("Would you like to include gift wrapping?")
if gift == 'yes':
cost_gift = inc_gift
elif gift == 'no':
cost_gift = no_gift
else:
print("Either enter yes or no.")
priority_delivery = 100
standard_delivery = 20
delivery = input("Would you like priority or standard delivery?")
if delivery == 'priority':
cost_delivery == priority_delivery
elif delivery == 'standard':
cost_delivery == standard_delivery
total_cost = cost_travel + cost_insurance + cost_gift + cost_delivery
print(total_cost)
I tried to define cost_delivery = 0 under standard and priority delivery definitions, but it resulted in delivery cost not being included at all in the final calculation.
I am very new to python so any suggestions would be helpful!!
A:
in below section
delivery = input("Would you like priority or standard delivery?")
if delivery == 'priority':
cost_delivery == priority_delivery
elif delivery == 'standard':
cost_delivery == standard_delivery
== is used to check if two object have same value.
since cost_delivery is not defined above in code and you are comparing it here in if .. elif condition, you are geeting this error.
you code should be
delivery = input("Would you like priority or standard delivery?")
if delivery == 'priority':
cost_delivery = priority_delivery
elif delivery == 'standard':
cost_delivery = standard_delivery
|
Why do i keep getting an undefined variable error message in python?
|
So I keep getting error messages for cost_delivery not being defined, but the rest of the cost__ variables are ok, and theres no difference to how I've coded them? I am including my code below - any help would be appreciated!
price = float(input("Please enter the price of the package: "))
distance = float(input("Please enter the distance of delivery in kms: "))
air = 0.36
freight = 0.25
travel = input("Would you like to send your package via air or freight? ")
if travel == 'air':
cost_travel = air * distance
elif travel == 'frieght':
cost_travel = freight * distance
else:
print("Error. Enter either air or frieght.")
full_insurance = 50
lim_insurance = 25
insurance = input("Would you like full insurance or partial insurance?")
if insurance == 'full insurance':
cost_insurance = full_insurance
elif insurance == 'partial insurance':
cost_insurance = lim_insurance
else:
print("Error. Either enter full insurance or partial insurance.")
inc_gift = 15
no_gift = 0
gift = input("Would you like to include gift wrapping?")
if gift == 'yes':
cost_gift = inc_gift
elif gift == 'no':
cost_gift = no_gift
else:
print("Either enter yes or no.")
priority_delivery = 100
standard_delivery = 20
delivery = input("Would you like priority or standard delivery?")
if delivery == 'priority':
cost_delivery == priority_delivery
elif delivery == 'standard':
cost_delivery == standard_delivery
total_cost = cost_travel + cost_insurance + cost_gift + cost_delivery
print(total_cost)
I tried to define cost_delivery = 0 under standard and priority delivery definitions, but it resulted in delivery cost not being included at all in the final calculation.
I am very new to python so any suggestions would be helpful!!
|
[
"in below section\ndelivery = input(\"Would you like priority or standard delivery?\")\nif delivery == 'priority':\n cost_delivery == priority_delivery\nelif delivery == 'standard':\n cost_delivery == standard_delivery\n\n\n== is used to check if two object have same value.\nsince cost_delivery is not defined above in code and you are comparing it here in if .. elif condition, you are geeting this error.\nyou code should be\ndelivery = input(\"Would you like priority or standard delivery?\")\nif delivery == 'priority':\n cost_delivery = priority_delivery\nelif delivery == 'standard':\n cost_delivery = standard_delivery\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"python_3.x",
"undefined"
] |
stackoverflow_0074670753_python_python_3.x_undefined.txt
|
Q:
Is it possible to mock a free-standing function in Javascript with Jest?
There are many questions on StackOverflow about how to mock things with Jest. I have, indeed, read many of those suggestions. I have experience with jest.mock and spyOn. I've tried the trick of doing a real import and overwriting just the function I desire to mock and have also tried the old import * as math from './math.js' and then you try to spyOn math but if you try it, you'll see that this won't work.
But after quite a lot of experimentation, I'm beginning to conclude that this is fundamentally impossible (which actually feels correct to me). The "real" subtract function that calls add will only ever be able to call the add defined in that module.
KEY POINT: The math.js file can NOT be edited. You cannot change it so that you have add and subtract as properties hanging off of some object. Consider that the math.js file is etched in stone and cannot be modified in any way.
I would LOVE to be wrong about this, but it seems to me that the free-standing add function in the math.js file cannot be mocked such that when you call the "real" subtract function, it runs the mocked add function. I know you could mock add and have mock add call a mocked subtract, but that is not the goal here.
Please consider this a purely academic question. This is not an XY problem. This is not a case of "what are you trying to do; there is a better way." This is purely trying to understand how things work given the fixed constraints I've outline in the question. Thanks!
math.js
export function add(a, b) {
return a+b;
}
export function subtract(a, b) {
return add(a, -b);
}
math.test.js
import { subtract } from './math.js';
// mock the add function to return 1234
describe('math', () => {
it('should return 1234', () => {
expect(subtract(5,3)).toBe(1234);
});
});
A:
It is not possible to mock a free-standing function in Javascript with Jest if that function is not a property of an object. In your example, the add function is not a property of any object, so it cannot be mocked in the way you described.
However, if you were able to modify the math.js file, you could change the add and subtract functions to be properties of an object, like this:
const math = {
add(a, b) {
return a+b;
},
subtract(a, b) {
return this.add(a, -b);
}
}
export default math;
With this change, you could then mock the add function by doing the following in your test:
import math from './math.js';
jest.mock('./math.js', () => {
const originalMath = jest.requireActual('./math.js');
return {
...originalMath,
add: jest.fn(() => 1234)
}
});
describe('math', () => {
it('should return 1234', () => {
expect(math.subtract(5,3)).toBe(1234);
});
});
This will mock the add function and have it return 1234 when math.subtract is called in the test. However, as mentioned, this assumes that you are able to modify the math.js file to make add and subtract properties of an object. If you are unable to make this change, it is not possible to mock the add function in the way you described.
|
Is it possible to mock a free-standing function in Javascript with Jest?
|
There are many questions on StackOverflow about how to mock things with Jest. I have, indeed, read many of those suggestions. I have experience with jest.mock and spyOn. I've tried the trick of doing a real import and overwriting just the function I desire to mock and have also tried the old import * as math from './math.js' and then you try to spyOn math but if you try it, you'll see that this won't work.
But after quite a lot of experimentation, I'm beginning to conclude that this is fundamentally impossible (which actually feels correct to me). The "real" subtract function that calls add will only ever be able to call the add defined in that module.
KEY POINT: The math.js file can NOT be edited. You cannot change it so that you have add and subtract as properties hanging off of some object. Consider that the math.js file is etched in stone and cannot be modified in any way.
I would LOVE to be wrong about this, but it seems to me that the free-standing add function in the math.js file cannot be mocked such that when you call the "real" subtract function, it runs the mocked add function. I know you could mock add and have mock add call a mocked subtract, but that is not the goal here.
Please consider this a purely academic question. This is not an XY problem. This is not a case of "what are you trying to do; there is a better way." This is purely trying to understand how things work given the fixed constraints I've outline in the question. Thanks!
math.js
export function add(a, b) {
return a+b;
}
export function subtract(a, b) {
return add(a, -b);
}
math.test.js
import { subtract } from './math.js';
// mock the add function to return 1234
describe('math', () => {
it('should return 1234', () => {
expect(subtract(5,3)).toBe(1234);
});
});
|
[
"It is not possible to mock a free-standing function in Javascript with Jest if that function is not a property of an object. In your example, the add function is not a property of any object, so it cannot be mocked in the way you described.\nHowever, if you were able to modify the math.js file, you could change the add and subtract functions to be properties of an object, like this:\nconst math = {\n add(a, b) {\n return a+b;\n },\n subtract(a, b) {\n return this.add(a, -b);\n }\n}\n\nexport default math;\n\nWith this change, you could then mock the add function by doing the following in your test:\nimport math from './math.js';\n\njest.mock('./math.js', () => {\n const originalMath = jest.requireActual('./math.js');\n return {\n ...originalMath,\n add: jest.fn(() => 1234)\n }\n});\n\ndescribe('math', () => {\n it('should return 1234', () => {\n expect(math.subtract(5,3)).toBe(1234);\n });\n});\n\nThis will mock the add function and have it return 1234 when math.subtract is called in the test. However, as mentioned, this assumes that you are able to modify the math.js file to make add and subtract properties of an object. If you are unable to make this change, it is not possible to mock the add function in the way you described.\n"
] |
[
0
] |
[] |
[] |
[
"javascript",
"jestjs",
"mocking",
"unit_testing"
] |
stackoverflow_0074670721_javascript_jestjs_mocking_unit_testing.txt
|
Q:
Risc-V input output use
I m triying to do a bigger number printer with risc-v. But i cannot implement that. What is not going in my code?
A:
Here you can find some exemple for risc-v input and output exemple for beginner.
|
Risc-V input output use
|
I m triying to do a bigger number printer with risc-v. But i cannot implement that. What is not going in my code?
|
[
"Here you can find some exemple for risc-v input and output exemple for beginner.\n\n"
] |
[
0
] |
[] |
[] |
[
"riscv"
] |
stackoverflow_0074647173_riscv.txt
|
Q:
Cannot print the string to which the stack address points using INT80 in Ubuntu system
I can print character in label that in section .data
But I can't print character use stack address
section .data
break db "a"
section .text
global _start
_start:
mov rax, qword 'a'
push rax
; push 'a' to stack
mov rax,4
mov rbx,1
; get stack top pointer and mov to rcx register
mov rcx,rsp
; If replace rsp with label <break> that can print newlines character
; mov rcx,break
mov rdx,1
int 80h
pop rax
call quit
quit:
mov rbx, 0
mov rax, 1
int 80h
ret
console>
not print anything
If replace rsp with label that can print newlines
; mov rcx, rsp
mov rcx, break
console>a#
print one character
Makefile
.PHONY: test
test:
nasm -f elf64 test.asm
ld -s -o test test.o
./test
.PHONY: test_debug
test_debug:
nasm -f elf64 -F dwarf -g test.asm
ld -g -o test test.o
gdb test
|
Cannot print the string to which the stack address points using INT80 in Ubuntu system
|
I can print character in label that in section .data
But I can't print character use stack address
section .data
break db "a"
section .text
global _start
_start:
mov rax, qword 'a'
push rax
; push 'a' to stack
mov rax,4
mov rbx,1
; get stack top pointer and mov to rcx register
mov rcx,rsp
; If replace rsp with label <break> that can print newlines character
; mov rcx,break
mov rdx,1
int 80h
pop rax
call quit
quit:
mov rbx, 0
mov rax, 1
int 80h
ret
console>
not print anything
If replace rsp with label that can print newlines
; mov rcx, rsp
mov rcx, break
console>a#
print one character
Makefile
.PHONY: test
test:
nasm -f elf64 test.asm
ld -s -o test test.o
./test
.PHONY: test_debug
test_debug:
nasm -f elf64 -F dwarf -g test.asm
ld -g -o test test.o
gdb test
|
[] |
[] |
[
"It looks like you're using the print function from the print.asm file to print the block character and the newline character. In order to print a character that's on the stack, you need to first get the address of the character from the stack and then pass it to the print function. You can do this by using the pop instruction to remove the character from the stack and store it in a register, and then pass the register to the print function.\nHere's an example of how you could modify your code to print the newline character that's on the stack:\n; print line break\npush rax\nmov rax, 0ah\npush rax\n\n; Get the address of the newline character from the stack\npop rbx\nmov rcx, rbx\n\nmov rdx, 1\ncall print\n\n; Remove the newline character from the stack\npop rax\n\nThis code first pushes the current value of the rax register onto the stack, then pushes the newline character onto the stack. It then uses the pop instruction to remove the newline character from the stack and store it in the rbx register. The code then passes the address of the newline character (stored in rbx) to the print function, along with the length of the character (1 byte). Finally, it removes the original value of the rax register from the stack.\nI hope this helps! Let me know if you have any other questions.\n"
] |
[
-1
] |
[
"nasm"
] |
stackoverflow_0074670768_nasm.txt
|
Q:
Connect to localhost from mobile phone using express, nodejs
I would like to access my server that I host on my computer (Node.js & Express) from my phone. The computer is on the same network as the phone.
As soon as I type localhost:3000 in the address bar of the browser on the desktop PC, everything works without problems.
If I now try to open my site with the cell phone under the following address 192.168.0.100:3000, I get no error message but nothing is displayed... The IP address was retrieved with ipconfig.
I have tried several solutions that I have found here on Stack Overflow such as port sharing in the firewall settings. Unfortunately without success.
Here is my code when creating at the server:
var express = require('express');
var app = express();
var server = app.listen(process.env.PORT || 3000, listen);
function listen() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://' + host + ':' + port);
}
When I try to check my IP address via the console.log, I get the following:
If someone has an idea what this could be I would be very happy!
#1 Update:
I have now replaced my line of code with
var server = app.listen(3000, "127.0.0.1", listen);
and I get the following back from my console:
I can access my server from my computer through
127.0.0.1:3000
localhost:3000
If I try to access (on computer) through 192.168.0.100:3000 nothing happens. I also get no error message. Only a white screen.
#2 Update:
Typing "ipconfig" in cmd
After changing the IP to
var server = app.listen(3000, "192.168.0.100", listen);
I could not access my server anymore. Not even using localhost:3000. However, when examining the item I found an error that does not show up when I set
var server = app.listen(3000, "127.0.0.1:3000", listen);
I do not understand why the error shows up when changing the IP address, since the code is the same.
Heres a picture of the error
Error fixing
Apparently one way to work around the error is to use a tunneling service (ngrok). I will try it
#3 Update
In my last attempt, i was trying to tunnel my server via ngrok. At first, everything looked like it was finally going to work. From my own PC I could access my websocket server via ngrok forwarding link. However, when I tried to click on the link with my phone/second pc, I got the error that the connection is refused...
If someone has an idea or an approach to what this could be, I would be very happy.
SOLUTION IS POSTED IN THE COMMENTS
A:
Sorry I can't comment:
Have you tried 192.168.0.100:3000 into the browser, on the computer?
As for the http://:::3000 you can check this
A:
If you want to access your localhost over the internet...
There are some softwares / Chrome Extensions that let's you access your local host over the internet...
https://ngrok.com
http://localtunnel.me
http://localhost.run
You can do Google search for more softwares like these ones and choose accordingly to your work.
A:
I give up because new errors keep appearing. I thought I'd post my solution (or my new approach) here in case anyone else is in the same situation as me. In the end I used the following github repository as a base for my project. If I set up a server with this there are no problems at all. I have also tunneled it with ngrok in the end.
Link to Github
It also uses p5.js, node.js and socket.io
|
Connect to localhost from mobile phone using express, nodejs
|
I would like to access my server that I host on my computer (Node.js & Express) from my phone. The computer is on the same network as the phone.
As soon as I type localhost:3000 in the address bar of the browser on the desktop PC, everything works without problems.
If I now try to open my site with the cell phone under the following address 192.168.0.100:3000, I get no error message but nothing is displayed... The IP address was retrieved with ipconfig.
I have tried several solutions that I have found here on Stack Overflow such as port sharing in the firewall settings. Unfortunately without success.
Here is my code when creating at the server:
var express = require('express');
var app = express();
var server = app.listen(process.env.PORT || 3000, listen);
function listen() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://' + host + ':' + port);
}
When I try to check my IP address via the console.log, I get the following:
If someone has an idea what this could be I would be very happy!
#1 Update:
I have now replaced my line of code with
var server = app.listen(3000, "127.0.0.1", listen);
and I get the following back from my console:
I can access my server from my computer through
127.0.0.1:3000
localhost:3000
If I try to access (on computer) through 192.168.0.100:3000 nothing happens. I also get no error message. Only a white screen.
#2 Update:
Typing "ipconfig" in cmd
After changing the IP to
var server = app.listen(3000, "192.168.0.100", listen);
I could not access my server anymore. Not even using localhost:3000. However, when examining the item I found an error that does not show up when I set
var server = app.listen(3000, "127.0.0.1:3000", listen);
I do not understand why the error shows up when changing the IP address, since the code is the same.
Heres a picture of the error
Error fixing
Apparently one way to work around the error is to use a tunneling service (ngrok). I will try it
#3 Update
In my last attempt, i was trying to tunnel my server via ngrok. At first, everything looked like it was finally going to work. From my own PC I could access my websocket server via ngrok forwarding link. However, when I tried to click on the link with my phone/second pc, I got the error that the connection is refused...
If someone has an idea or an approach to what this could be, I would be very happy.
SOLUTION IS POSTED IN THE COMMENTS
|
[
"Sorry I can't comment:\nHave you tried 192.168.0.100:3000 into the browser, on the computer?\nAs for the http://:::3000 you can check this\n",
"If you want to access your localhost over the internet...\nThere are some softwares / Chrome Extensions that let's you access your local host over the internet...\n\nhttps://ngrok.com\nhttp://localtunnel.me\nhttp://localhost.run\n\nYou can do Google search for more softwares like these ones and choose accordingly to your work.\n",
"I give up because new errors keep appearing. I thought I'd post my solution (or my new approach) here in case anyone else is in the same situation as me. In the end I used the following github repository as a base for my project. If I set up a server with this there are no problems at all. I have also tunneled it with ngrok in the end.\nLink to Github\nIt also uses p5.js, node.js and socket.io\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"express",
"localhost",
"node.js"
] |
stackoverflow_0074634082_express_localhost_node.js.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.