content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
30
130
Q: Rollback to specific version of a python package in Goolge Colab I've read that rolling back rpy2 version to v3.4.2 fixed the problem (in this case Rpy2 Error depends on execution method: NotImplementedError: Conversion "rpy2py" not defined, but it could be any problem) How can I change the installed version of the python package rpy2 to version v3.4.2 in Google Colab? I know the command !pip install rpy2, but how can I chose a specific version and is it a problem if there is already a newer version installed? In other words: How can I downgrade the version of a python package in Google Colab? A: !pip install -Iv rpy2==3.4.2 worked for me as explained in https://stackoverflow.com/a/5226504/7735095
Rollback to specific version of a python package in Goolge Colab
I've read that rolling back rpy2 version to v3.4.2 fixed the problem (in this case Rpy2 Error depends on execution method: NotImplementedError: Conversion "rpy2py" not defined, but it could be any problem) How can I change the installed version of the python package rpy2 to version v3.4.2 in Google Colab? I know the command !pip install rpy2, but how can I chose a specific version and is it a problem if there is already a newer version installed? In other words: How can I downgrade the version of a python package in Google Colab?
[ "!pip install -Iv rpy2==3.4.2\n\nworked for me as explained in https://stackoverflow.com/a/5226504/7735095\n" ]
[ 0 ]
[]
[]
[ "google_colaboratory", "python", "version" ]
stackoverflow_0074678556_google_colaboratory_python_version.txt
Q: How to change the master username at git in WebStorm? WebStorm tries to push my project to an account that does not exist anymore. How do I change it? I have already added the new account to WebStorm and it still tries pushing to the old account. A: You can change it in Settings>Repositories. A: Setting>General>Repository name>rename
How to change the master username at git in WebStorm?
WebStorm tries to push my project to an account that does not exist anymore. How do I change it? I have already added the new account to WebStorm and it still tries pushing to the old account.
[ "You can change it in Settings>Repositories.\n", "Setting>General>Repository name>rename\n" ]
[ 0, 0 ]
[]
[]
[ "git", "intellij_idea", "webstorm" ]
stackoverflow_0074678013_git_intellij_idea_webstorm.txt
Q: How do I achieve navbar and content div with 2 independently scrollable divs using Tailwind & Nextjs without sticky? I am trying to understand how Stripe achieves its layout here: https://stripe.com/docs/payments That page has a column flexbox div containing 2 child divs: one for the navbar and the second for the main content. The column direction means that the navbar will sit on top of the main content. The navbar does not use sticky and from what I can see it does not use fixed positioning either. The main content div is a Flexbox with overflow-y: hidden and has 2 child divs: the first for the LHS sidebar and the second for the main page content. Note that left sidebar and main page content scroll independently and the overall page itself does not scroll at all. Unless I misunderstand what is happening, Stripe appears to be using the overflow-hidden property in the primary div to ensure that the page contents div does not go outside the viewport and hence the overall page is not scrollable. The inner divs use overflow-y-auto to ensure that content inside them is scrollable. I'm trying to replicate this using the below using Tailwind and Nextjs: <div class="h-full bg-white" > <div class="flex flex-col h-full"> <div id="Navbar" class="bg-blue-200"> Navbar </div> <div id="MainContent" class="flex flex-auto h-full overflow-y-hidden"> <div> <div class="flex-grow-0 flex-shrink-0 flex flex-col h-full w-56 bg-green-100"> <div class="flex flex-grow overflow-y-auto overflow-x-hidden"> <div> <p>lhs</p> <p>lhs</p> ... lots more content here to ensure page overflow </div> </div> <div> Sidebar footer </div> </div> </div> <div class="bg-red-100 w-full"> Content </div> </div> </div> </div> However, when I use the above I just get the whole page that scrolls, whereas I'm expecting to see the LHS sidebar containing the list of <p>las</p> elements scroll and LHS sidebar footer and the page as a whole to stay static. There is no change when I add a load of content into the content div. Here's what it looks like: https://play.tailwindcss.com/J6unFAO47B Whilst I know that I could use a sticky navbar, I'm trying to understand what Stripe is doing in their page and so I want to understand why is my sidebar not scrolling independently of the other areas of the page? A: I'm not sure why it's not working in the Tailwind playground - I suspect it's because I'm not setting a height in one of the parent divs. When I do that, it works. In Nextjs, the solution wast to do this in CSS: #__next { height: 100%; } This ensures that the height of the top-most div is set to the height of the viewport and then the overflow seems to work fine as a result. A: Check out this: My ans. I hope this solves your problem.
How do I achieve navbar and content div with 2 independently scrollable divs using Tailwind & Nextjs without sticky?
I am trying to understand how Stripe achieves its layout here: https://stripe.com/docs/payments That page has a column flexbox div containing 2 child divs: one for the navbar and the second for the main content. The column direction means that the navbar will sit on top of the main content. The navbar does not use sticky and from what I can see it does not use fixed positioning either. The main content div is a Flexbox with overflow-y: hidden and has 2 child divs: the first for the LHS sidebar and the second for the main page content. Note that left sidebar and main page content scroll independently and the overall page itself does not scroll at all. Unless I misunderstand what is happening, Stripe appears to be using the overflow-hidden property in the primary div to ensure that the page contents div does not go outside the viewport and hence the overall page is not scrollable. The inner divs use overflow-y-auto to ensure that content inside them is scrollable. I'm trying to replicate this using the below using Tailwind and Nextjs: <div class="h-full bg-white" > <div class="flex flex-col h-full"> <div id="Navbar" class="bg-blue-200"> Navbar </div> <div id="MainContent" class="flex flex-auto h-full overflow-y-hidden"> <div> <div class="flex-grow-0 flex-shrink-0 flex flex-col h-full w-56 bg-green-100"> <div class="flex flex-grow overflow-y-auto overflow-x-hidden"> <div> <p>lhs</p> <p>lhs</p> ... lots more content here to ensure page overflow </div> </div> <div> Sidebar footer </div> </div> </div> <div class="bg-red-100 w-full"> Content </div> </div> </div> </div> However, when I use the above I just get the whole page that scrolls, whereas I'm expecting to see the LHS sidebar containing the list of <p>las</p> elements scroll and LHS sidebar footer and the page as a whole to stay static. There is no change when I add a load of content into the content div. Here's what it looks like: https://play.tailwindcss.com/J6unFAO47B Whilst I know that I could use a sticky navbar, I'm trying to understand what Stripe is doing in their page and so I want to understand why is my sidebar not scrolling independently of the other areas of the page?
[ "I'm not sure why it's not working in the Tailwind playground - I suspect it's because I'm not setting a height in one of the parent divs. When I do that, it works.\nIn Nextjs, the solution wast to do this in CSS:\n#__next {\n height: 100%;\n}\n\nThis ensures that the height of the top-most div is set to the height of the viewport and then the overflow seems to work fine as a result.\n", "Check out this: My ans. I hope this solves your problem.\n" ]
[ 0, 0 ]
[]
[]
[ "css", "next.js", "tailwind_css" ]
stackoverflow_0074677986_css_next.js_tailwind_css.txt
Q: Why groovy println function prints extra empty line? I noticed the println function in groovy will print extra empty line: string myline=extractedLine println 'myline":+myline The expected output is '101110' but the actual output shows 2 lines been printed out first line is an empty line and second line is '101110'. May I know how to remove the empty line? I tried to use print instead of println, but still the same result. A: I'm assuming the value in myline itself has a newline character(line feeder or a carriage return), hence try something like the one below. print "myline: " + myline.replaceAll('\n|\r', '')
Why groovy println function prints extra empty line?
I noticed the println function in groovy will print extra empty line: string myline=extractedLine println 'myline":+myline The expected output is '101110' but the actual output shows 2 lines been printed out first line is an empty line and second line is '101110'. May I know how to remove the empty line? I tried to use print instead of println, but still the same result.
[ "I'm assuming the value in myline itself has a newline character(line feeder or a carriage return), hence try something like the one below.\nprint \"myline: \" + myline.replaceAll('\\n|\\r', '')\n\n" ]
[ 0 ]
[]
[]
[ "groovy" ]
stackoverflow_0074672562_groovy.txt
Q: How to use asyncio to get responses from elasticsearch in Python? I am trying to use asyncio to get responses from elasticsearch. I am gatering queries to elastic in a list, then I am iterating through that list to make response for each of that query. that is my code: ` async def make_response(query, es): res = await es.search(index='index_name', query=query, size=10000) return res query_list = make_queries_list_db() async def main(): list_of_res = [] for enum, el in enumerate(query_list): es = AsyncElasticsearch(port, auth) list_of_res.append(make_response(query_list[enum],es)) await asyncio.gather(*list_of_res) asyncio.run(main()) ` Doing that I am still having errors, like "Unclosed client session" or "connection time exceed". How to use asyncio with elasticsearch in a proper way? A: It looks like you are using the make_response() function to make requests to Elasticsearch. This function should be an async function so that it can use await to make asynchronous requests to Elasticsearch. Here is an example of how you can use asyncio and aiohttp to make requests to Elasticsearch: import asyncio import aiohttp async def make_response(query, es_session): async with es_session.post('http://your-elasticsearch-url/index_name/_search', json=query, size=10000) as resp: res = await resp.json() return res async def main(): query_list = make_queries_list_db() async with aiohttp.ClientSession() as es_session: tasks = [] for query in query_list: task = asyncio.create_task(make_response(query, es_session)) tasks.append(task) results = await asyncio.gather(*tasks) # Do something with the results asyncio.run(main()) This code creates a new ClientSession using aiohttp to make requests to Elasticsearch. It then creates a list of tasks using the make_response() function, and uses asyncio.gather() to wait for all of the tasks to complete. It is also important to note that you should not create a new ClientSession for each query. Instead, you should create a single ClientSession at the beginning of your main() function, and use that session to make all of the requests to Elasticsearch. This ensures that the connections to Elasticsearch are properly managed and closed when the program ends.
How to use asyncio to get responses from elasticsearch in Python?
I am trying to use asyncio to get responses from elasticsearch. I am gatering queries to elastic in a list, then I am iterating through that list to make response for each of that query. that is my code: ` async def make_response(query, es): res = await es.search(index='index_name', query=query, size=10000) return res query_list = make_queries_list_db() async def main(): list_of_res = [] for enum, el in enumerate(query_list): es = AsyncElasticsearch(port, auth) list_of_res.append(make_response(query_list[enum],es)) await asyncio.gather(*list_of_res) asyncio.run(main()) ` Doing that I am still having errors, like "Unclosed client session" or "connection time exceed". How to use asyncio with elasticsearch in a proper way?
[ "It looks like you are using the make_response() function to make requests to Elasticsearch. This function should be an async function so that it can use await to make asynchronous requests to Elasticsearch.\nHere is an example of how you can use asyncio and aiohttp to make requests to Elasticsearch:\nimport asyncio\nimport aiohttp\n\nasync def make_response(query, es_session):\n async with es_session.post('http://your-elasticsearch-url/index_name/_search', json=query, size=10000) as resp:\n res = await resp.json()\n return res\n\nasync def main():\n query_list = make_queries_list_db()\n\n async with aiohttp.ClientSession() as es_session:\n tasks = []\n for query in query_list:\n task = asyncio.create_task(make_response(query, es_session))\n tasks.append(task)\n\n results = await asyncio.gather(*tasks)\n\n # Do something with the results\n\nasyncio.run(main())\n\nThis code creates a new ClientSession using aiohttp to make requests to Elasticsearch. It then creates a list of tasks using the make_response() function, and uses asyncio.gather() to wait for all of the tasks to complete.\nIt is also important to note that you should not create a new ClientSession for each query. Instead, you should create a single ClientSession at the beginning of your main() function, and use that session to make all of the requests to Elasticsearch. This ensures that the connections to Elasticsearch are properly managed and closed when the program ends.\n" ]
[ 0 ]
[]
[]
[ "elasticsearch", "python_asyncio" ]
stackoverflow_0074654423_elasticsearch_python_asyncio.txt
Q: How to have buttons appear on the screen? In the code I want all the squares to be a single color. Allowing me to still change the colors of individual squares if I want to. But after I did that, the buttons disappeared from the screen. To be able to have all the squares/boxes be a different color. I used this: https://jsfiddle.net/kwqh6zdn/ Doing so has the effect of hiding all the buttons though. .channel-browser__channel-grid-item::after { content: ""; position: absolute; inset: 0; background-color: pink; } How would this be fixed in the code so that, I am able to have all the squares be a certain color, while also being able to see the play buttons on the screen? <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> .channel-browser__channel-grid-item::after { content: ""; position: absolute; inset: 0; background-color: pink; } .cover { -webkit-appearance: none; appearance: none; display: flex; justify-content: center; align-items: center; position: relative; width: 90px; height: 90px; border-radius: 50%; cursor: pointer; border: 9px solid blue; background: transparent; filter: drop-shadow(3px 3px 3px rgba(0, 0, 0, 0.7)); position: absolute; left: 0; top: 0; bottom: 0; right: 0; margin: auto; } .cover::before { content: ""; width: 0; height: 0; border-top: 20px solid transparent; border-bottom: 20px solid transparent; border-left: 27px solid blue; transform: translateX(4px); } .channel-browser__channel-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } .channel-browser__channel-grid-item { position: relative; } .content-item-container--aspect-square .horizontal-content-browser__content-item { padding-top: 100%; } .horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component { position: absolute; top: 0; left: 0; width: 100%; height: auto; border-radius: 4px; background-color: #1a1a1a; -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); } .box-color-red::after { background: red; border-radius: 4px; } .box-color-blue { background: blue; } .box-color-yellow { background: yellow; } .box-color-green { background: green; } <div class="playButtonContainer with-curtain channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square"> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-red"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle2 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> </div> A: This can be achieved with the addition of: .channel-browser__channel-grid-item::after { z-index: -1; } Though if we're manipulating layers then it's often useful to style the parent with: .channel-browser__channel-grid-item::after { isolation: isolate; } This is in order to prevent layers "leaking" out of the parent element and interfering with other contents and their z-index specified layers: /* styling the parent of the pseudo-element in order to have each element be its own stacking context, and to isolate the various layers within that element: */ .channel-browser__channel-grid-item { isolation: isolate; } .channel-browser__channel-grid-item::after { content: ""; position: absolute; inset: 0; background-color: pink; /* positioning the pseudo-element behind the content of its parent element: */ z-index: -1; } .cover { -webkit-appearance: none; appearance: none; display: flex; justify-content: center; align-items: center; position: relative; width: 90px; height: 90px; border-radius: 50%; cursor: pointer; border: 9px solid blue; background: transparent; filter: drop-shadow(3px 3px 3px rgba(0, 0, 0, 0.7)); position: absolute; left: 0; top: 0; bottom: 0; right: 0; margin: auto; } .cover::before { content: ""; width: 0; height: 0; border-top: 20px solid transparent; border-bottom: 20px solid transparent; border-left: 27px solid blue; transform: translateX(4px); } .channel-browser__channel-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } .channel-browser__channel-grid-item { position: relative; } .content-item-container--aspect-square .horizontal-content-browser__content-item { padding-top: 100%; } .horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component { position: absolute; top: 0; left: 0; width: 100%; height: auto; border-radius: 4px; background-color: #1a1a1a; -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); } .box-color-red::after { background: red; border-radius: 4px; } .box-color-blue { background: blue; } .box-color-yellow { background: yellow; } .box-color-green { background: green; } <div class="playButtonContainer with-curtain channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square"> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-red"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle2 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> </div> JS Fiddle demo. References: isolation. z-index.
How to have buttons appear on the screen?
In the code I want all the squares to be a single color. Allowing me to still change the colors of individual squares if I want to. But after I did that, the buttons disappeared from the screen. To be able to have all the squares/boxes be a different color. I used this: https://jsfiddle.net/kwqh6zdn/ Doing so has the effect of hiding all the buttons though. .channel-browser__channel-grid-item::after { content: ""; position: absolute; inset: 0; background-color: pink; } How would this be fixed in the code so that, I am able to have all the squares be a certain color, while also being able to see the play buttons on the screen? <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> .channel-browser__channel-grid-item::after { content: ""; position: absolute; inset: 0; background-color: pink; } .cover { -webkit-appearance: none; appearance: none; display: flex; justify-content: center; align-items: center; position: relative; width: 90px; height: 90px; border-radius: 50%; cursor: pointer; border: 9px solid blue; background: transparent; filter: drop-shadow(3px 3px 3px rgba(0, 0, 0, 0.7)); position: absolute; left: 0; top: 0; bottom: 0; right: 0; margin: auto; } .cover::before { content: ""; width: 0; height: 0; border-top: 20px solid transparent; border-bottom: 20px solid transparent; border-left: 27px solid blue; transform: translateX(4px); } .channel-browser__channel-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } .channel-browser__channel-grid-item { position: relative; } .content-item-container--aspect-square .horizontal-content-browser__content-item { padding-top: 100%; } .horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component { position: absolute; top: 0; left: 0; width: 100%; height: auto; border-radius: 4px; background-color: #1a1a1a; -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); } .box-color-red::after { background: red; border-radius: 4px; } .box-color-blue { background: blue; } .box-color-yellow { background: yellow; } .box-color-green { background: green; } <div class="playButtonContainer with-curtain channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square"> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-red"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle2 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <button class="playSingle1 cover" type="button" data-container="play1" data-id="M7lc1UVf-VE"></button> </div> </div>
[ "This can be achieved with the addition of:\n.channel-browser__channel-grid-item::after {\n z-index: -1;\n}\n\nThough if we're manipulating layers then it's often useful to style the parent with:\n.channel-browser__channel-grid-item::after {\n isolation: isolate;\n}\n\nThis is in order to prevent layers \"leaking\" out of the parent element and interfering with other contents and their z-index specified layers:\n\n\n/* styling the parent of the pseudo-element in order to have each\n element be its own stacking context, and to isolate the various\n layers within that element: */\n.channel-browser__channel-grid-item {\n isolation: isolate;\n}\n\n.channel-browser__channel-grid-item::after {\n content: \"\";\n position: absolute;\n inset: 0;\n background-color: pink;\n /* positioning the pseudo-element behind the content of\n its parent element: */\n z-index: -1;\n}\n\n.cover {\n -webkit-appearance: none;\n appearance: none;\n display: flex;\n justify-content: center;\n align-items: center;\n position: relative;\n width: 90px;\n height: 90px;\n border-radius: 50%;\n cursor: pointer;\n border: 9px solid blue;\n background: transparent;\n filter: drop-shadow(3px 3px 3px rgba(0, 0, 0, 0.7));\n position: absolute;\n left: 0;\n top: 0;\n bottom: 0;\n right: 0;\n margin: auto;\n}\n\n.cover::before {\n content: \"\";\n width: 0;\n height: 0;\n border-top: 20px solid transparent;\n border-bottom: 20px solid transparent;\n border-left: 27px solid blue;\n transform: translateX(4px);\n}\n\n.channel-browser__channel-grid {\n display: grid;\n gap: 16px;\n grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));\n margin: 0;\n padding: 0;\n border: 0;\n font-size: 100%;\n font: inherit;\n vertical-align: baseline;\n}\n\n.channel-browser__channel-grid-item {\n position: relative;\n}\n\n.content-item-container--aspect-square .horizontal-content-browser__content-item {\n padding-top: 100%;\n}\n\n.horizontal-content-browser__content-item .horizontal-content-browser__fallback-image,\n.horizontal-content-browser__content-item .responsive-image-component {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: auto;\n border-radius: 4px;\n background-color: #1a1a1a;\n -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%);\n box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%);\n}\n\n.box-color-red::after {\n background: red;\n border-radius: 4px;\n}\n\n.box-color-blue {\n background: blue;\n}\n\n.box-color-yellow {\n background: yellow;\n}\n\n.box-color-green {\n background: green;\n}\n<div class=\"playButtonContainer with-curtain channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square\">\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-red\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle2 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <button class=\"playSingle1 cover\" type=\"button\" data-container=\"play1\" data-id=\"M7lc1UVf-VE\"></button>\n </div>\n</div>\n\n\n\nJS Fiddle demo.\nReferences:\n\nisolation.\nz-index.\n\n" ]
[ 1 ]
[]
[]
[ "background", "background_color", "button", "css", "html" ]
stackoverflow_0074678417_background_background_color_button_css_html.txt
Q: Mongoose model schema referencing each other - how to simplify? I am using mongoose and have two schemas: UserSchema and CommunitySchema: const UserSchema = new Schema({ name: String, communities: [{ type: Schema.Types.ObjectId, ref: CollectionModel }], exCommunities: [{ type: Schema.Types.ObjectId, ref: CollectionModel }], }, { timestamps: true }); const CommunitySchema = new Schema({ slug: { type: String, unique: true }, name: String, description: String, users: [ { type: Schema.Types.ObjectId, ref: "User" } ] }, { timestamps: true }); User can be a part of multiple communities and also leave any community and be in the exCommunities field. When an user joins a community, I have to do a double work: Add the user to a user community and update the community user field with the reference ID. Questions: Is there a way to simplify it? For example, by managing the CommunitySchema users field automatically based on the UserSchema communities field? Now I have to do this: collection.users.push(userId); user.communities.push(communityId); Could the collection.users be automatically added when I push a community to user.communities? And how?) Is it possible to add a date when the user is added to a community or leave a community? Something like: communities: [{ type: Schema.Types.ObjectId, ref: CollectionModel, createdAt: "<DATE>" }] Thank you! A: you no need to add communities and exCommunities in UserSchema const UserSchema = new Schema({ name: String, }, { timestamps: true }); const communityUserSchema = new Schema({ user_id:{type: Schema.Types.ObjectId, ref: "User"}, joined_at:{type:Date}, leaved_at:{type:Date}, is_active:{type:Boolean}, role:{type:String, enum:['user','admin'], default:'user'} }); const CommunitySchema = new Schema({ slug: { type: String, unique: true }, name: String, description: String, users:{ type:[communityUserSchema], default:[] } }, { timestamps: true }); you can find User's communities by : let user_id = req.user._id; all_communities = await Community.find({"users.user_id":user_id}); active_communities = await Community.find({"users.user_id":user_id, "is_active":true}); ex_communities = await Community.find({"users.user_id":user_id,"leaved_at":{"$ne":null}}); When User Create New Community (create as a Admin): let current_user = {user_id:req.user.id,joined_at:new Date(),is_active:true,role:'admin'}; // if you select users from frontend while creating new community let other_user = req.body.user_ids; let other_users_mapped = other_user.map((item)=>{ return {user_id:item,joined_at:new Date(),role:'user',is_active:true}}); let all_users = [current_user]; all_users = all_users.concat(other_users_mapped); let community = new Community(); community.name = req.body.name; community.slug = req.body.slug; community.description = req.body.description; community.users = all_users ; let created = await community.save(); When User Leave Community : Community.updateOne({_id: community_id , 'users.user_id':user_id },{ $set:{ 'users.$.is_active':false, 'users.$.leaved_at':new Date() } }); View Community with only active members : let community_id = req.params.community_id; let data = await Community.findOne({_id:community_id},{ users: { $elemMatch: { is_active: true } } }); A: AI solved it for me, here is the correct example: import * as mongoose from 'mongoose'; const Schema = mongoose.Schema; interface User { name: string; email: string; communities: Community[]; } interface Community { name: string; description: string; users: User[]; } const userSchema = new Schema({ name: String, email: String, }, { timestamps: true, }); const communitySchema = new Schema({ name: String, description: String, }, { timestamps: true, }); // Define the user_communities table using the communitySchema const userCommunitySchema = new Schema({ user: { type: Schema.Types.ObjectId, ref: 'User' }, community: { type: Schema.Types.ObjectId, ref: 'Community' }, joined_on: Date, }, { timestamps: true, }); // Use the userCommunitySchema to create the UserCommunity model const UserCommunity = mongoose.model('UserCommunity', userCommunitySchema); // Use the userSchema to create the User model, and define a virtual property // for accessing the user's communities userSchema.virtual('communities', { ref: 'Community', localField: '_id', foreignField: 'user', justOne: false, }); const User = mongoose.model<User>('User', userSchema); // Use the communitySchema to create the Community model, and define a virtual property // for accessing the community's users communitySchema.virtual('users', { ref: 'User', localField: '_id', foreignField: 'community', justOne: false, }); const Community = mongoose.model<Community>('Community', communitySchema); The userSchema and communitySchema are then used to create the User and Community models, respectively. For the User model, a virtual property called communities is defined using the virtual method. This virtual property is used to specify how to populate the user.communities property when querying the database. The communitySchema also defines a users virtual property, which is used to populate the community.users property when querying.
Mongoose model schema referencing each other - how to simplify?
I am using mongoose and have two schemas: UserSchema and CommunitySchema: const UserSchema = new Schema({ name: String, communities: [{ type: Schema.Types.ObjectId, ref: CollectionModel }], exCommunities: [{ type: Schema.Types.ObjectId, ref: CollectionModel }], }, { timestamps: true }); const CommunitySchema = new Schema({ slug: { type: String, unique: true }, name: String, description: String, users: [ { type: Schema.Types.ObjectId, ref: "User" } ] }, { timestamps: true }); User can be a part of multiple communities and also leave any community and be in the exCommunities field. When an user joins a community, I have to do a double work: Add the user to a user community and update the community user field with the reference ID. Questions: Is there a way to simplify it? For example, by managing the CommunitySchema users field automatically based on the UserSchema communities field? Now I have to do this: collection.users.push(userId); user.communities.push(communityId); Could the collection.users be automatically added when I push a community to user.communities? And how?) Is it possible to add a date when the user is added to a community or leave a community? Something like: communities: [{ type: Schema.Types.ObjectId, ref: CollectionModel, createdAt: "<DATE>" }] Thank you!
[ "you no need to add communities and exCommunities in UserSchema\nconst UserSchema = new Schema({\n name: String,\n}, { timestamps: true });\n\nconst communityUserSchema = new Schema({\n user_id:{type: Schema.Types.ObjectId, ref: \"User\"},\n joined_at:{type:Date},\n leaved_at:{type:Date},\n is_active:{type:Boolean},\n role:{type:String, enum:['user','admin'], default:'user'}\n});\n\nconst CommunitySchema = new Schema({\n slug: { type: String, unique: true },\n name: String, \n description: String, \n users:{\n type:[communityUserSchema],\n default:[]\n }\n}, { timestamps: true });\n\nyou can find User's communities by :\nlet user_id = req.user._id;\nall_communities = await Community.find({\"users.user_id\":user_id});\n\nactive_communities = await Community.find({\"users.user_id\":user_id, \"is_active\":true});\n\nex_communities = await Community.find({\"users.user_id\":user_id,\"leaved_at\":{\"$ne\":null}});\n\nWhen User Create New Community (create as a Admin):\nlet current_user = {user_id:req.user.id,joined_at:new Date(),is_active:true,role:'admin'};\n\n // if you select users from frontend while creating new community \n\n let other_user = req.body.user_ids;\n let other_users_mapped = other_user.map((item)=>{ return {user_id:item,joined_at:new Date(),role:'user',is_active:true}}); \n\n let all_users = [current_user];\n all_users = all_users.concat(other_users_mapped);\n\n let community = new Community();\n community.name = req.body.name;\n community.slug = req.body.slug;\n community.description = req.body.description;\n community.users = all_users ;\n let created = await community.save();\n\nWhen User Leave Community :\nCommunity.updateOne({_id: community_id , 'users.user_id':user_id },{\n $set:{\n 'users.$.is_active':false,\n 'users.$.leaved_at':new Date()\n }\n});\n\nView Community with only active members :\nlet community_id = req.params.community_id;\nlet data = await Community.findOne({_id:community_id},{ users: { $elemMatch: { is_active: true } } });\n\n", "AI solved it for me, here is the correct example:\nimport * as mongoose from 'mongoose';\nconst Schema = mongoose.Schema;\n\ninterface User {\n name: string;\n email: string;\n communities: Community[];\n}\n\ninterface Community {\n name: string;\n description: string;\n users: User[];\n}\n\nconst userSchema = new Schema({\n name: String,\n email: String,\n}, {\n timestamps: true,\n});\n\nconst communitySchema = new Schema({\n name: String,\n description: String,\n}, {\n timestamps: true,\n});\n\n// Define the user_communities table using the communitySchema\nconst userCommunitySchema = new Schema({\n user: { type: Schema.Types.ObjectId, ref: 'User' },\n community: { type: Schema.Types.ObjectId, ref: 'Community' },\n joined_on: Date,\n}, {\n timestamps: true,\n});\n\n// Use the userCommunitySchema to create the UserCommunity model\nconst UserCommunity = mongoose.model('UserCommunity', userCommunitySchema);\n\n// Use the userSchema to create the User model, and define a virtual property\n// for accessing the user's communities\nuserSchema.virtual('communities', {\n ref: 'Community',\n localField: '_id',\n foreignField: 'user',\n justOne: false,\n});\n\nconst User = mongoose.model<User>('User', userSchema);\n\n// Use the communitySchema to create the Community model, and define a virtual property\n// for accessing the community's users\ncommunitySchema.virtual('users', {\n ref: 'User',\n localField: '_id',\n foreignField: 'community',\n justOne: false,\n});\n\nconst Community = mongoose.model<Community>('Community', communitySchema);\n\nThe userSchema and communitySchema are then used to create the User and Community models, respectively. For the User model, a virtual property called communities is defined using the virtual method. This virtual property is used to specify how to populate the user.communities property when querying the database. The communitySchema also defines a users virtual property, which is used to populate the community.users property when querying.\n" ]
[ 1, 0 ]
[]
[]
[ "express", "mongoose" ]
stackoverflow_0074592435_express_mongoose.txt
Q: EF core Get Count and sum in one call Using Entity Framework core, can I get the total sum of the column and row count in one call? I have the following code, but I think there is a better way to do this. TotalCostResponse result = new TotalCostResponse { TotalCost = await dbContext.Transaction .Where(x => x.UserName == request.UserName && x.Date >= request.StartDate && x.Date <= request.EndDate) .SumAsync(x => x.Amount), TotalNumber = await dbContext.Transaction .Where(x => x.UserName == request.UserName && x.Date = request.StartDate && x.Date <= request.EndDate) .CountAsync() }; So instead of calling dbContext two times, I need to make it in one call. A: var result = await dbContext.Transaction .Where(x => x.UserName == request.UserName && x.Date >= request.StartDate && x.Date <= request.EndDate) .GroupBy(x => 1) .Select(group => new TotalCostResponse { TotalCost = group.Sum(x => x.Amount), TotalNumber = group.Count() }) .FirstOrDefaultAsync(); A: Yes, you can get the total sum and row count in a single call to the database using the Sum and Count methods together in a LINQ query. Here is an example of how you could do this: TotalCostResponse result = new TotalCostResponse { // Use the Sum and Count methods together in a LINQ query to get the total sum // and row count in a single call to the database. TotalCost = await dbContext.Transaction .Where(x => x.UserName == request.UserName && x.Date >= request.StartDate && x.Date <= request.EndDate) .Select(x => new { // Select the Amount column and use the Sum method to get the total sum. TotalCost = x.Amount.Sum(), // Use the Count method to get the row count. TotalNumber = x.Amount.Count() }) // Use the SingleOrDefault method to get the first element of the query result. // If the query result is empty, this will return null. .SingleOrDefault(), // If the query result is not null, set the TotalCost and TotalNumber properties // of the TotalCostResponse object using the values from the query result. // If the query result is null, these properties will remain uninitialized. TotalCost = result?.TotalCost, TotalNumber = result?.TotalNumber }; Alternatively, you could use the Sum and Count methods in separate LINQ queries and then combine the results in memory, like this: // Use the Sum method in a LINQ query to get the total sum. decimal? totalCost = await dbContext.Transaction .Where(x => x.UserName == request.UserName && x.Date >= request.StartDate && x.Date <= request.EndDate) .SumAsync(x => x.Amount); // Use the Count method in a LINQ query to get the row count. int? totalNumber = await dbContext.Transaction .Where(x => x.UserName == request.UserName && x.Date = request.StartDate && x.Date <= request.EndDate) .CountAsync(); TotalCostResponse result = new TotalCostResponse { // Set the TotalCost and TotalNumber properties of the TotalCostResponse // object using the values from the LINQ queries. TotalCost = totalCost, TotalNumber = totalNumber }; Both of these approaches will allow you to get the total sum and row count in a single call to the database, which should be more efficient than making two separate calls like in your original code. A: Here is an example with one querry, There are certainly other ways tath you can find. //In the select get only what you need, in your case only the Amount var transactions = await this.dbContext.Transaction .Where(x => x.UserName == request.UserName && x.Date >= request.StartDate && x.Date <= request.EndDate) .Select(y => new { Amount = y.Amount, }).ToListAsync(); //Calculating the data var result = new TotalCostResponse { TotalCost = transactions.Sum(x => x), TotalNumber = transactions.Count(), } //Dto model for the result public class TotalCostResponse { public decimal TotalCost { get; set; } public int TotalNumber { get; set; } }
EF core Get Count and sum in one call
Using Entity Framework core, can I get the total sum of the column and row count in one call? I have the following code, but I think there is a better way to do this. TotalCostResponse result = new TotalCostResponse { TotalCost = await dbContext.Transaction .Where(x => x.UserName == request.UserName && x.Date >= request.StartDate && x.Date <= request.EndDate) .SumAsync(x => x.Amount), TotalNumber = await dbContext.Transaction .Where(x => x.UserName == request.UserName && x.Date = request.StartDate && x.Date <= request.EndDate) .CountAsync() }; So instead of calling dbContext two times, I need to make it in one call.
[ "var result = await dbContext.Transaction\n .Where(x => x.UserName == request.UserName\n && x.Date >= request.StartDate\n && x.Date <= request.EndDate)\n .GroupBy(x => 1)\n .Select(group => new TotalCostResponse\n {\n TotalCost = group.Sum(x => x.Amount),\n TotalNumber = group.Count()\n })\n .FirstOrDefaultAsync();\n\n", "Yes, you can get the total sum and row count in a single call to the database using the Sum and Count methods together in a LINQ query. Here is an example of how you could do this:\nTotalCostResponse result = new TotalCostResponse\n{\n// Use the Sum and Count methods together in a LINQ query to get the total sum\n// and row count in a single call to the database.\nTotalCost = await dbContext.Transaction\n .Where(x => x.UserName == request.UserName\n && x.Date >= request.StartDate\n && x.Date <= request.EndDate)\n .Select(x => new\n {\n // Select the Amount column and use the Sum method to get the total sum.\n TotalCost = x.Amount.Sum(),\n // Use the Count method to get the row count.\n TotalNumber = x.Amount.Count()\n })\n // Use the SingleOrDefault method to get the first element of the query result.\n // If the query result is empty, this will return null.\n .SingleOrDefault(),\n\n// If the query result is not null, set the TotalCost and TotalNumber properties\n// of the TotalCostResponse object using the values from the query result.\n// If the query result is null, these properties will remain uninitialized.\nTotalCost = result?.TotalCost,\nTotalNumber = result?.TotalNumber\n};\n\nAlternatively, you could use the Sum and Count methods in separate LINQ queries and then combine the results in memory, like this:\n// Use the Sum method in a LINQ query to get the total sum.\ndecimal? totalCost = await dbContext.Transaction\n.Where(x => x.UserName == request.UserName\n && x.Date >= request.StartDate\n && x.Date <= request.EndDate)\n.SumAsync(x => x.Amount);\n\n// Use the Count method in a LINQ query to get the row count.\nint? totalNumber = await dbContext.Transaction\n.Where(x => x.UserName == request.UserName\n && x.Date = request.StartDate\n && x.Date <= request.EndDate)\n.CountAsync();\n\nTotalCostResponse result = new TotalCostResponse\n{\n// Set the TotalCost and TotalNumber properties of the TotalCostResponse\n// object using the values from the LINQ queries.\nTotalCost = totalCost,\nTotalNumber = totalNumber\n};\n\nBoth of these approaches will allow you to get the total sum and row count in a single call to the database, which should be more efficient than making two separate calls like in your original code.\n", "Here is an example with one querry, There are certainly other ways tath you can find.\n//In the select get only what you need, in your case only the Amount\nvar transactions = await this.dbContext.Transaction\n .Where(x => x.UserName == request.UserName\n && x.Date >= request.StartDate\n && x.Date <= request.EndDate)\n .Select(y => new\n {\n Amount = y.Amount,\n }).ToListAsync();\n\n//Calculating the data\nvar result = new TotalCostResponse\n{\n TotalCost = transactions.Sum(x => x),\n TotalNumber = transactions.Count(),\n}\n\n//Dto model for the result\npublic class TotalCostResponse\n{\n public decimal TotalCost { get; set; }\n public int TotalNumber { get; set; } \n}\n\n\n" ]
[ 3, 1, 0 ]
[]
[]
[ ".net_core", "c#", "entity_framework", "entity_framework_core" ]
stackoverflow_0074678001_.net_core_c#_entity_framework_entity_framework_core.txt
Q: update function does not go through all the line of codes inside it - Unity I have a problem where the line of codes in my Update function does not work. I added a debug.log both at the start and end of the update function but the whole if statement does not work. The dialogCycle variable does not even increment. Is there something wrong with the whole script? Here is the script: using System; using System.Linq; using TMPro; using UnityEngine; using UnityEngine.UI; public class TelevisionEvent : MonoBehaviour { [SerializeField] private GameData gameData; // SCRIPTABLEOBJECT [SerializeField] private GameObject dialogbox, interactButton; [SerializeField] private FollowPlayer followPlayer; [SerializeField] private Transform tv, player; [SerializeField] private TextAsset objectData; private ObjectDialog objectJson; public string[] dialogMessage; public int dialogCycle; public bool clickEnable; private void Update() { //if (gameData.isWatched) return; if (Input.GetMouseButtonDown(0) && clickEnable) { Debug.Log("Clicked"); // THIS WORKS dialogCycle++; // I PUT THIS OUTSIDE TO CHECK IF IT WILL WORK OUTSIDE THE IF BUT IT STILL DOES NOT tvDialog(); // THE DEBUG.LOG IS THE ONE THAT ONLY WORKS if (dialogCycle != dialogMessage.Length - 1) // BUT THIS WHOLE IF STATEMENT DOES NOT GET CHECKED { dialogCycle++; tvDialog(); } else { dialogbox.SetActive(false); dialogCycle = 0; Array.Clear(dialogMessage, 0, dialogMessage.Length); clickEnable = false; gameData.isWatched = true; followPlayer.player = player; } Debug.Log("Clicked2"); // THIS WORKS TOO } } private void OnTriggerEnter(Collider collisionInfo) { if(gameData.isWatched) return; if (collisionInfo.CompareTag("Player")) { interactButton.GetComponent<Button>().onClick.RemoveListener(tvDialog); interactButton.GetComponent<Button>().onClick.AddListener(tvDialog); } } private void OnTriggerExit(Collider collisionInfo) { Debug.Log("Hello"); if (gameData.isWatched) return; if (collisionInfo.CompareTag("Player")) { interactButton.GetComponent<Button>().onClick.RemoveListener(tvDialog); } } public void tvDialog() { dialogbox.SetActive(true); interactButton.SetActive(false); dialogCycle = 0; followPlayer.player = tv; objectJson = JsonUtility.FromJson<ObjectDialog>(objectData.text); loadDialog(); } public void loadDialog() { dialogbox.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = objectJson.name; dialogMessage = objectJson.object_dialog.Split('#'); dialogbox.transform.GetChild(1).GetComponent<TextMeshProUGUI>().text = dialogMessage[dialogCycle]; clickEnable = true; } } For more info, the game object that it is attached to have another script. Will it have an effect in this script? the other script is just like this but it is like an object interaction manager for the map (opening doors, etc.). By 'just like this' I mean there is also a line of codes similar to the prior script above. The script above is for an event when the player opens the door for the first time a television dialogue event will trigger. In the other script, I have the object interaction where I interact with object like a radio and the dialogue will show. I can just show you the script just for more info. the similarities will be in the update function and the last part of the script which is the objectDialog method using System; using System.Linq; using TMPro; using UnityEngine; using UnityEngine.UI; public class ObjectInteraction : MonoBehaviour { [SerializeField] private GameData gameData; [SerializeField] private GameObject interactButton, cafeArrow, aptArrow, konbiniArrow; [SerializeField] private GameObject cryptogram; [SerializeField] private GameObject dialogbox; private static ObjectInteraction instance; private ObjectDialog objectJson; private TextAsset objectData; private string[] dialogMessage; private int dialogCycle; private bool clickEnable; private int[] apartment = { 3, 8, 15, 16 }; // APARTMENT private int[] cafe = Enumerable.Range(0, 17).ToArray(); // CAFE private int[] konbini = { 77, 78, 82, 83 }; // CONVENIENT STORE private static bool isInside, isOpen; private void Start() { isInside = false; isOpen = false; //Debug.Log(dialogCycle); } private void Update() { //if (instance != this) return; if (Input.GetMouseButtonDown(0) && clickEnable) { if(dialogCycle != dialogMessage.Length-1) { dialogCycle++; loadDialog(); }else { dialogbox.SetActive(false); dialogCycle = 0; Array.Clear(dialogMessage, 0, dialogMessage.Length); clickEnable = false; } } } private void OnTriggerEnter(Collider collisionInfo) { if(collisionInfo.CompareTag("Player")) { if(gameObject.CompareTag("Door")) { interactButton.SetActive(true); interactButton.GetComponent<Image>().sprite = Resources.Load<Sprite>("InteractionAsset/OBJECT"); interactButton.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "Open"; interactButton.GetComponent<Button>().onClick.RemoveListener(enter); interactButton.GetComponent<Button>().onClick.AddListener(enter); } else if(gameObject.CompareTag("Newspaper")) { if (!gameData.cryptoDone) { interactButton.SetActive(true); interactButton.GetComponent<Image>().sprite = Resources.Load<Sprite>("InteractionAsset/OBJECT"); interactButton.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "View"; gameObject.GetComponent<Outline>().enabled = true; // ADD ONCLICK FOR NEWSPAPER interactButton.GetComponent<Button>().onClick.RemoveAllListeners(); interactButton.GetComponent<Button>().onClick.AddListener(showCryptogram); } } else if(gameObject.CompareTag("ObjectDialog")) { interactButton.SetActive(true); interactButton.GetComponent<Image>().sprite = Resources.Load<Sprite>("InteractionAsset/OBJECT"); interactButton.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "View"; gameObject.GetComponent<Outline>().enabled = true; interactButton.GetComponent<Button>().onClick.RemoveAllListeners(); interactButton.GetComponent<Button>().onClick.AddListener(objectDialog); } // WHEN LEAVING ROOMS if (gameObject.name == "apt_floor") { isInside = true; aptArrow.SetActive(true); } else if (gameObject.name == "cafe_floor") { isInside = true; cafeArrow.SetActive(true); } else if(gameObject.name == "konbini_floor") { isInside = true; konbiniArrow.SetActive(true); } } } private void OnTriggerExit(Collider collisionInfo) { interactButton.SetActive(false); interactButton.GetComponent<Button>().onClick.RemoveAllListeners(); if (collisionInfo.CompareTag("Player")) { // TURN OFF OUTLINE / HIGHLIGHT if(gameObject.CompareTag("Newspaper")) { gameObject.GetComponent<Outline>().enabled = false; } else if (gameObject.CompareTag("ObjectDialog")) { gameObject.GetComponent<Outline>().enabled = false; } // WHEN LEAVING ROOMS if (gameObject.name == "apt_floor" || (gameObject.name == "apt_wall" && !isInside && isOpen)) { for (int i = 0; i < apartment.Length; i++) { transform.root.GetChild(apartment[i]).GetComponent<MeshRenderer>().enabled = true; transform.root.GetChild(apartment[i]).gameObject.SetActive(true); } aptArrow.SetActive(false); } else if(gameObject.name == "cafe_floor" || (gameObject.name == "cafe_wall" && !isInside && isOpen)) { for (int i = 0; i < cafe.Length; i++) { if (i != 13) { transform.root.GetChild(cafe[i]).gameObject.SetActive(true); } } transform.root.GetChild(63).GetComponent<MeshRenderer>().enabled = true; transform.root.GetChild(67).GetComponent<MeshRenderer>().enabled = true; transform.root.GetChild(68).GetComponent<MeshRenderer>().enabled = true; transform.root.GetChild(59).gameObject.SetActive(true); cafeArrow.SetActive(false); } else if(gameObject.name == "konbini_floor" || (gameObject.name == "konbini_wall" && !isInside && isOpen)) { for (int i = 0; i < konbini.Length; i++) { transform.root.GetChild(konbini[i]).GetComponent<MeshRenderer>().enabled = true; } transform.root.GetChild(73).gameObject.SetActive(true); transform.root.GetChild(74).gameObject.SetActive(true); konbiniArrow.SetActive(false); } } } // ENTER ROOM public void enter() { FindObjectOfType<AudioManager>().Play("ButtonSound"); if (gameObject.name == "apt_door") { for(int i = 0; i < apartment.Length; i++) { transform.root.GetChild(apartment[i]).GetComponent<MeshRenderer>().enabled = false; } gameObject.SetActive(false); }else if(gameObject.name == "cafe_door") { for (int i = 0; i < cafe.Length; i++) { if(i != 13) { transform.root.GetChild(cafe[i]).gameObject.SetActive(false); } } transform.root.GetChild(63).GetComponent<MeshRenderer>().enabled = false; transform.root.GetChild(67).GetComponent<MeshRenderer>().enabled = false; transform.root.GetChild(68).GetComponent<MeshRenderer>().enabled = false; gameObject.SetActive(false); }else if(gameObject.name == "konbini_door1") { for (int i = 0; i < konbini.Length; i++) { transform.root.GetChild(konbini[i]).GetComponent<MeshRenderer>().enabled = false; } transform.root.GetChild(73).gameObject.SetActive(false); transform.root.GetChild(74).gameObject.SetActive(false); } isOpen = true; interactButton.SetActive(false); interactButton.GetComponent<Button>().onClick.RemoveListener(enter); } // SHOW CRYPTOGRAM MINIGAME IN OBJECT public void showCryptogram() { FindObjectOfType<AudioManager>().Play("ButtonSound"); cryptogram.SetActive(true); } public void objectDialog() { dialogbox.SetActive(true); interactButton.SetActive(false); dialogCycle = 0; loadJson(); loadDialog(); } public void loadJson() { if (gameObject.name == "Radio") { objectData = Resources.Load<TextAsset>("JSON/Objects/Radio"); }else if(gameObject.name == "Television") { objectData = Resources.Load<TextAsset>("JSON/Objects/TV"); } objectJson = JsonUtility.FromJson<ObjectDialog>(objectData.text); } public void loadDialog() { dialogbox.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = objectJson.name; dialogMessage = objectJson.object_dialog.Split('#'); if (dialogMessage.Length == 1) { dialogbox.transform.GetChild(1).GetComponent<TextMeshProUGUI>().text = objectJson.object_dialog; } else if (dialogCycle < dialogMessage.Length) { dialogbox.transform.GetChild(1).GetComponent<TextMeshProUGUI>().text = dialogMessage[dialogCycle]; clickEnable = true; } } } A: You set dialogCycle to 0 in tvDialog() after incrementing it, and in the else statement so it will never increment. A: Try to attach debugger and put breakpoint where you are trying to increment. Inspect variable and make some steps over and inspect again, try to press "Continue" and reach that breakpoint again. I assume there's something that assigns 0 to dialogCycle. It can't be otherwise because it is impossible that this operation just ignored
update function does not go through all the line of codes inside it - Unity
I have a problem where the line of codes in my Update function does not work. I added a debug.log both at the start and end of the update function but the whole if statement does not work. The dialogCycle variable does not even increment. Is there something wrong with the whole script? Here is the script: using System; using System.Linq; using TMPro; using UnityEngine; using UnityEngine.UI; public class TelevisionEvent : MonoBehaviour { [SerializeField] private GameData gameData; // SCRIPTABLEOBJECT [SerializeField] private GameObject dialogbox, interactButton; [SerializeField] private FollowPlayer followPlayer; [SerializeField] private Transform tv, player; [SerializeField] private TextAsset objectData; private ObjectDialog objectJson; public string[] dialogMessage; public int dialogCycle; public bool clickEnable; private void Update() { //if (gameData.isWatched) return; if (Input.GetMouseButtonDown(0) && clickEnable) { Debug.Log("Clicked"); // THIS WORKS dialogCycle++; // I PUT THIS OUTSIDE TO CHECK IF IT WILL WORK OUTSIDE THE IF BUT IT STILL DOES NOT tvDialog(); // THE DEBUG.LOG IS THE ONE THAT ONLY WORKS if (dialogCycle != dialogMessage.Length - 1) // BUT THIS WHOLE IF STATEMENT DOES NOT GET CHECKED { dialogCycle++; tvDialog(); } else { dialogbox.SetActive(false); dialogCycle = 0; Array.Clear(dialogMessage, 0, dialogMessage.Length); clickEnable = false; gameData.isWatched = true; followPlayer.player = player; } Debug.Log("Clicked2"); // THIS WORKS TOO } } private void OnTriggerEnter(Collider collisionInfo) { if(gameData.isWatched) return; if (collisionInfo.CompareTag("Player")) { interactButton.GetComponent<Button>().onClick.RemoveListener(tvDialog); interactButton.GetComponent<Button>().onClick.AddListener(tvDialog); } } private void OnTriggerExit(Collider collisionInfo) { Debug.Log("Hello"); if (gameData.isWatched) return; if (collisionInfo.CompareTag("Player")) { interactButton.GetComponent<Button>().onClick.RemoveListener(tvDialog); } } public void tvDialog() { dialogbox.SetActive(true); interactButton.SetActive(false); dialogCycle = 0; followPlayer.player = tv; objectJson = JsonUtility.FromJson<ObjectDialog>(objectData.text); loadDialog(); } public void loadDialog() { dialogbox.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = objectJson.name; dialogMessage = objectJson.object_dialog.Split('#'); dialogbox.transform.GetChild(1).GetComponent<TextMeshProUGUI>().text = dialogMessage[dialogCycle]; clickEnable = true; } } For more info, the game object that it is attached to have another script. Will it have an effect in this script? the other script is just like this but it is like an object interaction manager for the map (opening doors, etc.). By 'just like this' I mean there is also a line of codes similar to the prior script above. The script above is for an event when the player opens the door for the first time a television dialogue event will trigger. In the other script, I have the object interaction where I interact with object like a radio and the dialogue will show. I can just show you the script just for more info. the similarities will be in the update function and the last part of the script which is the objectDialog method using System; using System.Linq; using TMPro; using UnityEngine; using UnityEngine.UI; public class ObjectInteraction : MonoBehaviour { [SerializeField] private GameData gameData; [SerializeField] private GameObject interactButton, cafeArrow, aptArrow, konbiniArrow; [SerializeField] private GameObject cryptogram; [SerializeField] private GameObject dialogbox; private static ObjectInteraction instance; private ObjectDialog objectJson; private TextAsset objectData; private string[] dialogMessage; private int dialogCycle; private bool clickEnable; private int[] apartment = { 3, 8, 15, 16 }; // APARTMENT private int[] cafe = Enumerable.Range(0, 17).ToArray(); // CAFE private int[] konbini = { 77, 78, 82, 83 }; // CONVENIENT STORE private static bool isInside, isOpen; private void Start() { isInside = false; isOpen = false; //Debug.Log(dialogCycle); } private void Update() { //if (instance != this) return; if (Input.GetMouseButtonDown(0) && clickEnable) { if(dialogCycle != dialogMessage.Length-1) { dialogCycle++; loadDialog(); }else { dialogbox.SetActive(false); dialogCycle = 0; Array.Clear(dialogMessage, 0, dialogMessage.Length); clickEnable = false; } } } private void OnTriggerEnter(Collider collisionInfo) { if(collisionInfo.CompareTag("Player")) { if(gameObject.CompareTag("Door")) { interactButton.SetActive(true); interactButton.GetComponent<Image>().sprite = Resources.Load<Sprite>("InteractionAsset/OBJECT"); interactButton.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "Open"; interactButton.GetComponent<Button>().onClick.RemoveListener(enter); interactButton.GetComponent<Button>().onClick.AddListener(enter); } else if(gameObject.CompareTag("Newspaper")) { if (!gameData.cryptoDone) { interactButton.SetActive(true); interactButton.GetComponent<Image>().sprite = Resources.Load<Sprite>("InteractionAsset/OBJECT"); interactButton.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "View"; gameObject.GetComponent<Outline>().enabled = true; // ADD ONCLICK FOR NEWSPAPER interactButton.GetComponent<Button>().onClick.RemoveAllListeners(); interactButton.GetComponent<Button>().onClick.AddListener(showCryptogram); } } else if(gameObject.CompareTag("ObjectDialog")) { interactButton.SetActive(true); interactButton.GetComponent<Image>().sprite = Resources.Load<Sprite>("InteractionAsset/OBJECT"); interactButton.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "View"; gameObject.GetComponent<Outline>().enabled = true; interactButton.GetComponent<Button>().onClick.RemoveAllListeners(); interactButton.GetComponent<Button>().onClick.AddListener(objectDialog); } // WHEN LEAVING ROOMS if (gameObject.name == "apt_floor") { isInside = true; aptArrow.SetActive(true); } else if (gameObject.name == "cafe_floor") { isInside = true; cafeArrow.SetActive(true); } else if(gameObject.name == "konbini_floor") { isInside = true; konbiniArrow.SetActive(true); } } } private void OnTriggerExit(Collider collisionInfo) { interactButton.SetActive(false); interactButton.GetComponent<Button>().onClick.RemoveAllListeners(); if (collisionInfo.CompareTag("Player")) { // TURN OFF OUTLINE / HIGHLIGHT if(gameObject.CompareTag("Newspaper")) { gameObject.GetComponent<Outline>().enabled = false; } else if (gameObject.CompareTag("ObjectDialog")) { gameObject.GetComponent<Outline>().enabled = false; } // WHEN LEAVING ROOMS if (gameObject.name == "apt_floor" || (gameObject.name == "apt_wall" && !isInside && isOpen)) { for (int i = 0; i < apartment.Length; i++) { transform.root.GetChild(apartment[i]).GetComponent<MeshRenderer>().enabled = true; transform.root.GetChild(apartment[i]).gameObject.SetActive(true); } aptArrow.SetActive(false); } else if(gameObject.name == "cafe_floor" || (gameObject.name == "cafe_wall" && !isInside && isOpen)) { for (int i = 0; i < cafe.Length; i++) { if (i != 13) { transform.root.GetChild(cafe[i]).gameObject.SetActive(true); } } transform.root.GetChild(63).GetComponent<MeshRenderer>().enabled = true; transform.root.GetChild(67).GetComponent<MeshRenderer>().enabled = true; transform.root.GetChild(68).GetComponent<MeshRenderer>().enabled = true; transform.root.GetChild(59).gameObject.SetActive(true); cafeArrow.SetActive(false); } else if(gameObject.name == "konbini_floor" || (gameObject.name == "konbini_wall" && !isInside && isOpen)) { for (int i = 0; i < konbini.Length; i++) { transform.root.GetChild(konbini[i]).GetComponent<MeshRenderer>().enabled = true; } transform.root.GetChild(73).gameObject.SetActive(true); transform.root.GetChild(74).gameObject.SetActive(true); konbiniArrow.SetActive(false); } } } // ENTER ROOM public void enter() { FindObjectOfType<AudioManager>().Play("ButtonSound"); if (gameObject.name == "apt_door") { for(int i = 0; i < apartment.Length; i++) { transform.root.GetChild(apartment[i]).GetComponent<MeshRenderer>().enabled = false; } gameObject.SetActive(false); }else if(gameObject.name == "cafe_door") { for (int i = 0; i < cafe.Length; i++) { if(i != 13) { transform.root.GetChild(cafe[i]).gameObject.SetActive(false); } } transform.root.GetChild(63).GetComponent<MeshRenderer>().enabled = false; transform.root.GetChild(67).GetComponent<MeshRenderer>().enabled = false; transform.root.GetChild(68).GetComponent<MeshRenderer>().enabled = false; gameObject.SetActive(false); }else if(gameObject.name == "konbini_door1") { for (int i = 0; i < konbini.Length; i++) { transform.root.GetChild(konbini[i]).GetComponent<MeshRenderer>().enabled = false; } transform.root.GetChild(73).gameObject.SetActive(false); transform.root.GetChild(74).gameObject.SetActive(false); } isOpen = true; interactButton.SetActive(false); interactButton.GetComponent<Button>().onClick.RemoveListener(enter); } // SHOW CRYPTOGRAM MINIGAME IN OBJECT public void showCryptogram() { FindObjectOfType<AudioManager>().Play("ButtonSound"); cryptogram.SetActive(true); } public void objectDialog() { dialogbox.SetActive(true); interactButton.SetActive(false); dialogCycle = 0; loadJson(); loadDialog(); } public void loadJson() { if (gameObject.name == "Radio") { objectData = Resources.Load<TextAsset>("JSON/Objects/Radio"); }else if(gameObject.name == "Television") { objectData = Resources.Load<TextAsset>("JSON/Objects/TV"); } objectJson = JsonUtility.FromJson<ObjectDialog>(objectData.text); } public void loadDialog() { dialogbox.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = objectJson.name; dialogMessage = objectJson.object_dialog.Split('#'); if (dialogMessage.Length == 1) { dialogbox.transform.GetChild(1).GetComponent<TextMeshProUGUI>().text = objectJson.object_dialog; } else if (dialogCycle < dialogMessage.Length) { dialogbox.transform.GetChild(1).GetComponent<TextMeshProUGUI>().text = dialogMessage[dialogCycle]; clickEnable = true; } } }
[ "You set dialogCycle to 0 in tvDialog() after incrementing it, and in the else statement so it will never increment.\n", "Try to attach debugger and put breakpoint where you are trying to increment. Inspect variable and make some steps over and inspect again, try to press \"Continue\" and reach that breakpoint again. I assume there's something that assigns 0 to dialogCycle. It can't be otherwise because it is impossible that this operation just ignored\n" ]
[ 0, 0 ]
[]
[]
[ "c#", "if_statement", "unity3d" ]
stackoverflow_0074678396_c#_if_statement_unity3d.txt
Q: How to use `last()` when mutating by group with {dbplyr}? Consider the following remote table: library(dbplyr) library(dplyr, w = F) remote_data <- memdb_frame( grp = c(2, 2, 2, 1, 3, 1, 1), win = c("B", "C", "A", "B", "C", "A", "C"), id = c(1,3,5,7,2,4,6), ) I wish to group by grp, order by win and take the last id. This is fairly straightforward if I collect first # intended output when collecting first remote_data %>% collect() %>% arrange(grp, win) %>% group_by(grp) %>% mutate(last_id = last(id)) %>% ungroup() #> # A tibble: 7 × 4 #> grp win id last_id #> <dbl> <chr> <dbl> <dbl> #> 1 1 A 4 6 #> 2 1 B 7 6 #> 3 1 C 6 6 #> 4 2 A 5 3 #> 5 2 B 1 3 #> 6 2 C 3 3 #> 7 3 C 2 2 However I cannot directly convert this to {dbplyr} code by removing collect(), though the SQL code doesn't look bad, what's happening here ? remote_data %>% arrange(grp, win) %>% group_by(grp) %>% mutate(last_id = last(id)) %>% ungroup() %>% print() %>% show_query() #> # Source: SQL [7 x 4] #> # Database: sqlite 3.39.4 [:memory:] #> # Ordered by: grp, win #> grp win id last_id #> <dbl> <chr> <dbl> <dbl> #> 1 1 A 4 4 #> 2 1 B 7 7 #> 3 1 C 6 6 #> 4 2 A 5 5 #> 5 2 B 1 1 #> 6 2 C 3 3 #> 7 3 C 2 2 #> <SQL> #> SELECT #> *, #> LAST_VALUE(`id`) OVER (PARTITION BY `grp` ORDER BY `grp`, `win`) AS `last_id` #> FROM `dbplyr_001` #> ORDER BY `grp`, `win` dbplyr::window_order() allows us to override th ORDER BY clause created by the group_by(), I tried window_order(,win), but no cookie: remote_data %>% arrange(grp, win) %>% group_by(grp) %>% window_order(win) %>% mutate(last_id = last(id)) %>% ungroup() %>% print() %>% show_query() #> # Source: SQL [7 x 4] #> # Database: sqlite 3.39.4 [:memory:] #> # Ordered by: win #> grp win id last_id #> <dbl> <chr> <dbl> <dbl> #> 1 1 A 4 4 #> 2 1 B 7 7 #> 3 1 C 6 6 #> 4 2 A 5 5 #> 5 2 B 1 1 #> 6 2 C 3 3 #> 7 3 C 2 2 #> <SQL> #> SELECT *, LAST_VALUE(`id`) OVER (PARTITION BY `grp` ORDER BY `win`) AS `last_id` #> FROM `dbplyr_001` #> ORDER BY `grp`, `win` For some reason window_order(,grp) does trigger a window calculation but not with the expected order: remote_data %>% arrange(grp, win) %>% group_by(grp) %>% window_order(grp) %>% mutate(last_id = last(id)) %>% ungroup() %>% print() %>% show_query() #> # Source: SQL [7 x 4] #> # Database: sqlite 3.39.4 [:memory:] #> # Ordered by: grp #> grp win id last_id #> <dbl> <chr> <dbl> <dbl> #> 1 1 A 4 6 #> 2 1 B 7 6 #> 3 1 C 6 6 #> 4 2 A 5 5 #> 5 2 B 1 5 #> 6 2 C 3 5 #> 7 3 C 2 2 #> <SQL> #> SELECT *, LAST_VALUE(`id`) OVER (PARTITION BY `grp` ORDER BY `grp`) AS `last_id` #> FROM `dbplyr_001` #> ORDER BY `grp`, `win` What can I do to keep my initial output with only remote computations, preferably {dbplyr} code ? A: Here is a work around using a join, but that's not very satisfying, possibly inefficient too: lkp <- remote_data %>% group_by(grp) %>% filter(win == max(win, na.rm = TRUE)) %>% ungroup() %>% select(grp, last_id = id) %>% distinct() remote_data %>% left_join(lkp, by = "grp") %>% arrange(grp, win) %>% print() %>% show_query() #> # Source: SQL [7 x 4] #> # Database: sqlite 3.39.4 [:memory:] #> # Ordered by: grp, win #> grp win id last_id #> <dbl> <chr> <dbl> <dbl> #> 1 1 A 4 6 #> 2 1 B 7 6 #> 3 1 C 6 6 #> 4 2 A 5 3 #> 5 2 B 1 3 #> 6 2 C 3 3 #> 7 3 C 2 2 #> <SQL> #> SELECT * #> FROM ( #> SELECT `LHS`.`grp` AS `grp`, `win`, `id`, `last_id` #> FROM `dbplyr_001` AS `LHS` #> LEFT JOIN ( #> SELECT DISTINCT `grp`, `id` AS `last_id` #> FROM ( #> SELECT `grp`, `win`, `id` #> FROM ( #> SELECT *, MAX(`win`) OVER (PARTITION BY `grp`) AS `q01` #> FROM `dbplyr_001` #> ) #> WHERE (`win` = `q01`) #> ) #> ) AS `RHS` #> ON (`LHS`.`grp` = `RHS`.`grp`) #> ) #> ORDER BY `grp`, `win` Created on 2022-12-04 with reprex v2.0.2 A: While last() seems to be broken first() appears to work as expected, so you could make use of the order_by argument to get the last value: library(dbplyr) library(dplyr, w = F) remote_data %>% arrange(grp, win) %>% group_by(grp) %>% mutate(last_id = first(id, order_by = desc(win))) %>% ungroup() %>% print() %>% show_query() # Source: SQL [7 x 4] # Database: sqlite 3.39.4 [:memory:] # Ordered by: grp, win grp win id last_id <dbl> <chr> <dbl> <dbl> 1 1 A 4 6 2 1 B 7 6 3 1 C 6 6 4 2 A 5 3 5 2 B 1 3 6 2 C 3 3 7 3 C 2 2 <SQL> SELECT *, FIRST_VALUE(`id`) OVER (PARTITION BY `grp` ORDER BY `win` DESC) AS `last_id` FROM `dbplyr_001` ORDER BY `grp`, `win`
How to use `last()` when mutating by group with {dbplyr}?
Consider the following remote table: library(dbplyr) library(dplyr, w = F) remote_data <- memdb_frame( grp = c(2, 2, 2, 1, 3, 1, 1), win = c("B", "C", "A", "B", "C", "A", "C"), id = c(1,3,5,7,2,4,6), ) I wish to group by grp, order by win and take the last id. This is fairly straightforward if I collect first # intended output when collecting first remote_data %>% collect() %>% arrange(grp, win) %>% group_by(grp) %>% mutate(last_id = last(id)) %>% ungroup() #> # A tibble: 7 × 4 #> grp win id last_id #> <dbl> <chr> <dbl> <dbl> #> 1 1 A 4 6 #> 2 1 B 7 6 #> 3 1 C 6 6 #> 4 2 A 5 3 #> 5 2 B 1 3 #> 6 2 C 3 3 #> 7 3 C 2 2 However I cannot directly convert this to {dbplyr} code by removing collect(), though the SQL code doesn't look bad, what's happening here ? remote_data %>% arrange(grp, win) %>% group_by(grp) %>% mutate(last_id = last(id)) %>% ungroup() %>% print() %>% show_query() #> # Source: SQL [7 x 4] #> # Database: sqlite 3.39.4 [:memory:] #> # Ordered by: grp, win #> grp win id last_id #> <dbl> <chr> <dbl> <dbl> #> 1 1 A 4 4 #> 2 1 B 7 7 #> 3 1 C 6 6 #> 4 2 A 5 5 #> 5 2 B 1 1 #> 6 2 C 3 3 #> 7 3 C 2 2 #> <SQL> #> SELECT #> *, #> LAST_VALUE(`id`) OVER (PARTITION BY `grp` ORDER BY `grp`, `win`) AS `last_id` #> FROM `dbplyr_001` #> ORDER BY `grp`, `win` dbplyr::window_order() allows us to override th ORDER BY clause created by the group_by(), I tried window_order(,win), but no cookie: remote_data %>% arrange(grp, win) %>% group_by(grp) %>% window_order(win) %>% mutate(last_id = last(id)) %>% ungroup() %>% print() %>% show_query() #> # Source: SQL [7 x 4] #> # Database: sqlite 3.39.4 [:memory:] #> # Ordered by: win #> grp win id last_id #> <dbl> <chr> <dbl> <dbl> #> 1 1 A 4 4 #> 2 1 B 7 7 #> 3 1 C 6 6 #> 4 2 A 5 5 #> 5 2 B 1 1 #> 6 2 C 3 3 #> 7 3 C 2 2 #> <SQL> #> SELECT *, LAST_VALUE(`id`) OVER (PARTITION BY `grp` ORDER BY `win`) AS `last_id` #> FROM `dbplyr_001` #> ORDER BY `grp`, `win` For some reason window_order(,grp) does trigger a window calculation but not with the expected order: remote_data %>% arrange(grp, win) %>% group_by(grp) %>% window_order(grp) %>% mutate(last_id = last(id)) %>% ungroup() %>% print() %>% show_query() #> # Source: SQL [7 x 4] #> # Database: sqlite 3.39.4 [:memory:] #> # Ordered by: grp #> grp win id last_id #> <dbl> <chr> <dbl> <dbl> #> 1 1 A 4 6 #> 2 1 B 7 6 #> 3 1 C 6 6 #> 4 2 A 5 5 #> 5 2 B 1 5 #> 6 2 C 3 5 #> 7 3 C 2 2 #> <SQL> #> SELECT *, LAST_VALUE(`id`) OVER (PARTITION BY `grp` ORDER BY `grp`) AS `last_id` #> FROM `dbplyr_001` #> ORDER BY `grp`, `win` What can I do to keep my initial output with only remote computations, preferably {dbplyr} code ?
[ "Here is a work around using a join, but that's not very satisfying, possibly inefficient too:\nlkp <- remote_data %>% \n group_by(grp) %>% \n filter(win == max(win, na.rm = TRUE)) %>% \n ungroup() %>% \n select(grp, last_id = id) %>% \n distinct()\n\nremote_data %>% \n left_join(lkp, by = \"grp\") %>% \n arrange(grp, win) %>% \n print() %>% \n show_query()\n#> # Source: SQL [7 x 4]\n#> # Database: sqlite 3.39.4 [:memory:]\n#> # Ordered by: grp, win\n#> grp win id last_id\n#> <dbl> <chr> <dbl> <dbl>\n#> 1 1 A 4 6\n#> 2 1 B 7 6\n#> 3 1 C 6 6\n#> 4 2 A 5 3\n#> 5 2 B 1 3\n#> 6 2 C 3 3\n#> 7 3 C 2 2\n#> <SQL>\n#> SELECT *\n#> FROM (\n#> SELECT `LHS`.`grp` AS `grp`, `win`, `id`, `last_id`\n#> FROM `dbplyr_001` AS `LHS`\n#> LEFT JOIN (\n#> SELECT DISTINCT `grp`, `id` AS `last_id`\n#> FROM (\n#> SELECT `grp`, `win`, `id`\n#> FROM (\n#> SELECT *, MAX(`win`) OVER (PARTITION BY `grp`) AS `q01`\n#> FROM `dbplyr_001`\n#> )\n#> WHERE (`win` = `q01`)\n#> )\n#> ) AS `RHS`\n#> ON (`LHS`.`grp` = `RHS`.`grp`)\n#> )\n#> ORDER BY `grp`, `win`\n\nCreated on 2022-12-04 with reprex v2.0.2\n", "While last() seems to be broken first() appears to work as expected, so you could make use of the order_by argument to get the last value:\nlibrary(dbplyr)\nlibrary(dplyr, w = F)\n\nremote_data %>% \n arrange(grp, win) %>% \n group_by(grp) %>% \n mutate(last_id = first(id, order_by = desc(win))) %>% \n ungroup() %>% \n print() %>% \n show_query()\n\n# Source: SQL [7 x 4]\n# Database: sqlite 3.39.4 [:memory:]\n# Ordered by: grp, win\n grp win id last_id\n <dbl> <chr> <dbl> <dbl>\n1 1 A 4 6\n2 1 B 7 6\n3 1 C 6 6\n4 2 A 5 3\n5 2 B 1 3\n6 2 C 3 3\n7 3 C 2 2\n<SQL>\nSELECT\n *,\n FIRST_VALUE(`id`) OVER (PARTITION BY `grp` ORDER BY `win` DESC) AS `last_id`\nFROM `dbplyr_001`\nORDER BY `grp`, `win`\n\n" ]
[ 1, 1 ]
[]
[]
[ "dbplyr", "dplyr", "r", "sql" ]
stackoverflow_0074677042_dbplyr_dplyr_r_sql.txt
Q: Prevent duplicates when updating a record in Laravel using validation So I am trying to update a record with multiple fields in my database using laravel, however I am trying to validate the input first before proceeding with the actual updating of the record. So my problem is that one of my field has to be unique and should allow the other fields to be edited even if that field is not edited. I know that in the document it is that we can use this code to do that. use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule;   Validator::make($data, [ 'email' => [ 'required', Rule::unique('users')->ignore($user->id), ], ]); However, the id that is supposed to be used in the ignore method is also validated. 'product_id' => 'required|string|exists:' . Product::class, 'product_name' => 'required|unique:' . Product::class, 'product_stock_amount' => 'required|integer|numeric|gte:0', 'product_price' => 'required|integer|numeric|gte:0', 'product_price_currency' => 'required|string|', 'product_description' => 'nullable|string' I am confused on how should I apply the recommendation in the documentation to my validation rules. My idea is to check if the product exists with the product_id then proceedd with the rest of the validation but I don't know if that is correct and I am afraid that would make my code vulnerable to attacks. Any recommendations on how to solve this? A: To allow multiple fields to be edited while still validating the unique constraint for one of the fields, you can use the ignore method in your validation rules like this: use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule; Validator::make($data, [ 'product_id' => 'required|string|exists:' . Product::class, 'product_name' => [ 'required', Rule::unique('products')->ignore($data['product_id'], 'product_id'), ], 'product_stock_amount' => 'required|integer|numeric|gte:0', 'product_price' => 'required|integer|numeric|gte:0', 'product_price_currency' => 'required|string|', 'product_description' => 'nullable|string' ]); In this example, the product_name field will be validated for uniqueness, but will allow the record with the specified product_id to be updated even if the product_name does not change. Keep in mind that the ignore method should be used with caution to avoid potential vulnerabilities. In this case, the product_id field should be validated using the exists rule to ensure that the specified product_id exists in the database before using it in the ignore method. This helps to prevent potential attacks where a non-existent product_id is provided to bypass the unique constraint. A: In your case, you can use the ignore method of the unique rule to specify that the unique rule should be ignored for the current product. You can do this by passing the product_id of the current product as the argument to the ignore method, like this: use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule; $validator = Validator::make($data, [ 'product_id' => 'required|string|exists:' . Product::class, 'product_name' => [ 'required', Rule::unique('products')->ignore($data['product_id']), ], 'product_stock_amount' => 'required|integer|numeric|gte:0', 'product_price' => 'required|integer|numeric|gte:0', 'product_price_currency' => 'required|string|', 'product_description' => 'nullable|string' ]); This will ensure that the product_name must be unique, but it will be ignored if the current product has the same product_name as the one being updated. It's also a good idea to verify that the product_id provided in the request exists in the products table. You can do this by using the exists rule, as shown above. This will help prevent attacks where a user tries to update a product that does not exist. Once you have validated the input, you can proceed with updating the product in the database.
Prevent duplicates when updating a record in Laravel using validation
So I am trying to update a record with multiple fields in my database using laravel, however I am trying to validate the input first before proceeding with the actual updating of the record. So my problem is that one of my field has to be unique and should allow the other fields to be edited even if that field is not edited. I know that in the document it is that we can use this code to do that. use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule;   Validator::make($data, [ 'email' => [ 'required', Rule::unique('users')->ignore($user->id), ], ]); However, the id that is supposed to be used in the ignore method is also validated. 'product_id' => 'required|string|exists:' . Product::class, 'product_name' => 'required|unique:' . Product::class, 'product_stock_amount' => 'required|integer|numeric|gte:0', 'product_price' => 'required|integer|numeric|gte:0', 'product_price_currency' => 'required|string|', 'product_description' => 'nullable|string' I am confused on how should I apply the recommendation in the documentation to my validation rules. My idea is to check if the product exists with the product_id then proceedd with the rest of the validation but I don't know if that is correct and I am afraid that would make my code vulnerable to attacks. Any recommendations on how to solve this?
[ "To allow multiple fields to be edited while still validating the unique constraint for one of the fields, you can use the ignore method in your validation rules like this:\nuse Illuminate\\Support\\Facades\\Validator;\nuse Illuminate\\Validation\\Rule;\n \nValidator::make($data, [\n 'product_id' => 'required|string|exists:' . Product::class,\n 'product_name' => [\n 'required',\n Rule::unique('products')->ignore($data['product_id'], 'product_id'),\n ],\n 'product_stock_amount' => 'required|integer|numeric|gte:0',\n 'product_price' => 'required|integer|numeric|gte:0',\n 'product_price_currency' => 'required|string|',\n 'product_description' => 'nullable|string'\n]);\n\nIn this example, the product_name field will be validated for uniqueness, but will allow the record with the specified product_id to be updated even if the product_name does not change.\nKeep in mind that the ignore method should be used with caution to avoid potential vulnerabilities. In this case, the product_id field should be validated using the exists rule to ensure that the specified product_id exists in the database before using it in the ignore method. This helps to prevent potential attacks where a non-existent product_id is provided to bypass the unique constraint.\n", "In your case, you can use the ignore method of the unique rule to specify that the unique rule should be ignored for the current product. You can do this by passing the product_id of the current product as the argument to the ignore method, like this:\nuse Illuminate\\Support\\Facades\\Validator;\nuse Illuminate\\Validation\\Rule;\n\n$validator = Validator::make($data, [\n 'product_id' => 'required|string|exists:' . Product::class,\n 'product_name' => [\n 'required',\n Rule::unique('products')->ignore($data['product_id']),\n ],\n 'product_stock_amount' => 'required|integer|numeric|gte:0',\n 'product_price' => 'required|integer|numeric|gte:0',\n 'product_price_currency' => 'required|string|',\n 'product_description' => 'nullable|string'\n]);\n\nThis will ensure that the product_name must be unique, but it will be ignored if the current product has the same product_name as the one being updated.\nIt's also a good idea to verify that the product_id provided in the request exists in the products table. You can do this by using the exists rule, as shown above. This will help prevent attacks where a user tries to update a product that does not exist.\nOnce you have validated the input, you can proceed with updating the product in the database.\n" ]
[ 0, 0 ]
[]
[]
[ "laravel", "laravel_9", "php" ]
stackoverflow_0074678537_laravel_laravel_9_php.txt
Q: Linked List issue when inserting a new item in Javascript I have the next implementation of Linked List: class Node { constructor(data) { this.data = data; this.next = null; } } class LinkedLIst { constructor() { this.head = {}; } add(head) { if(!this.head.next) { this.head = new Node(head); } this.head.next = new Node(head); } } const list = new LinkedLIst(); list.add(1) list.add(2) list.add(3) console.log(list) I don't understand, why 2 is not added within the list? And how to fix that? A: Since this is a linked list, I am assuming you want to insert at the end. To do that, you can create a tail property. Then, in you add method, you can check if no elements exist, then set the head and tail to the new node. If there is at least 1 element, you can set the tail's next to the new node and finally, make the tail point to the new node. class Node { constructor(data) { this.data = data; this.next = null; } } class LinkedLIst { constructor() { this.head = null; this.tail = null; } add(value) { const newNode = new Node(value) if (this.head === null) { this.head = this.tail = newNode } else { this.tail.next = newNode this.tail = newNode; } } } const list = new LinkedLIst(); list.add(1) list.add(2) list.add(3) console.log(list) A: if you don't want to use tail just iterate until the end of the linklist class Node { constructor(data) { this.data = data; this.next = null; } } class LinkedLIst { constructor() { this.head = null; } add(head) { if(!this.head) { this.head = new Node(head); }else{ let ptr = this.head; while(ptr.next!==null){ ptr = ptr.next; } ptr.next=new Node(head); } } } const list = new LinkedLIst(); list.add(1) list.add(2) list.add(3) console.log(list)
Linked List issue when inserting a new item in Javascript
I have the next implementation of Linked List: class Node { constructor(data) { this.data = data; this.next = null; } } class LinkedLIst { constructor() { this.head = {}; } add(head) { if(!this.head.next) { this.head = new Node(head); } this.head.next = new Node(head); } } const list = new LinkedLIst(); list.add(1) list.add(2) list.add(3) console.log(list) I don't understand, why 2 is not added within the list? And how to fix that?
[ "Since this is a linked list, I am assuming you want to insert at the end. To do that, you can create a tail property.\nThen, in you add method, you can check if no elements exist, then set the head and tail to the new node. If there is at least 1 element, you can set the tail's next to the new node and finally, make the tail point to the new node.\n\n\nclass Node {\n constructor(data) {\n this.data = data;\n this.next = null;\n }\n}\n\nclass LinkedLIst {\n constructor() {\n this.head = null;\n this.tail = null;\n }\n\n add(value) { \n const newNode = new Node(value)\n if (this.head === null) {\n this.head = this.tail = newNode\n } else {\n this.tail.next = newNode\n this.tail = newNode;\n }\n }\n}\n\n\nconst list = new LinkedLIst();\nlist.add(1)\nlist.add(2)\nlist.add(3)\n\n\nconsole.log(list)\n\n\n\n", "if you don't want to use tail just iterate until the end of the linklist\n\n\nclass Node {\n constructor(data) {\n this.data = data;\n this.next = null;\n }\n}\n\nclass LinkedLIst {\n constructor() {\n this.head = null;\n }\n\n add(head) { \n \n if(!this.head) {\n this.head = new Node(head);\n }else{\n let ptr = this.head; \n while(ptr.next!==null){\n ptr = ptr.next;\n }\n ptr.next=new Node(head);\n }\n \n \n }\n}\n\n\nconst list = new LinkedLIst();\nlist.add(1)\nlist.add(2)\nlist.add(3)\n\n\nconsole.log(list)\n\n\n\n" ]
[ 1, 1 ]
[]
[]
[ "javascript" ]
stackoverflow_0074678432_javascript.txt
Q: Javascript addEventListener is Not being Executed or is There an await Problem I have a Chrome extension with the following js code in the initial HTML. (async() => { console.log("Starting wrapper"); await document.getElementById("start").addEventListener("click",sendStart); await document.getElementById("stop").addEventListener("click",sendStop); await document.getElementById("config").addEventListener("click",sendConfig); let {started} =await chrome.storage.session.get("started"); if (started===undefined) { await chrome.storage.local.set({status:false}); await chrome.storage.session.set({started:true}); } let run=await chrome.storage.local.get("status"); if (!run.status || Object.keys(run)==0) { document.getElementById("start").disabled=false; document.getElementById("stop").disable=true; document.getElementById("config").disabled=false; } else { document.getElementById("start").disabled=true; document.getElementById("stop").disabled=false; document.getElementById("config").disabled=true; } tmrs_obj= await chrome.storage.local.get("tmrs"); document.getElementById("tmrs").innerHTML=tmrs_obj.tmrs; console.log("wrapper setup complete"); })(); The problem is when I click on the "start" button the listener does not seem to get triggered. In the console, all I see, when I click the "start" button is: Starting wrapper wrapper setup complete In the listener I have a console.log statement that outputs that the listener was executed but that never shows up. The only thing I can think of is that when I click the "start" button the listener is not yet set up. However, even if I wait to click that button it still does not execute the listener. Oddly however, after trying 2 or 3 times (quitting each time) it finally works. Can someone help me debug this? TIA.
Javascript addEventListener is Not being Executed or is There an await Problem
I have a Chrome extension with the following js code in the initial HTML. (async() => { console.log("Starting wrapper"); await document.getElementById("start").addEventListener("click",sendStart); await document.getElementById("stop").addEventListener("click",sendStop); await document.getElementById("config").addEventListener("click",sendConfig); let {started} =await chrome.storage.session.get("started"); if (started===undefined) { await chrome.storage.local.set({status:false}); await chrome.storage.session.set({started:true}); } let run=await chrome.storage.local.get("status"); if (!run.status || Object.keys(run)==0) { document.getElementById("start").disabled=false; document.getElementById("stop").disable=true; document.getElementById("config").disabled=false; } else { document.getElementById("start").disabled=true; document.getElementById("stop").disabled=false; document.getElementById("config").disabled=true; } tmrs_obj= await chrome.storage.local.get("tmrs"); document.getElementById("tmrs").innerHTML=tmrs_obj.tmrs; console.log("wrapper setup complete"); })(); The problem is when I click on the "start" button the listener does not seem to get triggered. In the console, all I see, when I click the "start" button is: Starting wrapper wrapper setup complete In the listener I have a console.log statement that outputs that the listener was executed but that never shows up. The only thing I can think of is that when I click the "start" button the listener is not yet set up. However, even if I wait to click that button it still does not execute the listener. Oddly however, after trying 2 or 3 times (quitting each time) it finally works. Can someone help me debug this? TIA.
[]
[]
[ "wrap the code inside the event listener in an async function:\ndocument.getElementById(\"start\").addEventListener(\"click\", async function() {\n// Your code \n});\n\nAlso you can remove the await keyword from inside the event listener and use a regular then callback instead\ndocument.getElementById(\"start\").addEventListener(\"click\", function() {\n// Your code \n});\n\n" ]
[ -1 ]
[ "addeventlistener", "async.js", "google_chrome_extension", "javascript" ]
stackoverflow_0074678608_addeventlistener_async.js_google_chrome_extension_javascript.txt
Q: Mypy is not able to find an attribute defined in the parent NamedTuple In my project I'm using Fava. Fava, is using Beancount. I have configured Mypy to read the stubs locally by setting mypy_path in mypy.ini. Mypy is able to read the config. So far so good. Consider this function of mine 1 def get_units(postings: list[Posting]): 2 numbers = [] 3 for posting in postings: 4 numbers.append(posting.units.number) 5 return numbers When I run mypy src I get the following error report.py:4 error: Item "type" of "Union[Amount, Type[MISSING]]" has no attribute "number" [union-attr] When I check the defined stub here I can see the type of units which is Amount. Now, Amount is inheriting number from its parent _Amount. Going back to the stubs in Fava I can see the type here. My question is why mypy is not able to find the attribute number although it is defined in the stubs? A: The type of units isn't Amount: class Posting(NamedTuple): account: Account units: Union[Amount, Type[MISSING]] It's Union[Amount, Type[MISSING]], exactly like the error message says. And if it's Type[MISSING] there is no number attribute, exactly like the error message says. If you were to run this code and units were in fact MISSING, it would raise an AttributeError on trying to access that number attribute. (Aside: I'm not familiar with beancount, but this seems like a weird interface to me -- the more idiomatic thing IMO would be to just make it an Optional[Amount] with None representing the "missing" case.) You need to change your code to account for the MISSING possibility so that mypy knows you're aware of it (and also so that readers of your code can see that possibility before it bites them in the form of an AttributeError). Something like: for posting in postings: assert isinstance(posting.units, Amount), "Units are MISSING!" numbers.append(posting.units.number) Obviously if you want your code to do something other than raise an AssertionError on MISSING units, you should write your code to do that instead of assert. If you want to just assume that it's an Amount and raise an AttributeError at runtime if it's not, use typing.cast to tell mypy that you want to consider it to be an Amount even though the type stub says otherwise: for posting in postings: # posting.units might be MISSING, but let's assume it's not numbers.append(cast(Amount, posting.units).number)
Mypy is not able to find an attribute defined in the parent NamedTuple
In my project I'm using Fava. Fava, is using Beancount. I have configured Mypy to read the stubs locally by setting mypy_path in mypy.ini. Mypy is able to read the config. So far so good. Consider this function of mine 1 def get_units(postings: list[Posting]): 2 numbers = [] 3 for posting in postings: 4 numbers.append(posting.units.number) 5 return numbers When I run mypy src I get the following error report.py:4 error: Item "type" of "Union[Amount, Type[MISSING]]" has no attribute "number" [union-attr] When I check the defined stub here I can see the type of units which is Amount. Now, Amount is inheriting number from its parent _Amount. Going back to the stubs in Fava I can see the type here. My question is why mypy is not able to find the attribute number although it is defined in the stubs?
[ "The type of units isn't Amount:\nclass Posting(NamedTuple):\n account: Account\n units: Union[Amount, Type[MISSING]]\n\nIt's Union[Amount, Type[MISSING]], exactly like the error message says. And if it's Type[MISSING] there is no number attribute, exactly like the error message says. If you were to run this code and units were in fact MISSING, it would raise an AttributeError on trying to access that number attribute.\n(Aside: I'm not familiar with beancount, but this seems like a weird interface to me -- the more idiomatic thing IMO would be to just make it an Optional[Amount] with None representing the \"missing\" case.)\nYou need to change your code to account for the MISSING possibility so that mypy knows you're aware of it (and also so that readers of your code can see that possibility before it bites them in the form of an AttributeError). Something like:\nfor posting in postings:\n assert isinstance(posting.units, Amount), \"Units are MISSING!\"\n numbers.append(posting.units.number)\n\nObviously if you want your code to do something other than raise an AssertionError on MISSING units, you should write your code to do that instead of assert.\nIf you want to just assume that it's an Amount and raise an AttributeError at runtime if it's not, use typing.cast to tell mypy that you want to consider it to be an Amount even though the type stub says otherwise:\nfor posting in postings:\n # posting.units might be MISSING, but let's assume it's not\n numbers.append(cast(Amount, posting.units).number)\n\n" ]
[ 3 ]
[]
[]
[ "mypy", "python" ]
stackoverflow_0074678602_mypy_python.txt
Q: PySpark incrementally add id based on another column and previous data Increammentally derive ID from a **name ** column and on next load if there are new values added to that name column then assign ned ID which is not already assigned to previous data Example: first load Name a b b a result ID Name 1 a 2 b 2 b 1 a next load Name a b b a c d c result ID Name 1 a 2 b 2 b 1 a 3 c 4 d 3 c As described in question looking for a solution in PySpark A: You can use window and dense_rank. The code below will make dataframe sorted by 'name' column and give each unique name an incremental unique id. from pyspark.sql import functions as F from pyspark.sql import types as T from pyspark.sql import Window as W window = W.orderBy('name') ( df .withColumn('id', F.dense_rank().over(window)) ).show() +----+---+ |name| id| +----+---+ | a| 1| | a| 1| | b| 2| | b| 2| | c| 3| | c| 3| | d| 4| +----+---+ A: You can create additional dataframe df_map where you store your IDs between loads. If you need to, you can save and restore this dataframe from the disk. df1 = spark.createDataFrame( data=[['a'], ['b'], ['b'], ['a']], schema=["name"] ) df2 = spark.createDataFrame( data=[['a'], ['b'], ['b'], ['a'], ['c'], ['d'], ['c'], ['0']], schema=["name"] ) w = Window.orderBy('name') # create empty map df_map = spark.createDataFrame([], schema='name string, id int') df_map.show() # get additional name->id map for df1 n = df_map.select(F.count('id').alias('n')).collect()[0].n df_map = df1.subtract(df_map.select('name')).withColumn('id', F.row_number().over(w) + F.lit(n)).union(df_map) df_map.show() # map can be saved to disk between runs # get additional name->id map for df2 n = df_map.select(F.count('id').alias('n')).collect()[0].n df_map = df2.subtract(df_map.select('name')).withColumn('id', F.row_number().over(w) + F.lit(n)).union(df_map) df_map.show() # join to get the final dataframe df2.join(df_map, on='name').show()
PySpark incrementally add id based on another column and previous data
Increammentally derive ID from a **name ** column and on next load if there are new values added to that name column then assign ned ID which is not already assigned to previous data Example: first load Name a b b a result ID Name 1 a 2 b 2 b 1 a next load Name a b b a c d c result ID Name 1 a 2 b 2 b 1 a 3 c 4 d 3 c As described in question looking for a solution in PySpark
[ "You can use window and dense_rank. The code below will make dataframe sorted by 'name' column and give each unique name an incremental unique id.\nfrom pyspark.sql import functions as F\nfrom pyspark.sql import types as T\nfrom pyspark.sql import Window as W\n\nwindow = W.orderBy('name')\n(\n df\n .withColumn('id', F.dense_rank().over(window))\n).show() \n\n+----+---+\n|name| id|\n+----+---+\n| a| 1|\n| a| 1|\n| b| 2|\n| b| 2|\n| c| 3|\n| c| 3|\n| d| 4|\n+----+---+\n\n", "You can create additional dataframe df_map where you store your IDs between loads. If you need to, you can save and restore this dataframe from the disk.\ndf1 = spark.createDataFrame(\n data=[['a'], ['b'], ['b'], ['a']],\n schema=[\"name\"]\n)\ndf2 = spark.createDataFrame(\n data=[['a'], ['b'], ['b'], ['a'], ['c'], ['d'], ['c'], ['0']],\n schema=[\"name\"]\n)\n\nw = Window.orderBy('name')\n\n# create empty map\ndf_map = spark.createDataFrame([], schema='name string, id int')\ndf_map.show()\n\n# get additional name->id map for df1\nn = df_map.select(F.count('id').alias('n')).collect()[0].n\ndf_map = df1.subtract(df_map.select('name')).withColumn('id', F.row_number().over(w) + F.lit(n)).union(df_map)\ndf_map.show()\n\n# map can be saved to disk between runs\n\n# get additional name->id map for df2\nn = df_map.select(F.count('id').alias('n')).collect()[0].n\ndf_map = df2.subtract(df_map.select('name')).withColumn('id', F.row_number().over(w) + F.lit(n)).union(df_map)\ndf_map.show()\n\n# join to get the final dataframe\ndf2.join(df_map, on='name').show()\n\n" ]
[ 0, 0 ]
[]
[]
[ "apache_spark_sql", "pyspark", "user_defined_functions" ]
stackoverflow_0074675378_apache_spark_sql_pyspark_user_defined_functions.txt
Q: ws.write = (result.join(',') + '\n'); && TypeError: result.join is not a function ...how i solve this type error help to solve in this javascript problem. Give me clear documentation about (join). function main() { const ws = fs.createWriteStream(process.env.OUTPUT_PATH); const a = readLine().replace(/\s+$/g, '').split(' ').map(aTemp => parseInt(aTemp, 10)); const b = readLine().replace(/\s+$/g, '').split(' ').map(bTemp => parseInt(bTemp, 10)); const result = compareTriplets(a, b); ws.write = (result.join(',') + '\n'); ws.end(); } A: Clear documentation for join const result = compareTriplets(a, b); Not sure what compareTriplets is but based on the word compare I am assuming it returns a boolean. You are trying to join a boolean expression. If you want one string containing of A and B then put A and B into an array and then use join. But with so little information it is hard to understand what you are trying to accomplish. Based on your code I am assuming A and B both are arrays. If you want to join the elements together do this. Also assuming result is a boolean. function main() { const ws = fs.createWriteStream(process.env.OUTPUT_PATH); const a = readLine().replace(/\s+$/g, '').split(' ').map(aTemp => parseInt(aTemp, 10)); const b = readLine().replace(/\s+$/g, '').split(' ').map(bTemp => parseInt(bTemp, 10)); const result = compareTriplets(a, b); if(result){ ws.write = (a.join(',') + ',' + b.join(',') + '\n'); } ws.end(); } A: I have gone through the same issue in a problem on Hackkerank,what i was doing wrong was that i was returning results as "return(scoreOfA , scoreOfB)" but the correct format was "return([scoreOfA,scoreOfB])" as it is using "join" which takes an array as an input . function compareTriplets(a, b) { let scoreA=0,scoreB=0; for(let i=0;i<3;i++){ if(a[i] > b[i]){ scoreA += 1} else if(a[i]< b[i]){ scoreB += 1} } return ([scoreA,scoreB]) } } A: Anyone who has encountered this issue while doing a test on Hackerrank using javascript. They should not use console.log in the middle of the loops instead they should create an array and push console.log data into that array and then return that array at the end of the function.
ws.write = (result.join(',') + '\n'); && TypeError: result.join is not a function ...how i solve this type error
help to solve in this javascript problem. Give me clear documentation about (join). function main() { const ws = fs.createWriteStream(process.env.OUTPUT_PATH); const a = readLine().replace(/\s+$/g, '').split(' ').map(aTemp => parseInt(aTemp, 10)); const b = readLine().replace(/\s+$/g, '').split(' ').map(bTemp => parseInt(bTemp, 10)); const result = compareTriplets(a, b); ws.write = (result.join(',') + '\n'); ws.end(); }
[ "Clear documentation for join\nconst result = compareTriplets(a, b);\n\nNot sure what compareTriplets is but based on the word compare I am assuming it returns a boolean. You are trying to join a boolean expression. If you want one string containing of A and B then put A and B into an array and then use join. But with so little information it is hard to understand what you are trying to accomplish.\nBased on your code I am assuming A and B both are arrays. If you want to join the elements together do this. Also assuming result is a boolean.\nfunction main() {\nconst ws = fs.createWriteStream(process.env.OUTPUT_PATH);\n\nconst a = readLine().replace(/\\s+$/g, '').split(' ').map(aTemp => parseInt(aTemp, 10));\n\nconst b = readLine().replace(/\\s+$/g, '').split(' ').map(bTemp => parseInt(bTemp, 10));\n\nconst result = compareTriplets(a, b);\n\nif(result){\n ws.write = (a.join(',') + ',' + b.join(',') + '\\n');\n}\nws.end();\n}\n\n", "I have gone through the same issue in a problem on Hackkerank,what i was doing wrong was that i was returning results as \"return(scoreOfA , scoreOfB)\" but the correct format was \"return([scoreOfA,scoreOfB])\" as it is using \"join\" which takes an array as an input .\nfunction compareTriplets(a, b) {\nlet scoreA=0,scoreB=0;\n\nfor(let i=0;i<3;i++){\nif(a[i] > b[i]){ scoreA += 1}\nelse if(a[i]< b[i]){ scoreB += 1}\n}\nreturn ([scoreA,scoreB])\n}\n}\n\n", "Anyone who has encountered this issue while doing a test on Hackerrank using javascript. They should not use console.log in the middle of the loops instead they should create an array and push console.log data into that array and then return that array at the end of the function.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "javascript" ]
stackoverflow_0065047354_javascript.txt
Q: Discord.py, If message length is bigger than a specific number, break it into several lines I need help. If the message is longer than a specific number I want the message breaks into several lines Example: Displayed Message: Hello everyone!, I'm AHMED, how are you guys? what are you doing? Edit: Hello everyone!, I'm AHMED, how are you guys? what are you doing? Can anyone help me with that? A: Maybe try this one. I used strip() to make sure there won't be any blank characters at the start of a new line. sentence = "Hello everyone!, I'm AHMED, how are you guys? what are you doing?" edited = sentence if len(sentence) > 90: edited = sentence[:90].strip() + "..." elif len(sentence) > 45: edited = sentence[:45] + "\n" + sentence[45:].strip() print(edited) Output: Hello everyone!, I'm AHMED, how are you guys? what are you doing? A: use \n to break the lines hope it helps you.
Discord.py, If message length is bigger than a specific number, break it into several lines
I need help. If the message is longer than a specific number I want the message breaks into several lines Example: Displayed Message: Hello everyone!, I'm AHMED, how are you guys? what are you doing? Edit: Hello everyone!, I'm AHMED, how are you guys? what are you doing? Can anyone help me with that?
[ "Maybe try this one. I used strip() to make sure there won't be any blank characters at the start of a new line.\nsentence = \"Hello everyone!, I'm AHMED, how are you guys? what are you doing?\"\nedited = sentence\n\nif len(sentence) > 90:\n edited = sentence[:90].strip() + \"...\"\n\nelif len(sentence) > 45:\n edited = sentence[:45] + \"\\n\" + sentence[45:].strip()\n\nprint(edited)\n\nOutput:\nHello everyone!, I'm AHMED, how are you guys?\nwhat are you doing?\n\n", "use \\n to break the lines hope it helps you.\n" ]
[ 2, 0 ]
[]
[]
[ "discord.py" ]
stackoverflow_0069948459_discord.py.txt
Q: Mongo DB - add date to reference object I am using mongoose and have two schemas, user and community: UserSchema: const UserSchema = new Schema({ name: String, communities: [{ type: Schema.Types.ObjectId, ref: CommunityModel }], }, { timestamps: true }); } Community: const CommunitySchema = new Schema({ name: String, users: [ { type: Schema.Types.ObjectId, ref: "User" } ] }, { timestamps: true }); When user joins a community, I want to know when it happened, so I'd like to add a joinedAt or createdAt to each community in the UserSchema. How could I achieve it if it is a reference? Is it possible? And if not, what could be the alternative? Thanks! A: This is the correct answer: AI solved it for me, here is the correct example: import * as mongoose from 'mongoose'; const Schema = mongoose.Schema; interface User { name: string; email: string; communities: Community[]; } interface Community { name: string; description: string; users: User[]; } const userSchema = new Schema({ name: String, email: String, }, { timestamps: true, }); const communitySchema = new Schema({ name: String, description: String, }, { timestamps: true, }); // Define the user_communities table using the communitySchema const userCommunitySchema = new Schema({ user: { type: Schema.Types.ObjectId, ref: 'User' }, community: { type: Schema.Types.ObjectId, ref: 'Community' }, joined_on: Date, }, { timestamps: true, }); // Use the userCommunitySchema to create the UserCommunity model const UserCommunity = mongoose.model('UserCommunity', userCommunitySchema); // Use the userSchema to create the User model, and define a virtual property // for accessing the user's communities userSchema.virtual('communities', { ref: 'Community', localField: '_id', foreignField: 'user', justOne: false, }); const User = mongoose.model<User>('User', userSchema); // Use the communitySchema to create the Community model, and define a virtual property // for accessing the community's users communitySchema.virtual('users', { ref: 'User', localField: '_id', foreignField: 'community', justOne: false, }); const Community = mongoose.model<Community>('Community', communitySchema); The userSchema and communitySchema are then used to create the User and Community models, respectively. For the User model, a virtual property called communities is defined using the virtual method. This virtual property is used to specify how to populate the user.communities property when querying the database. The communitySchema also defines a users virtual property, which is used to populate the community.users property when querying.
Mongo DB - add date to reference object
I am using mongoose and have two schemas, user and community: UserSchema: const UserSchema = new Schema({ name: String, communities: [{ type: Schema.Types.ObjectId, ref: CommunityModel }], }, { timestamps: true }); } Community: const CommunitySchema = new Schema({ name: String, users: [ { type: Schema.Types.ObjectId, ref: "User" } ] }, { timestamps: true }); When user joins a community, I want to know when it happened, so I'd like to add a joinedAt or createdAt to each community in the UserSchema. How could I achieve it if it is a reference? Is it possible? And if not, what could be the alternative? Thanks!
[ "This is the correct answer:\nAI solved it for me, here is the correct example:\nimport * as mongoose from 'mongoose';\nconst Schema = mongoose.Schema;\n\ninterface User {\n name: string;\n email: string;\n communities: Community[];\n}\n\ninterface Community {\n name: string;\n description: string;\n users: User[];\n}\n\nconst userSchema = new Schema({\n name: String,\n email: String,\n}, {\n timestamps: true,\n});\n\nconst communitySchema = new Schema({\n name: String,\n description: String,\n}, {\n timestamps: true,\n});\n\n// Define the user_communities table using the communitySchema\nconst userCommunitySchema = new Schema({\n user: { type: Schema.Types.ObjectId, ref: 'User' },\n community: { type: Schema.Types.ObjectId, ref: 'Community' },\n joined_on: Date,\n}, {\n timestamps: true,\n});\n\n// Use the userCommunitySchema to create the UserCommunity model\nconst UserCommunity = mongoose.model('UserCommunity', userCommunitySchema);\n\n// Use the userSchema to create the User model, and define a virtual property\n// for accessing the user's communities\nuserSchema.virtual('communities', {\n ref: 'Community',\n localField: '_id',\n foreignField: 'user',\n justOne: false,\n});\n\nconst User = mongoose.model<User>('User', userSchema);\n\n// Use the communitySchema to create the Community model, and define a virtual property\n// for accessing the community's users\ncommunitySchema.virtual('users', {\n ref: 'User',\n localField: '_id',\n foreignField: 'community',\n justOne: false,\n});\n\nconst Community = mongoose.model<Community>('Community', communitySchema);\n\nThe userSchema and communitySchema are then used to create the User and Community models, respectively. For the User model, a virtual property called communities is defined using the virtual method. This virtual property is used to specify how to populate the user.communities property when querying the database. The communitySchema also defines a users virtual property, which is used to populate the community.users property when querying.\n" ]
[ 0 ]
[]
[]
[ "mongodb", "mongoose" ]
stackoverflow_0074674813_mongodb_mongoose.txt
Q: how to Decryption correct method my Decryption text consider all characters are ASCII 65 how to correct way decryption characters result += char(int(chiper_text[i] - 65 - Cshift_key ) % 26 + 65) how To correct method to decryption A: To correct the decryption method in your code, you can use the ord() and chr() functions to convert between ASCII character codes and actual characters. For example, you could replace the following line of code: result += char(int(chiper_text[i] - 65 - Cshift_key ) % 26 + 65) with this: result += chr((ord(chiper_text[i]) - ord('A') - Cshift_key) % 26 + ord('A')) This code uses the ord() function to convert the character at index i in the chiper_text string to its corresponding ASCII code, and then subtracts the ASCII code for 'A' to get the 0-based index of the character within the alphabet. It then applies the shift key and takes the modulo 26 to wrap around to the beginning of the alphabet if necessary. Finally, it uses the chr() function to convert the resulting index back to a character and adds it to the result string. It's also worth noting that the original code uses the char() function, which is not a standard Python function. In Python, the equivalent function is chr(), which converts an ASCII code to a character. You should use chr() instead of char() in your code.
how to Decryption correct method
my Decryption text consider all characters are ASCII 65 how to correct way decryption characters result += char(int(chiper_text[i] - 65 - Cshift_key ) % 26 + 65) how To correct method to decryption
[ "To correct the decryption method in your code, you can use the ord() and chr() functions to convert between ASCII character codes and actual characters. For example, you could replace the following line of code:\nresult += char(int(chiper_text[i] - 65 - Cshift_key ) % 26 + 65)\n\n\nwith this:\nresult += chr((ord(chiper_text[i]) - ord('A') - Cshift_key) % 26 + ord('A'))\n\nThis code uses the ord() function to convert the character at index i in the chiper_text string to its corresponding ASCII code, and then subtracts the ASCII code for 'A' to get the 0-based index of the character within the alphabet. It then applies the shift key and takes the modulo 26 to wrap around to the beginning of the alphabet if necessary. Finally, it uses the chr() function to convert the resulting index back to a character and adds it to the result string.\nIt's also worth noting that the original code uses the char() function, which is not a standard Python function. In Python, the equivalent function is chr(), which converts an ASCII code to a character. You should use chr() instead of char() in your code.\n" ]
[ 0 ]
[]
[]
[ "c++", "ooad" ]
stackoverflow_0074678534_c++_ooad.txt
Q: Displaying real time data on 7 segment i wonder how the real time data from microcontroller (TMS320F28835) can be displayed on 7-segment. I can view the data(float or int data type) on expression window in code composer studio but i want to display that data on 7 segment(SND3360). Need help for this problem. Any refernece code or manual for this problem will be helpful. Looking for reference code or technical manual. A: The SND3360 is a very basic 6 digit display with no controller/multiplexer. For each digit you must have all the common cathode digit pins normally high, then set the segment pins for one digit and pull its cathode low to illuminate the selected LEDs. You would after a short delay reset the cathode high, then repeat for the next digit. By cycling through each digit rapidly and regularly persistence of vision will give the impression that all 6 digits are displayed. You need to do this in software in such a way that the digit refresh rate is not affected but other code running. One way of doing that is to update the display in a timer interrupt handler or a high priority RTOS thread. A hardware solution (and therefore off-topic) is to use a BCD to 7-Segment display decoder (e.g. CD5411to drive the segment pins, in that case your MCU needs just 4 pins instead of 8 to define the digit, and then 6 lines to select the digit - you could further use a multiplexer (e.g. 74137) to select one of 6 digit pins using just three GPIO, so with the BCD decoder and output multiplexer, you can connect the display using just 7 GPIO rather than 14 driving it directly from MCU GPIO. It also simplifies the software. Even simpler is to use a controller chip specifically designed to drive exactly this type of display. For example the STLED316S. That can be driven from a three-wire serial interface. The controller handles all the multiplexing and refresh for you.
Displaying real time data on 7 segment
i wonder how the real time data from microcontroller (TMS320F28835) can be displayed on 7-segment. I can view the data(float or int data type) on expression window in code composer studio but i want to display that data on 7 segment(SND3360). Need help for this problem. Any refernece code or manual for this problem will be helpful. Looking for reference code or technical manual.
[ "The SND3360 is a very basic 6 digit display with no controller/multiplexer. For each digit you must have all the common cathode digit pins normally high, then set the segment pins for one digit and pull its cathode low to illuminate the selected LEDs. You would after a short delay reset the cathode high, then repeat for the next digit. By cycling through each digit rapidly and regularly persistence of vision will give the impression that all 6 digits are displayed.\nYou need to do this in software in such a way that the digit refresh rate is not affected but other code running. One way of doing that is to update the display in a timer interrupt handler or a high priority RTOS thread.\nA hardware solution (and therefore off-topic) is to use a BCD to 7-Segment display decoder (e.g. CD5411to drive the segment pins, in that case your MCU needs just 4 pins instead of 8 to define the digit, and then 6 lines to select the digit - you could further use a multiplexer (e.g. 74137) to select one of 6 digit pins using just three GPIO, so with the BCD decoder and output multiplexer, you can connect the display using just 7 GPIO rather than 14 driving it directly from MCU GPIO. It also simplifies the software.\nEven simpler is to use a controller chip specifically designed to drive exactly this type of display. For example the STLED316S. That can be driven from a three-wire serial interface. The controller handles all the multiplexing and refresh for you.\n" ]
[ 0 ]
[]
[]
[ "clock", "controls", "embedded", "microcontroller", "texas_instruments" ]
stackoverflow_0074674631_clock_controls_embedded_microcontroller_texas_instruments.txt
Q: How to assign dynamic variables calling from a function in python I have a function which does a bunch of stuff and returns pandas dataframes. The dataframe is extracted from a dynamic list and hence I'm using the below method to return these dataframes. As soon as I call the function (code in 2nd block), my jupyter notebook just runs the cell infinitely like some infinity loop. Any idea how I can do this more efficiently. funct(x): some code which creates multiple dataframes i = 0 for k in range(len(dynamic_list)): i += 1 return globals()["df" + str(i)] The next thing I do is call the function and try to assign it dynamically, i = 0 for k in range(len(dynamic_list)): i += 1 globals()["new_df" + str(i)] = funct(x) I have tried returning selective dataframes from first function and it works just fine, like, funct(x): some code returning df1, df2, df3....., df_n return df1, df2 new_df1, new_df2 = funct(x) A: for each dataframe object your code is creating you can simply add it to a dictionary and set the key from your dynamic list. Here is a simple example: import pandas as pd test_data = {"key1":[1, 2, 3], "key2":[1, 2, 3], "key3":[1, 2, 3]} df = pd.DataFrame.from_dict(test_data) dataframe example: key1 key2 key3 0 1 1 1 1 2 2 2 2 3 3 3 I have used a fixed list of values to focus on but this can be dynamic based on however you are creating them. values_of_interest_list = [1, 3] Now we can do whatever we want to do with the dataframe, in this instance, I want to filter only data where we have a value from our list. data_dict = {} for value_of_interest in values_of_interest_list: x_df = df[df["key1"] == value_of_interest] data_dict[value_of_interest] = x_df To see what we have, we can print out the created dictionary that contains the key we have assigned and the associated dataframe object. for key, value in data_dict.items(): print(type(key)) print(type(value)) Which returns <class 'int'> <class 'pandas.core.frame.DataFrame'> <class 'int'> <class 'pandas.core.frame.DataFrame'> Full sample code is below: import pandas as pd test_data = {"key1":[1, 2, 3], "key2":[1, 2, 3], "key3":[1, 2, 3]} df = pd.DataFrame.from_dict(test_data) values_of_interest_list = [1, 3] # Dictionary for data data_dict = {} # Loop though the values of interest for value_of_interest in values_of_interest_list: x_df = df[df["key1"] == value_of_interest] data_dict[value_of_interest] = x_df for key, value in data_dict.items(): print(type(key)) print(type(value))
How to assign dynamic variables calling from a function in python
I have a function which does a bunch of stuff and returns pandas dataframes. The dataframe is extracted from a dynamic list and hence I'm using the below method to return these dataframes. As soon as I call the function (code in 2nd block), my jupyter notebook just runs the cell infinitely like some infinity loop. Any idea how I can do this more efficiently. funct(x): some code which creates multiple dataframes i = 0 for k in range(len(dynamic_list)): i += 1 return globals()["df" + str(i)] The next thing I do is call the function and try to assign it dynamically, i = 0 for k in range(len(dynamic_list)): i += 1 globals()["new_df" + str(i)] = funct(x) I have tried returning selective dataframes from first function and it works just fine, like, funct(x): some code returning df1, df2, df3....., df_n return df1, df2 new_df1, new_df2 = funct(x)
[ "for each dataframe object your code is creating you can simply add it to a dictionary and set the key from your dynamic list.\nHere is a simple example:\nimport pandas as pd\n\ntest_data = {\"key1\":[1, 2, 3], \"key2\":[1, 2, 3], \"key3\":[1, 2, 3]}\ndf = pd.DataFrame.from_dict(test_data)\n\ndataframe example:\n key1 key2 key3\n0 1 1 1\n1 2 2 2\n2 3 3 3\n\nI have used a fixed list of values to focus on but this can be dynamic based on however you are creating them.\nvalues_of_interest_list = [1, 3]\n\nNow we can do whatever we want to do with the dataframe, in this instance, I want to filter only data where we have a value from our list.\ndata_dict = {}\n\nfor value_of_interest in values_of_interest_list:\n\n x_df = df[df[\"key1\"] == value_of_interest]\n\n data_dict[value_of_interest] = x_df\n\nTo see what we have, we can print out the created dictionary that contains the key we have assigned and the associated dataframe object.\nfor key, value in data_dict.items():\n print(type(key))\n print(type(value))\n\nWhich returns\n<class 'int'>\n<class 'pandas.core.frame.DataFrame'>\n<class 'int'>\n<class 'pandas.core.frame.DataFrame'>\n\nFull sample code is below:\nimport pandas as pd\n\ntest_data = {\"key1\":[1, 2, 3], \"key2\":[1, 2, 3], \"key3\":[1, 2, 3]}\ndf = pd.DataFrame.from_dict(test_data)\n\nvalues_of_interest_list = [1, 3]\n\n# Dictionary for data\ndata_dict = {}\n\n# Loop though the values of interest\nfor value_of_interest in values_of_interest_list:\n\n x_df = df[df[\"key1\"] == value_of_interest]\n\n data_dict[value_of_interest] = x_df\n\n\nfor key, value in data_dict.items():\n print(type(key))\n print(type(value))\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074672341_pandas_python.txt
Q: Read and write a text file in typescript How should I read and write a text file from typescript in node.js? I am not sure would read/write a file be sandboxed in node.js, if not, i believe there should be a way in accessing file system. A: believe there should be a way in accessing file system. Include node.d.ts using npm i @types/node. And then create a new tsconfig.json file (npx tsc --init) and create a .ts file as followed: import * as fs from 'fs'; fs.readFileSync('foo.txt','utf8'); You can use other functions in fs as well : https://nodejs.org/api/fs.html More Node quick start : https://basarat.gitbook.io/typescript/nodejs A: import { readFileSync } from 'fs'; const file = readFileSync('./filename.txt', 'utf-8'); This worked for me. You may need to wrap the second command in any function or you may need to declare inside a class without keyword const. A: First you will need to install node definitions for Typescript. You can find the definitions file here: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts Once you've got file, just add the reference to your .ts file like this: /// <reference path="path/to/node.d.ts" /> Then you can code your typescript class that read/writes, using the Node File System module. Your typescript class myClass.ts can look like this: /// <reference path="path/to/node.d.ts" /> class MyClass { // Here we import the File System module of node private fs = require('fs'); constructor() { } createFile() { this.fs.writeFile('file.txt', 'I am cool!', function(err) { if (err) { return console.error(err); } console.log("File created!"); }); } showFile() { this.fs.readFile('file.txt', function (err, data) { if (err) { return console.error(err); } console.log("Asynchronous read: " + data.toString()); }); } } // Usage // var obj = new MyClass(); // obj.createFile(); // obj.showFile(); Once you transpile your .ts file to a javascript (check out here if you don't know how to do it), you can run your javascript file with node and let the magic work: > node myClass.js A: import * as fs from 'fs'; import * as path from 'path'; fs.readFile(path.join(__dirname, "filename.txt"), (err, data) => { if (err) throw err; console.log(data); }) EDIT: consider the project structure: ../readfile/ ├── filename.txt └── src ├── index.js └── index.ts consider the index.ts: import * as fs from 'fs'; import * as path from 'path'; function lookFilesInDirectory(path_directory) { fs.stat(path_directory, (err, stat) => { if (!err) { if (stat.isDirectory()) { console.log(path_directory) fs.readdirSync(path_directory).forEach(file => { console.log(`\t${file}`); }); console.log(); } } }); } let path_view = './'; lookFilesInDirectory(path_view); lookFilesInDirectory(path.join(__dirname, path_view)); if you have in the readfile folder and run tsc src/index.ts && node src/index.js, the output will be: ./ filename.txt src /home/andrei/scripts/readfile/src/ index.js index.ts that is, it depends on where you run the node. the __dirname is directory name of the current module. A: Just to clarify: if ever the TS 2307: Cannot find module import error appears: check the tsconfig.json file. It must contain node_modules { ..... "include": [ "src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "tests/**/*.ts", "tests/**/*.tsx", "node_modules" ], ..... } A: I encounter "Cannot find module 'fs' or its corresponding type declarations" when import { readFileSync } from 'fs'; How I solve it A bit deviation from Jerome Villiseck's ans Edit tsconfig.app.json: ... "include": [ "src/**/*.d.ts", "node_modules/@types/node/" ] ... A: It is possible to write file in ts. But something how its js. You can install jquery to run javascript in angular. npm i jquery Import in it in angular.json file and use this code var fileWriter = new Writer(); var fileName = "test_syskey/Test.doc"; fileWriter.removeFile(fileName, function(err,url) { if (err) { resp.error("Write failed"); } else { resp.success(url); } });
Read and write a text file in typescript
How should I read and write a text file from typescript in node.js? I am not sure would read/write a file be sandboxed in node.js, if not, i believe there should be a way in accessing file system.
[ "\nbelieve there should be a way in accessing file system.\n\nInclude node.d.ts using npm i @types/node. And then create a new tsconfig.json file (npx tsc --init) and create a .ts file as followed:\nimport * as fs from 'fs';\nfs.readFileSync('foo.txt','utf8');\n\nYou can use other functions in fs as well : https://nodejs.org/api/fs.html\nMore\nNode quick start : https://basarat.gitbook.io/typescript/nodejs\n", "import { readFileSync } from 'fs';\n\nconst file = readFileSync('./filename.txt', 'utf-8');\n\nThis worked for me.\nYou may need to wrap the second command in any function or you may need to declare inside a class without keyword const.\n", "First you will need to install node definitions for Typescript. You can find the definitions file here:\nhttps://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts\nOnce you've got file, just add the reference to your .ts file like this:\n/// <reference path=\"path/to/node.d.ts\" />\nThen you can code your typescript class that read/writes, using the Node File System module. Your typescript class myClass.ts can look like this:\n/// <reference path=\"path/to/node.d.ts\" />\n\nclass MyClass {\n\n // Here we import the File System module of node\n private fs = require('fs');\n\n constructor() { }\n\n createFile() {\n\n this.fs.writeFile('file.txt', 'I am cool!', function(err) {\n if (err) {\n return console.error(err);\n }\n console.log(\"File created!\");\n });\n }\n\n showFile() {\n\n this.fs.readFile('file.txt', function (err, data) {\n if (err) {\n return console.error(err);\n }\n console.log(\"Asynchronous read: \" + data.toString());\n });\n }\n}\n\n// Usage\n// var obj = new MyClass();\n// obj.createFile();\n// obj.showFile();\n\nOnce you transpile your .ts file to a javascript (check out here if you don't know how to do it), you can run your javascript file with node and let the magic work:\n> node myClass.js\n\n", "import * as fs from 'fs';\nimport * as path from 'path';\n\nfs.readFile(path.join(__dirname, \"filename.txt\"), (err, data) => {\n if (err) throw err;\n console.log(data);\n})\n\n\nEDIT:\nconsider the project structure:\n../readfile/\n├── filename.txt\n└── src\n ├── index.js\n └── index.ts\n\nconsider the index.ts:\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nfunction lookFilesInDirectory(path_directory) {\n fs.stat(path_directory, (err, stat) => {\n if (!err) {\n if (stat.isDirectory()) {\n console.log(path_directory)\n fs.readdirSync(path_directory).forEach(file => {\n console.log(`\\t${file}`);\n });\n console.log();\n }\n }\n });\n}\n\nlet path_view = './';\nlookFilesInDirectory(path_view);\nlookFilesInDirectory(path.join(__dirname, path_view));\n\nif you have in the readfile folder and run tsc src/index.ts && node src/index.js, the output will be:\n./\n filename.txt\n src\n\n/home/andrei/scripts/readfile/src/\n index.js\n index.ts\n\nthat is, it depends on where you run the node.\nthe __dirname is directory name of the current module.\n", "Just to clarify: if ever the TS 2307: Cannot find module import error appears: check the tsconfig.json file.\nIt must contain node_modules\n{\n.....\n \"include\": [\n \"src/**/*.ts\",\n \"src/**/*.tsx\",\n \"src/**/*.vue\",\n \"tests/**/*.ts\",\n \"tests/**/*.tsx\",\n \"node_modules\"\n ],\n.....\n}\n\n", "I encounter \"Cannot find module 'fs' or its corresponding type declarations\" when\nimport { readFileSync } from 'fs';\n\nHow I solve it\nA bit deviation from Jerome Villiseck's ans\nEdit tsconfig.app.json:\n...\n\"include\": [\n \"src/**/*.d.ts\",\n \"node_modules/@types/node/\"\n]\n...\n\n", "It is possible to write file in ts.\nBut something how its js.\nYou can install jquery to run javascript in angular.\nnpm i jquery\n\nImport in it in angular.json file and use this code\nvar fileWriter = new Writer();\nvar fileName = \"test_syskey/Test.doc\";\nfileWriter.removeFile(fileName, function(err,url) {\n if (err) {\n resp.error(\"Write failed\");\n } else {\n resp.success(url);\n }\n}); \n\n" ]
[ 86, 22, 14, 12, 0, 0, 0 ]
[]
[]
[ "node.js", "typescript" ]
stackoverflow_0033643107_node.js_typescript.txt
Q: Creating multiple resources in different regions of the same AWS account We have a service (using a lot of AWS components) which is hosted in us-west-1 AWS region. Now we have a requirement to host a database (mostly a ddb) in the eu-south-2 AWS region. Someone told me that it's not ideal to host infra in different regions in the same AWS account and recommends we create different AWS accounts and then host the database in the eu-south-2 region there and then make a cross region call from our service in us-west-1 to the database in the other account in the eu-south-2 region. The cross region call cannot be avoided since the database has to be in the us-west-1 region and the service also has to be in `us-west-1 I tried to find something online but wasn't able to find any suggestions on this, can anyone maybe help me in terms of why this might be a recommendation? or is it even a good recommendation? Should we just use the same AWS account? A: /* Creating multiple resources in different regions of the same AWS account */ var AWS = require('aws-sdk'); var ec2 = new AWS.EC2({region: 'us-east-1'}); var ec2 = new AWS.EC2({region: 'us-west-2'});
Creating multiple resources in different regions of the same AWS account
We have a service (using a lot of AWS components) which is hosted in us-west-1 AWS region. Now we have a requirement to host a database (mostly a ddb) in the eu-south-2 AWS region. Someone told me that it's not ideal to host infra in different regions in the same AWS account and recommends we create different AWS accounts and then host the database in the eu-south-2 region there and then make a cross region call from our service in us-west-1 to the database in the other account in the eu-south-2 region. The cross region call cannot be avoided since the database has to be in the us-west-1 region and the service also has to be in `us-west-1 I tried to find something online but wasn't able to find any suggestions on this, can anyone maybe help me in terms of why this might be a recommendation? or is it even a good recommendation? Should we just use the same AWS account?
[ "/* Creating multiple resources in different regions of the same AWS account */\nvar AWS = require('aws-sdk');\nvar ec2 = new AWS.EC2({region: 'us-east-1'});\nvar ec2 = new AWS.EC2({region: 'us-west-2'});\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_regions" ]
stackoverflow_0074678621_amazon_web_services_aws_regions.txt
Q: How to perform a mathematical operation on two instances of object in Django? I want to add two numbers from two different objects. Here is a simplified version. I have two integers and I multiply those to get multiplied . models.py: class ModelA(models.Model): number_a = models.IntegerField(default=1, null=True, blank=True) number_b = models.IntegerField(default=1, null=True, blank=True) def multiplied(self): return self.number_a * self.number_b views.py: @login_required def homeview(request): numbers = ModelA.objects.all() context = { 'numbers': numbers, } return TemplateResponse... What I'm trying to do is basically multiplied + multiplied in the template but I simply can't figure out how to do it since I first have to loop through the objects. So if I had 2 instances of ModelA and two 'multiplied' values of 100 I want to display 200 in the template. Is this possible? A: In your template, when you do a forloop over the numbers variable, you can directly access properties, functions and attributes. So to access the value you want I guess it would look something like this, simplified: {% for number in numbers %} {{ number.multiplied }} {% endfor %} Hope that makes sense? However, please take note that this is not the most efficient method. We can make Django ask the SQL server to do the heavy lifting on the calculation side of things, so if you want to be really clever and optimise your view, you can comment out your multiplied function and replace then, you still access it in the template the same way I described above, but we needs to change the code in your view slightly like so: numbers = ModelA.objects.aggregate(Sum('number_a', 'number_b')) As described loosely in haduki's answer. This offloads the calculation to the SQL server by crafting an SQL query which uses the SUM SQL database function, which for all intents and purposes is almost always going to be substantially faster that having a function on the object. A: You can try doing that with aggregate from django.db.models import Sum ModelA.objects.aggregate(Sum('multiplied')) If that does not suit you just use aggregate on each field and then add them together. A: The good practice is always to avoid logic on the template. It would be better to loop at the view and add calculated value to context: def homeview(request): queryset = ModelA.objects.all() multipliers_addition = 0 for obj in queryset: multipliers_addition += obj.multiplied() context = { 'addition': multipliers_addition, } return render(request, 'multiply.html', context)
How to perform a mathematical operation on two instances of object in Django?
I want to add two numbers from two different objects. Here is a simplified version. I have two integers and I multiply those to get multiplied . models.py: class ModelA(models.Model): number_a = models.IntegerField(default=1, null=True, blank=True) number_b = models.IntegerField(default=1, null=True, blank=True) def multiplied(self): return self.number_a * self.number_b views.py: @login_required def homeview(request): numbers = ModelA.objects.all() context = { 'numbers': numbers, } return TemplateResponse... What I'm trying to do is basically multiplied + multiplied in the template but I simply can't figure out how to do it since I first have to loop through the objects. So if I had 2 instances of ModelA and two 'multiplied' values of 100 I want to display 200 in the template. Is this possible?
[ "In your template, when you do a forloop over the numbers variable, you can directly access properties, functions and attributes.\nSo to access the value you want I guess it would look something like this, simplified:\n{% for number in numbers %}\n {{ number.multiplied }}\n{% endfor %}\n\nHope that makes sense?\nHowever, please take note that this is not the most efficient method.\nWe can make Django ask the SQL server to do the heavy lifting on the calculation side of things, so if you want to be really clever and optimise your view, you can comment out your multiplied function and replace then, you still access it in the template the same way I described above, but we needs to change the code in your view slightly like so:\nnumbers = ModelA.objects.aggregate(Sum('number_a', 'number_b'))\n\nAs described loosely in haduki's answer. This offloads the calculation to the SQL server by crafting an SQL query which uses the SUM SQL database function, which for all intents and purposes is almost always going to be substantially faster that having a function on the object.\n", "You can try doing that with aggregate\nfrom django.db.models import Sum\n\nModelA.objects.aggregate(Sum('multiplied'))\n\nIf that does not suit you just use aggregate on each field and then add them together.\n", "The good practice is always to avoid logic on the template. It would be better to loop at the view and add calculated value to context:\ndef homeview(request):\n queryset = ModelA.objects.all()\n multipliers_addition = 0\n for obj in queryset:\n multipliers_addition += obj.multiplied()\n\n context = {\n 'addition': multipliers_addition,\n }\n\n return render(request, 'multiply.html', context)\n\n" ]
[ 2, 1, 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0074678108_django_django_templates_python.txt
Q: "Help to fix 'blur rendering' in flutter web" My flutter web is blur at some resolution. Anyone know how to fix it? For more information, I'm running in debug mode, and when I zoom in or out the page the quality change, some zoom level blur, some not. enter image description here [√] Flutter (Channel stable, v1.7.8+hotfix.4, on Microsoft Windows [Version 10.0.17763.615], locale en-US) • Flutter version 1.7.8+hotfix.4 at D:\flutter • Framework revision 20e59316b8 (3 weeks ago), 2019-07-18 20:04:33 -0700 • Engine revision fee001c93f • Dart version 2.4.0 A: I encountered a similar issue when using html renderer for web builds. Flutter web should use CanvasKit by default that should prevent this issue. Otherwise you'd need to define --web-renderer canvaskit argument on build. A: try to add this line in a TextStyle property: TextStyle(fontFeatures: [FontFeature.proportionalFigures()])
"Help to fix 'blur rendering' in flutter web"
My flutter web is blur at some resolution. Anyone know how to fix it? For more information, I'm running in debug mode, and when I zoom in or out the page the quality change, some zoom level blur, some not. enter image description here [√] Flutter (Channel stable, v1.7.8+hotfix.4, on Microsoft Windows [Version 10.0.17763.615], locale en-US) • Flutter version 1.7.8+hotfix.4 at D:\flutter • Framework revision 20e59316b8 (3 weeks ago), 2019-07-18 20:04:33 -0700 • Engine revision fee001c93f • Dart version 2.4.0
[ "I encountered a similar issue when using html renderer for web builds. Flutter web should use CanvasKit by default that should prevent this issue. Otherwise you'd need to define --web-renderer canvaskit argument on build.\n", "try to add this line in a TextStyle property:\n TextStyle(fontFeatures: [FontFeature.proportionalFigures()]) \n\n" ]
[ 0, 0 ]
[]
[]
[ "flutter", "render", "rendering", "web" ]
stackoverflow_0057407347_flutter_render_rendering_web.txt
Q: Why is mongoDB a database server? I've recently begun learning mongoDB and came across the phrase "mongoDb is a database server." There was no explanation, and I'm a little confused because servers simply host resources and have an IP address assigned to them. Pretty sure that I am confused because I don't know enough of anything. But in summary can someone explain what is meant by "mongoDB is a database server". I would greatly appreciate it. I've been looking all morning and haven't found a "suitable" answer A: The term "server" is ambiguous. On one hand a "server" can be a (typically big) computer, which runs some software. Typical examples are database or web server. See Server computing On the other hand a "server" can be a software. Usually this software does not do anything, until a client software connects to it and ask for some activities. Typical example is a web-server and a browser as client. Server and client software can run on the same computer, this is no problem at all. See Client–server model For better distinction some people use "server" for computer hardware and "service" for the software item. But in general these term are not used consistently and mixed with each other.
Why is mongoDB a database server?
I've recently begun learning mongoDB and came across the phrase "mongoDb is a database server." There was no explanation, and I'm a little confused because servers simply host resources and have an IP address assigned to them. Pretty sure that I am confused because I don't know enough of anything. But in summary can someone explain what is meant by "mongoDB is a database server". I would greatly appreciate it. I've been looking all morning and haven't found a "suitable" answer
[ "The term \"server\" is ambiguous.\nOn one hand a \"server\" can be a (typically big) computer, which runs some software. Typical examples are database or web server. See Server computing\nOn the other hand a \"server\" can be a software. Usually this software does not do anything, until a client software connects to it and ask for some activities. Typical example is a web-server and a browser as client. Server and client software can run on the same computer, this is no problem at all. See Client–server model\nFor better distinction some people use \"server\" for computer hardware and \"service\" for the software item. But in general these term are not used consistently and mixed with each other.\n" ]
[ 0 ]
[]
[]
[ "database", "mongodb", "nosql", "paradigms", "server" ]
stackoverflow_0074678209_database_mongodb_nosql_paradigms_server.txt
Q: File is not showing when applying rasterio.open() Here is my code refPath = '/Users/admin/Downloads/Landsat8/' ext = '_NDWI.tif' for file in sorted(os.listdir(refPath)): if file.endswith(ext): print(file) ndwiopen = rs.open(file) ndwiread = ndwiopen.read(1) Here is the error 2014_NDWI.tif --------------------------------------------------------------------------- CPLE_OpenFailedError Traceback (most recent call last) File rasterio/_base.pyx:302, in rasterio._base.DatasetBase.__init__() File rasterio/_base.pyx:213, in rasterio._base.open_dataset() File rasterio/_err.pyx:217, in rasterio._err.exc_wrap_pointer() CPLE_OpenFailedError: 2014_NDWI.tif: No such file or directory During handling of the above exception, another exception occurred: RasterioIOError Traceback (most recent call last) Input In [104], in <cell line: 33>() 34 if file.endswith(ext): 35 print(file) ---> 36 ndwiopen = rs.open(file) 38 ndwiread = ndwiopen.read(1) 39 plt.figure(figsize = (20, 15)) File /Applications/anaconda3/lib/python3.9/site-packages/rasterio/env.py:442, in ensure_env_with_credentials.<locals>.wrapper(*args, **kwds) 439 session = DummySession() 441 with env_ctor(session=session): --> 442 return f(*args, **kwds) File /Applications/anaconda3/lib/python3.9/site-packages/rasterio/__init__.py:277, in open(fp, mode, driver, width, height, count, crs, transform, dtype, nodata, sharing, **kwargs) 274 path = _parse_path(raw_dataset_path) 276 if mode == "r": --> 277 dataset = DatasetReader(path, driver=driver, sharing=sharing, **kwargs) 278 elif mode == "r+": 279 dataset = get_writer_for_path(path, driver=driver)( 280 path, mode, driver=driver, sharing=sharing, **kwargs 281 ) File rasterio/_base.pyx:304, in rasterio._base.DatasetBase.__init__() RasterioIOError: 2014_NDWI.tif: No such file or directory As it is shown that the file is getting printed as an output but that can not be opened by the RasterIO (as rs). Can't understand what is missing in the script. A: Unsure if this is your exact problem, but I rammed my head against this same exact error for 5-10 hours before I realized that the '.tif' file I was trying to read had an extension in all caps, as in '.TIF'. This is apparently the default for the Landsat 8 image bands that I was working with. I was doing similar concatenation but my string would result in 'filename.tif' instead of the correct 'filename.TIF', so rasterio would be unable to read it. It was really frustrating, so I figured I would share how I was able to solve it since you have not yet received any replies, even though I cannot know if this was your issue. When I searched this error, this post is one of the first and most similar that would pop up but was unanswered, so I thought I would post in case any one with my issue might stumble across it as well (or, for myself when I inevitably forget in a few months how I had solved this).
File is not showing when applying rasterio.open()
Here is my code refPath = '/Users/admin/Downloads/Landsat8/' ext = '_NDWI.tif' for file in sorted(os.listdir(refPath)): if file.endswith(ext): print(file) ndwiopen = rs.open(file) ndwiread = ndwiopen.read(1) Here is the error 2014_NDWI.tif --------------------------------------------------------------------------- CPLE_OpenFailedError Traceback (most recent call last) File rasterio/_base.pyx:302, in rasterio._base.DatasetBase.__init__() File rasterio/_base.pyx:213, in rasterio._base.open_dataset() File rasterio/_err.pyx:217, in rasterio._err.exc_wrap_pointer() CPLE_OpenFailedError: 2014_NDWI.tif: No such file or directory During handling of the above exception, another exception occurred: RasterioIOError Traceback (most recent call last) Input In [104], in <cell line: 33>() 34 if file.endswith(ext): 35 print(file) ---> 36 ndwiopen = rs.open(file) 38 ndwiread = ndwiopen.read(1) 39 plt.figure(figsize = (20, 15)) File /Applications/anaconda3/lib/python3.9/site-packages/rasterio/env.py:442, in ensure_env_with_credentials.<locals>.wrapper(*args, **kwds) 439 session = DummySession() 441 with env_ctor(session=session): --> 442 return f(*args, **kwds) File /Applications/anaconda3/lib/python3.9/site-packages/rasterio/__init__.py:277, in open(fp, mode, driver, width, height, count, crs, transform, dtype, nodata, sharing, **kwargs) 274 path = _parse_path(raw_dataset_path) 276 if mode == "r": --> 277 dataset = DatasetReader(path, driver=driver, sharing=sharing, **kwargs) 278 elif mode == "r+": 279 dataset = get_writer_for_path(path, driver=driver)( 280 path, mode, driver=driver, sharing=sharing, **kwargs 281 ) File rasterio/_base.pyx:304, in rasterio._base.DatasetBase.__init__() RasterioIOError: 2014_NDWI.tif: No such file or directory As it is shown that the file is getting printed as an output but that can not be opened by the RasterIO (as rs). Can't understand what is missing in the script.
[ "Unsure if this is your exact problem, but I rammed my head against this same exact error for 5-10 hours before I realized that the '.tif' file I was trying to read had an extension in all caps, as in '.TIF'. This is apparently the default for the Landsat 8 image bands that I was working with.\nI was doing similar concatenation but my string would result in 'filename.tif' instead of the correct 'filename.TIF', so rasterio would be unable to read it. It was really frustrating, so I figured I would share how I was able to solve it since you have not yet received any replies, even though I cannot know if this was your issue. When I searched this error, this post is one of the first and most similar that would pop up but was unanswered, so I thought I would post in case any one with my issue might stumble across it as well (or, for myself when I inevitably forget in a few months how I had solved this).\n" ]
[ 0 ]
[]
[]
[ "image", "python", "rasterio" ]
stackoverflow_0073506395_image_python_rasterio.txt
Q: go-flags ignore unknown input How do I make flags ignore unknown input and store it for further processing? I've seen something about const IgnoreUnknown and I'm not sure how to use it because when I tried to put it as follows nothing changed: const ( IgnoreUnknown = true ) A: The documentation is very poor, so for future reference, it should be done as follows: parser := flags.NewParser(&opt, flags.IgnoreUnknown) args, _ := parser.Parse()
go-flags ignore unknown input
How do I make flags ignore unknown input and store it for further processing? I've seen something about const IgnoreUnknown and I'm not sure how to use it because when I tried to put it as follows nothing changed: const ( IgnoreUnknown = true )
[ "The documentation is very poor, so for future reference, it should be done as follows:\nparser := flags.NewParser(&opt, flags.IgnoreUnknown)\nargs, _ := parser.Parse()\n\n" ]
[ 1 ]
[]
[]
[ "flags", "go" ]
stackoverflow_0074678438_flags_go.txt
Q: Deleting a key in a dictionary submission How would I go about in deleting a specified key within a Dictionary based on the following condition?[enter image description here Deleting a key in a dictionary
Deleting a key in a dictionary submission
How would I go about in deleting a specified key within a Dictionary based on the following condition?[enter image description here Deleting a key in a dictionary
[]
[]
[ "thisdict = {\n \"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 1964\n}\ndel thisdict[\"model\"]\nprint(thisdict)\n\n" ]
[ -3 ]
[ "python" ]
stackoverflow_0074678640_python.txt
Q: FLL Python - running two commands at once I am helping coach First Lego League (FLL) and this year with the SPIKE robot they allow us to use Python to command the robot. We used to be able (using Scratch style coding) to have the robot do two things at once, like drive forward and raise attachement. But with Python everything is sequential. How could we have it do both of these at once, or send one function and not have it wait for a response before processing the next function? A: To run two processes at once in python, you can use the multiprocessing module to create separate processes for each command and run them simultaneously. import multiprocessing def run_command1(): # code for command1 def run_command2(): # code for command2 if __name__ == '__main__': p1 = multiprocessing.Process(target=run_command1) p2 = multiprocessing.Process(target=run_command2) p1.start() p2.start() This will create two separate processes for the run_command1() and run_command2() functions, and run them simultaneously. Consult the python documentation for more information on the multiprocessing module and managing processes in python.
FLL Python - running two commands at once
I am helping coach First Lego League (FLL) and this year with the SPIKE robot they allow us to use Python to command the robot. We used to be able (using Scratch style coding) to have the robot do two things at once, like drive forward and raise attachement. But with Python everything is sequential. How could we have it do both of these at once, or send one function and not have it wait for a response before processing the next function?
[ "To run two processes at once in python, you can use the multiprocessing module to create separate processes for each command and run them simultaneously.\nimport multiprocessing\n\ndef run_command1():\n # code for command1\n\ndef run_command2():\n # code for command2\n\nif __name__ == '__main__':\n p1 = multiprocessing.Process(target=run_command1)\n p2 = multiprocessing.Process(target=run_command2)\n\n p1.start()\n p2.start()\n\nThis will create two separate processes for the run_command1() and run_command2() functions, and run them simultaneously. Consult the python documentation for more information on the multiprocessing module and managing processes in python.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074678613_python.txt
Q: How to format the code on Git Push and Pull I am currently working on development projects with different languages (TS, TSX) with different developers. Moreover we use Prettier/ESLint, but it's a detail. And some developers are used to develop with 2 indentation, and the use of spaces. And some use 4 indentation, and prefer tabs. The problem is that when we get the code from github, the indentation may be that of another developer and therefore not the one that corresponds to us. When a developer retrieves this code indented to 2, is working with 4 indentation, the entire files are detected as being modified by git. Is it possible to perform at the time of a clone/pull/fetch, a formatting of the code to match our preferences? And at the time of the creation of a pull request/push/commit, to format the code so that it corresponds to that present on the repository? We have tried several things to solve this problem but without success: We tried using clean and smudge, but it never worked: Can git automatically switch between spaces and tabs? We tried github actions, the problem is that to find a specific modification, it is not practical at all. A: Pushing and fetching are not points at which code can be formatted, because Git simply pushes or fetches the data that's already there. Other than deltifying and compressing it, it really doesn't change the data sent in any way. However, the way most organizations do this is to set up a set of code standards and a lint tool to enforce them. For example, in Rust, you're likely going to use 4 spaces and rustfmt to format the code. Then, you set up your CI to run the linter or style checked and fail if it's not correct. Thus, code cannot be merged if it doesn't meet code style. While everyone is welcome to have their own preferences about how to format code, when you're working together on a project, it's completely normal and reasonable to require everyone to agree on a set of standards. Not everyone has to like it: the Go team explicitly agrees that the standard Go style is not anyone's favourite, but it's a fixed standard and everyone adheres to it. I myself have rigorously enforced code style changes which differed from my preferred style simply because it was more important that everyone use the same style. This becomes much easier if you have a tool to auto-format the code because then everyone just runs that tool and it can be automatically checked without needing to consider it at all in code review. It either passes CI or it doesn't. Note that you can provide pre-commit hooks if you want to, but you shouldn't require them, since it can be useful for users to create improperly formatted temporary commits in advanced workflows. Since the Git FAQ mentions that hooks on the developer machine are not an effective control, you need to set CI up anyway. A: You may find this article helpful; the author shows how to enforce code style using clang-format with a local pre-commit workflow (or hook), as well as PR actions. As a bare minimum, an .editorconfig file is a good idea, and as long as the team members are judicious about running a simple auto-format after making changes, the indention style and spaces can become a non-issue. For me, running the auto-format shortcut quickly became as habitual as CTRL+S.
How to format the code on Git Push and Pull
I am currently working on development projects with different languages (TS, TSX) with different developers. Moreover we use Prettier/ESLint, but it's a detail. And some developers are used to develop with 2 indentation, and the use of spaces. And some use 4 indentation, and prefer tabs. The problem is that when we get the code from github, the indentation may be that of another developer and therefore not the one that corresponds to us. When a developer retrieves this code indented to 2, is working with 4 indentation, the entire files are detected as being modified by git. Is it possible to perform at the time of a clone/pull/fetch, a formatting of the code to match our preferences? And at the time of the creation of a pull request/push/commit, to format the code so that it corresponds to that present on the repository? We have tried several things to solve this problem but without success: We tried using clean and smudge, but it never worked: Can git automatically switch between spaces and tabs? We tried github actions, the problem is that to find a specific modification, it is not practical at all.
[ "Pushing and fetching are not points at which code can be formatted, because Git simply pushes or fetches the data that's already there. Other than deltifying and compressing it, it really doesn't change the data sent in any way.\nHowever, the way most organizations do this is to set up a set of code standards and a lint tool to enforce them. For example, in Rust, you're likely going to use 4 spaces and rustfmt to format the code. Then, you set up your CI to run the linter or style checked and fail if it's not correct. Thus, code cannot be merged if it doesn't meet code style.\nWhile everyone is welcome to have their own preferences about how to format code, when you're working together on a project, it's completely normal and reasonable to require everyone to agree on a set of standards. Not everyone has to like it: the Go team explicitly agrees that the standard Go style is not anyone's favourite, but it's a fixed standard and everyone adheres to it. I myself have rigorously enforced code style changes which differed from my preferred style simply because it was more important that everyone use the same style.\nThis becomes much easier if you have a tool to auto-format the code because then everyone just runs that tool and it can be automatically checked without needing to consider it at all in code review. It either passes CI or it doesn't.\nNote that you can provide pre-commit hooks if you want to, but you shouldn't require them, since it can be useful for users to create improperly formatted temporary commits in advanced workflows. Since the Git FAQ mentions that hooks on the developer machine are not an effective control, you need to set CI up anyway.\n", "You may find this article helpful; the author shows how to enforce code style using clang-format with a local pre-commit workflow (or hook), as well as PR actions.\nAs a bare minimum, an .editorconfig file is a good idea, and as long as the team members are judicious about running a simple auto-format after making changes, the indention style and spaces can become a non-issue. For me, running the auto-format shortcut quickly became as habitual as CTRL+S.\n" ]
[ 1, 0 ]
[]
[]
[ "git", "indentation", "prettier", "tabs", "visual_studio_code" ]
stackoverflow_0071725790_git_indentation_prettier_tabs_visual_studio_code.txt
Q: MapView not loading when running on CI I have some XCUITests that need to tap annotations on a map, when I run the tests in my mac everything works fine, but when they run on CI the map doesn't load. https://i.stack.imgur.com/B6YEG.jpg A: Ensure your CI device/simulator is connected to the internet. Your map load in CI may be slower than on a real device, so you may need to increase wait times.
MapView not loading when running on CI
I have some XCUITests that need to tap annotations on a map, when I run the tests in my mac everything works fine, but when they run on CI the map doesn't load. https://i.stack.imgur.com/B6YEG.jpg
[ "Ensure your CI device/simulator is connected to the internet. Your map load in CI may be slower than on a real device, so you may need to increase wait times.\n" ]
[ 0 ]
[]
[]
[ "ios", "swift", "xcode", "xctest", "xcuitest" ]
stackoverflow_0074393921_ios_swift_xcode_xctest_xcuitest.txt
Q: Is there a standard to sign and verify node.js code? I have a certificate for code signing and I want to know if is there a standard way to sign and verify a nodejs/javascript code? Maybe using OpenSSL or other tools? Unlike binaries, the nodejs/javascript code has multiples files and that makes it more complex to use some utilities to sign software. A: If you upload JavaScript to a web server, you "sign" it by serving it with a TLS certificate. You can use Let's Encrypt to get one for free. If you're trying to, essentially credit yourself, adding a license alongside your JavaScript files is how you would "sign" it. Since JavaScript is not a binary format itself, there's no way to sign it with a Code Signing Certificate. However, Node.js is a signed binary that is used to execute your code. If you're trying to sign a binary compiled from JavaScript with a tool like pkg, use a Code Signing Certificate. A: Warning i don't think this has ever been done before or this is a standard way of doing this but i do have a plan/idea Steps 1 have a source map of all the files in project [with or without excluding stuff like node_modules and .env] 2 convert each file to a hash [which doesn't matter best to pick the one with the most text to hash possible] 3 add all the hash to a file like the source map but instead of the file path it would a bunch of hash [filename:hash; something like json] 4 then using your public key to encrypt that file and hash that file lets call it "CSIGN" Verification do the same steps again save it in the file "VSIGN" and then check if "VSIGN" and "CSIGN" are the Disclaimer this has a lot of issues like you might need to implement some solution for big files and then u will have to save everyone's public key somewhere and a lot more but if your ready and you do need help you could contact me, check my bio
Is there a standard to sign and verify node.js code?
I have a certificate for code signing and I want to know if is there a standard way to sign and verify a nodejs/javascript code? Maybe using OpenSSL or other tools? Unlike binaries, the nodejs/javascript code has multiples files and that makes it more complex to use some utilities to sign software.
[ "If you upload JavaScript to a web server, you \"sign\" it by serving it with a TLS certificate. You can use Let's Encrypt to get one for free.\nIf you're trying to, essentially credit yourself, adding a license alongside your JavaScript files is how you would \"sign\" it.\nSince JavaScript is not a binary format itself, there's no way to sign it with a Code Signing Certificate. However, Node.js is a signed binary that is used to execute your code.\nIf you're trying to sign a binary compiled from JavaScript with a tool like pkg, use a Code Signing Certificate.\n", "Warning\ni don't think this has ever been done before or this is a standard way of doing this but i do have a plan/idea\nSteps\n\n1 have a source map of all the files in project [with or without excluding stuff like node_modules and .env]\n\n2 convert each file to a hash [which doesn't matter best to pick the one with the most text to hash possible]\n\n3 add all the hash to a file like the source map but instead of the file path it would a bunch of hash [filename:hash; something like json]\n\n4 then using your public key to encrypt that file and hash that file lets call it \"CSIGN\"\n\n\nVerification\ndo the same steps again save it in the file \"VSIGN\" and then check if \"VSIGN\" and \"CSIGN\" are the\nDisclaimer\nthis has a lot of issues like you might need to implement some solution for big files and then u will have to save everyone's public key somewhere and a lot more\nbut if your ready and you do need help you could contact me, check my bio\n" ]
[ 1, 0 ]
[]
[]
[ "code_signing", "javascript", "node.js", "security" ]
stackoverflow_0065417787_code_signing_javascript_node.js_security.txt
Q: I am not able to show the search result in the frontend , though its working on the backend tested though postman I am able to use the search function through backend and its working in postman, also able to bring the search result on the frontend browser console. But i am not able to display the searched result in the page. Frontend code is attached below. searchHandler is bringing the searched result to console but i am not able to display that on page import React, { useEffect, useState } from "react"; import axios from "axios"; const UserList = () => { const [userData, setUserData] = useState(""); const fetchUserData = async () => { const resp = await axios.get("/getTodo"); console.log(resp); //if no user is there please dont set any value if (resp.data.users.length > 0) { setUserData(resp.data.users); } }; useEffect(() => { fetchUserData(); }, [userData]); ///edit const handleEdit = async (user) => { var edittodo = `${user.todo}`; var edittask = `${user.task}`; const userTodo = prompt("Enter your Name", edittodo); const userTask = prompt("Enter your Email", edittask); if (!userTodo || !userTask) { alert("please Enter Todo and Task Both"); } else { const resp = await axios.put(`/editTodo/${user._id}`, { todo: userTodo, task: userTask, }); console.log(resp); } }; //Delete const handleDelete = async (userId) => { const resp = await axios.delete(`/deleteTodo/${userId}`); console.log(resp); }; const searchHandle = async (event) => { let key = event.target.value; console.log(key) await axios .get(`http://localhost:5500/search/${key}`) .then((response) => { console.log(response.data); }) .catch((err) => { console.log(err); }); }; return ( <div> <form> <input type="text" className="search-box" placeholder="Search Todo" onChange={(searchHandle)} /> </form> <section className="text-gray-600 body-font"> <div className="container px-5 py-24 mx-auto"> <div className="flex flex-col text-center w-full mb-8"> <h1 className="sm:text-4xl text-3xl font-medium title-font mb-2 text-gray-900"> All Users </h1> </div> <div className="lg:w-2/3 w-full mx-auto overflow-auto"> <table className="table-auto w-full text-left whitespace-no-wrap"> <thead> <tr> <th className="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100 rounded-tl rounded-bl"> Todo </th> <th className="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100"> Task </th> <th className="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100"> Edit </th> <th className="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100"> Delete </th> </tr> </thead> <tbody> {userData && userData.map((user, index) => ( <tr key={index}> <td className="px-4 py-3">{user.todo}</td> <td className="px-4 py-3">{user.task}</td> <td className="px-4 py-3"> <button className="hover:text-green-500" onClick={() => handleEdit(user)} > Edit </button> </td> <td className="px-4 py-3 text-lg text-gray-900"> <button className="hover:text-red-500" onClick={() => handleDelete(user._id)} > Delete </button> </td> </tr> ))} </tbody> </table> </div> </div> </section> </div> ); }; export default UserList; A: Just set the data inside the then .get(`http://localhost:5500/search/${key}`) .then((response) => { setUserData(resp.data); }) A: Change to this const fetchUserData = async () => { const resp = await axios.get("/getTodo"); resp.then(data => setUserData(data.users)); }; useEffect(() => { fetchUserData(); }, []);
I am not able to show the search result in the frontend , though its working on the backend tested though postman
I am able to use the search function through backend and its working in postman, also able to bring the search result on the frontend browser console. But i am not able to display the searched result in the page. Frontend code is attached below. searchHandler is bringing the searched result to console but i am not able to display that on page import React, { useEffect, useState } from "react"; import axios from "axios"; const UserList = () => { const [userData, setUserData] = useState(""); const fetchUserData = async () => { const resp = await axios.get("/getTodo"); console.log(resp); //if no user is there please dont set any value if (resp.data.users.length > 0) { setUserData(resp.data.users); } }; useEffect(() => { fetchUserData(); }, [userData]); ///edit const handleEdit = async (user) => { var edittodo = `${user.todo}`; var edittask = `${user.task}`; const userTodo = prompt("Enter your Name", edittodo); const userTask = prompt("Enter your Email", edittask); if (!userTodo || !userTask) { alert("please Enter Todo and Task Both"); } else { const resp = await axios.put(`/editTodo/${user._id}`, { todo: userTodo, task: userTask, }); console.log(resp); } }; //Delete const handleDelete = async (userId) => { const resp = await axios.delete(`/deleteTodo/${userId}`); console.log(resp); }; const searchHandle = async (event) => { let key = event.target.value; console.log(key) await axios .get(`http://localhost:5500/search/${key}`) .then((response) => { console.log(response.data); }) .catch((err) => { console.log(err); }); }; return ( <div> <form> <input type="text" className="search-box" placeholder="Search Todo" onChange={(searchHandle)} /> </form> <section className="text-gray-600 body-font"> <div className="container px-5 py-24 mx-auto"> <div className="flex flex-col text-center w-full mb-8"> <h1 className="sm:text-4xl text-3xl font-medium title-font mb-2 text-gray-900"> All Users </h1> </div> <div className="lg:w-2/3 w-full mx-auto overflow-auto"> <table className="table-auto w-full text-left whitespace-no-wrap"> <thead> <tr> <th className="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100 rounded-tl rounded-bl"> Todo </th> <th className="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100"> Task </th> <th className="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100"> Edit </th> <th className="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100"> Delete </th> </tr> </thead> <tbody> {userData && userData.map((user, index) => ( <tr key={index}> <td className="px-4 py-3">{user.todo}</td> <td className="px-4 py-3">{user.task}</td> <td className="px-4 py-3"> <button className="hover:text-green-500" onClick={() => handleEdit(user)} > Edit </button> </td> <td className="px-4 py-3 text-lg text-gray-900"> <button className="hover:text-red-500" onClick={() => handleDelete(user._id)} > Delete </button> </td> </tr> ))} </tbody> </table> </div> </div> </section> </div> ); }; export default UserList;
[ "Just set the data inside the then\n.get(`http://localhost:5500/search/${key}`)\n .then((response) => {\n setUserData(resp.data);\n \n \n })\n\n", "Change to this\nconst fetchUserData = async () => {\n const resp = await axios.get(\"/getTodo\");\n resp.then(data => setUserData(data.users));\n };\n\n useEffect(() => {\n fetchUserData();\n }, []);\n\n" ]
[ 0, 0 ]
[]
[]
[ "javascript", "node.js", "reactjs" ]
stackoverflow_0074678588_javascript_node.js_reactjs.txt
Q: when I go to scrapy to convert my web scraping data to csv! No matter how many rows I have. In just one row, the data of all rows is being inserted import scrapy from ..items import AmazondawinItem class AmazonspiderSpider(scrapy.Spider): name = 'amazon' pagenumber = 3 allowed_domains = ['amazon.com'] start_urls = [ 'https://www.amazon.com/s?k=laptop&i=computers&crid=27GFGJVF4KNRP&sprefix=%2Ccomputers%2C725&ref=nb_sb_ss_recent_1_0_recent' ] def parse(self, response): items = AmazondawinItem() name = response.css('.a-size-medium::text').extract() try: old_price = response.css('.a-spacing-top-micro .a-text-price span::text').extract() except: old_price = None price = response.css('.a-spacing-top-micro .a-price-whole::text').extract() try: review = response.css('.s-link-style .s-underline-text::text').extract() except: review = None imagelink = response.css('.s-image::attr(src)').extract() items['name'] = name items['old_price'] = old_price items['price'] = price items['review'] = review items['imagelink'] = imagelink # description = # ram = # brand = # cpu_model = yield items Here when I go to scrapy to convert my web scraping data to csv file or any file! No matter how many rows I have. In just one row, the data of all rows is being inserted. or import. Suppose, I have 200 rows in 1 column. But I am getting 200 rows of data in one row. A: It's because you're yielding all the items instead of yielding each item separately. A not so nice solution: import scrapy # from ..items import AmazondawinItem class AmazonspiderSpider(scrapy.Spider): name = 'amazon' pagenumber = 3 allowed_domains = ['amazon.com'] start_urls = [ 'https://www.amazon.com/s?k=laptop&i=computers&crid=27GFGJVF4KNRP&sprefix=%2Ccomputers%2C725&ref=nb_sb_ss_recent_1_0_recent' ] def parse(self, response): # items = AmazondawinItem() name = response.css('.a-size-medium::text').extract() try: old_price = response.css('.a-spacing-top-micro .a-text-price span::text').extract() except: old_price = None price = response.css('.a-spacing-top-micro .a-price-whole::text').extract() try: review = response.css('.s-link-style .s-underline-text::text').extract() except: review = None imagelink = response.css('.s-image::attr(src)').extract() # items = dict() # items['name'] = name # items['old_price'] = old_price # items['price'] = price # items['review'] = review # items['imagelink'] = imagelink items = dict() for (items['name'], items['old_price'], items['price'], items['review'], items['imagelink']) in zip(name, old_price, price, review, imagelink): yield items # description = # ram = # brand = # cpu_model = # yield items A better solution: Remove the try except, get() function will return none if no value was found. It's better not to use it in spiders anyway. Get the items one by one. Just replace the dict part with your item, just make sure it's inside the loop. import scrapy # from ..items import AmazondawinItem class AmazonspiderSpider(scrapy.Spider): name = 'amazon' pagenumber = 3 allowed_domains = ['amazon.com'] start_urls = [ 'https://www.amazon.com/s?k=laptop&i=computers&crid=27GFGJVF4KNRP&sprefix=%2Ccomputers%2C725&ref=nb_sb_ss_recent_1_0_recent' ] def parse(self, response): for row in response.css('div.s-result-list div.s-result-item.s-asin'): # items = AmazondawinItem() items = dict() items['name'] = row.css('.a-size-medium::text').get() items['old_price'] = row.css('.a-spacing-top-micro .a-text-price span::text').get() items['price'] = response.css('.a-spacing-top-micro .a-price-whole::text').get() items['review'] = row.css('.s-link-style .s-underline-text::text').get() items['imagelink'] = row.css('.s-image::attr(src)').get() yield items # description = # ram = # brand = # cpu_model = # yield items
when I go to scrapy to convert my web scraping data to csv! No matter how many rows I have. In just one row, the data of all rows is being inserted
import scrapy from ..items import AmazondawinItem class AmazonspiderSpider(scrapy.Spider): name = 'amazon' pagenumber = 3 allowed_domains = ['amazon.com'] start_urls = [ 'https://www.amazon.com/s?k=laptop&i=computers&crid=27GFGJVF4KNRP&sprefix=%2Ccomputers%2C725&ref=nb_sb_ss_recent_1_0_recent' ] def parse(self, response): items = AmazondawinItem() name = response.css('.a-size-medium::text').extract() try: old_price = response.css('.a-spacing-top-micro .a-text-price span::text').extract() except: old_price = None price = response.css('.a-spacing-top-micro .a-price-whole::text').extract() try: review = response.css('.s-link-style .s-underline-text::text').extract() except: review = None imagelink = response.css('.s-image::attr(src)').extract() items['name'] = name items['old_price'] = old_price items['price'] = price items['review'] = review items['imagelink'] = imagelink # description = # ram = # brand = # cpu_model = yield items Here when I go to scrapy to convert my web scraping data to csv file or any file! No matter how many rows I have. In just one row, the data of all rows is being inserted. or import. Suppose, I have 200 rows in 1 column. But I am getting 200 rows of data in one row.
[ "It's because you're yielding all the items instead of yielding each item separately.\nA not so nice solution:\nimport scrapy\n# from ..items import AmazondawinItem\n\n\nclass AmazonspiderSpider(scrapy.Spider):\n name = 'amazon'\n pagenumber = 3\n allowed_domains = ['amazon.com']\n start_urls = [\n 'https://www.amazon.com/s?k=laptop&i=computers&crid=27GFGJVF4KNRP&sprefix=%2Ccomputers%2C725&ref=nb_sb_ss_recent_1_0_recent'\n ]\n\n def parse(self, response):\n # items = AmazondawinItem()\n\n name = response.css('.a-size-medium::text').extract()\n try:\n old_price = response.css('.a-spacing-top-micro .a-text-price span::text').extract()\n except:\n old_price = None\n price = response.css('.a-spacing-top-micro .a-price-whole::text').extract()\n try:\n review = response.css('.s-link-style .s-underline-text::text').extract()\n except:\n review = None\n\n imagelink = response.css('.s-image::attr(src)').extract()\n # items = dict()\n # items['name'] = name\n # items['old_price'] = old_price\n # items['price'] = price\n # items['review'] = review\n # items['imagelink'] = imagelink\n\n items = dict()\n for (items['name'], items['old_price'], items['price'], items['review'], items['imagelink']) in zip(name, old_price, price, review, imagelink):\n yield items\n # description =\n # ram =\n # brand =\n # cpu_model =\n # yield items\n\nA better solution:\n\nRemove the try except, get() function will return none if no value was found. It's better not to use it in spiders anyway.\nGet the items one by one.\nJust replace the dict part with your item, just make sure it's inside the loop.\n\nimport scrapy\n# from ..items import AmazondawinItem\n\n\nclass AmazonspiderSpider(scrapy.Spider):\n name = 'amazon'\n pagenumber = 3\n allowed_domains = ['amazon.com']\n start_urls = [\n 'https://www.amazon.com/s?k=laptop&i=computers&crid=27GFGJVF4KNRP&sprefix=%2Ccomputers%2C725&ref=nb_sb_ss_recent_1_0_recent'\n ]\n\n def parse(self, response):\n for row in response.css('div.s-result-list div.s-result-item.s-asin'):\n # items = AmazondawinItem()\n items = dict()\n items['name'] = row.css('.a-size-medium::text').get()\n items['old_price'] = row.css('.a-spacing-top-micro .a-text-price span::text').get()\n items['price'] = response.css('.a-spacing-top-micro .a-price-whole::text').get()\n items['review'] = row.css('.s-link-style .s-underline-text::text').get()\n items['imagelink'] = row.css('.s-image::attr(src)').get()\n yield items\n # description =\n # ram =\n # brand =\n # cpu_model =\n # yield items\n\n" ]
[ 0 ]
[]
[]
[ "python", "scrapy", "web_crawler", "web_scraping" ]
stackoverflow_0074671535_python_scrapy_web_crawler_web_scraping.txt
Q: Java ASM visitMethod access 4161 meaning I have the following inheritance structure: SomeModel implements Entity, and SomeModelQueryRepo has 2 methods that return SomeModel: get given an Id, and get returning all SomeModels in the repo. For some reason, visitMethod detects another secret method: get which returns a base Entity. However, that is not explicitly declared. The access code is a bit unusual, with a value of 4161. I tried looking at the opcodes, but I can't determine which combination leads to that value. What does 4161 mean? A: These are the Method access and property flags. 4161 (which is 0x1041) corresponds to this combination of flags: 0x0001 ACC_PUBLIC 0x0040 ACC_BRIDGE 0x1000 ACC_SYNTHETIC The meaning of these flags is The ACC_BRIDGE flag is used to indicate a bridge method generated by a compiler for the Java programming language The ACC_SYNTHETIC flag indicates that this method was generated by a compiler and does not appear in source code, unless it is one of the methods named in §4.7.8. This combination is used by the Java Compiler if it needs to create "bridge methods": methods that are needed because of generics spezialisation / generics type erasure. In your case you probably have: public interface Entity<E> {} public class SomeModel implements Entity<Long> {} public interface QueryRepository<Id, E extends<Entity<Id>> { E get(Id id); } public class SomeModelQueryRepo implements QueryRepository<Long, SomeModel> { @Override public SomeModel get(Long id) { return null; } } For the class SomeModelQueryRepo to implement QueryRepository it must contain a method Entity get(Object id) because that is what the QueryRepository contains as method after type erasure. The compiler therefore creates this synthetic bridge method: public Entity<Object> get(Object id) { return get((Long) id); }
Java ASM visitMethod access 4161 meaning
I have the following inheritance structure: SomeModel implements Entity, and SomeModelQueryRepo has 2 methods that return SomeModel: get given an Id, and get returning all SomeModels in the repo. For some reason, visitMethod detects another secret method: get which returns a base Entity. However, that is not explicitly declared. The access code is a bit unusual, with a value of 4161. I tried looking at the opcodes, but I can't determine which combination leads to that value. What does 4161 mean?
[ "These are the Method access and property flags.\n4161 (which is 0x1041) corresponds to this combination of flags:\n0x0001 ACC_PUBLIC\n0x0040 ACC_BRIDGE\n0x1000 ACC_SYNTHETIC\n\nThe meaning of these flags is\n\n\nThe ACC_BRIDGE flag is used to indicate a bridge method generated by a compiler for the Java programming language\nThe ACC_SYNTHETIC flag indicates that this method was generated by a compiler and does not appear in source code, unless it is one of the methods named in §4.7.8.\n\n\nThis combination is used by the Java Compiler if it needs to create \"bridge methods\": methods that are needed because of generics spezialisation / generics type erasure.\nIn your case you probably have:\npublic interface Entity<E> {}\n\npublic class SomeModel implements Entity<Long> {}\n\npublic interface QueryRepository<Id, E extends<Entity<Id>> {\n E get(Id id);\n}\n\npublic class SomeModelQueryRepo implements QueryRepository<Long, SomeModel> {\n @Override\n public SomeModel get(Long id) {\n return null;\n }\n}\n\nFor the class SomeModelQueryRepo to implement QueryRepository it must contain a method Entity get(Object id) because that is what the QueryRepository contains as method after type erasure.\nThe compiler therefore creates this synthetic bridge method:\n public Entity<Object> get(Object id) {\n return get((Long) id);\n }\n\n" ]
[ 1 ]
[]
[]
[ "jar", "java", "java_bytecode_asm" ]
stackoverflow_0074678377_jar_java_java_bytecode_asm.txt
Q: Power BI calculate DAX measure cumulatively I can't configure how to calculate DAX measure cumulatively. The DAX measure by it self looks like this: UpdateTicket_ = CALCULATE(Logging[LogDistcount_], Logging[Step] = 7) # DAX measure to filter distinct ID by some condition. LogDistcount_ = DISTINCTCOUNT(Logging[TicketId]) # DAX measure to calculate distinct ID presented in the featured dataset. The ploblem is that formula construction to calculate cumulatively doesn't allow to sum DAX measure. I mean this: =CALCULATE(SUM(UpdateTicket_)... The formula doesn't give an option to select UpdateTicket_ to make a SUM of it. This measure doesn't appear in the selection list of the SUM formula at all. Currently output of the UpdateTicket_ measure looks like this: StartTime_DateOnly UpdateTicket_ 08.11.2022 950 09.11.2022 1056 10.11.2022 1056 11.11.2022 1056 12.11.2022 1056 13.11.2022 1056 What I am looking for: StartTime_DateOnly UpdateTicket_ UpdateTicket_Cumulatively 08.11.2022 950 950 09.11.2022 1056 2006 10.11.2022 1056 3062 11.11.2022 1056 4118 12.11.2022 1056 5174 13.11.2022 1056 6230 A: I hope you can accept the following solution: Let Power BI create the measure for you by going to Quick measure - Running total You'll get the following expression: UpdateTicket_Cumulatively = CALCULATE( SUM('Table'[UpdateTicket_]), FILTER( ALLSELECTED('Table'[StartTime_DateOnly]), ISONORAFTER('Table'[StartTime_DateOnly], MAX('Table'[StartTime_DateOnly]), DESC) ) and a table like this: Note that this works with both measures and columns.
Power BI calculate DAX measure cumulatively
I can't configure how to calculate DAX measure cumulatively. The DAX measure by it self looks like this: UpdateTicket_ = CALCULATE(Logging[LogDistcount_], Logging[Step] = 7) # DAX measure to filter distinct ID by some condition. LogDistcount_ = DISTINCTCOUNT(Logging[TicketId]) # DAX measure to calculate distinct ID presented in the featured dataset. The ploblem is that formula construction to calculate cumulatively doesn't allow to sum DAX measure. I mean this: =CALCULATE(SUM(UpdateTicket_)... The formula doesn't give an option to select UpdateTicket_ to make a SUM of it. This measure doesn't appear in the selection list of the SUM formula at all. Currently output of the UpdateTicket_ measure looks like this: StartTime_DateOnly UpdateTicket_ 08.11.2022 950 09.11.2022 1056 10.11.2022 1056 11.11.2022 1056 12.11.2022 1056 13.11.2022 1056 What I am looking for: StartTime_DateOnly UpdateTicket_ UpdateTicket_Cumulatively 08.11.2022 950 950 09.11.2022 1056 2006 10.11.2022 1056 3062 11.11.2022 1056 4118 12.11.2022 1056 5174 13.11.2022 1056 6230
[ "I hope you can accept the following solution:\nLet Power BI create the measure for you by going to Quick measure - Running total\n\nYou'll get the following expression:\nUpdateTicket_Cumulatively = \nCALCULATE(\n SUM('Table'[UpdateTicket_]),\n FILTER(\n ALLSELECTED('Table'[StartTime_DateOnly]),\n ISONORAFTER('Table'[StartTime_DateOnly], MAX('Table'[StartTime_DateOnly]), DESC)\n )\n\nand a table like this:\n\nNote that this works with both measures and columns.\n" ]
[ 0 ]
[]
[]
[ "dax", "powerbi", "powerbi_desktop", "powerquery" ]
stackoverflow_0074678307_dax_powerbi_powerbi_desktop_powerquery.txt
Q: How to filter Hive data in flutter by data values? In Flutter, I using ValueListenableBuilder widget to get list of hive data, and I'm trying to filter my data by data values. Example:- Key: 1 name(value) : mydata1 des(value) : mydescription1 value(value) : 1 here in this example I want to filter data by data value called value(value) by help of dropdown, like: if (value.compareTo(1) == 1){ print('All First Value Data Showing Result'); } Something like that: Expanded( child: ValueListenableBuilder( valueListenable: msgbox.listenable(), builder: (context, box, _) { Map<dynamic, dynamic> raw = box.toMap(); List list = raw.values.toList(); return ListView.builder( itemCount: list.length, itemBuilder: (context, index){ MsgModel msges = list[index]; return GestureDetector( onDoubleTap: () {}, child: Padding( padding: EdgeInsets.only(left: 8, right: 8), child: Column( children: [ ... ValueListenableBuilder mycode Image A: You can simply filter the list using the where() function. Example: list.where((item) => item.value == 1) .forEach((item) => print('All First Value Data Showing Result')); This will filter the list and retain objects only where the value is equal to 1. Or for other people that are using Box to retrieve your values you can do like this example: Box<Item> itemBox = Hive.box<Item>("Item"); itemBox.values.where((item) => item.value == 1) .forEach((item) => print('All First Value Data Showing Result')); Hope this is what you were searching for. A: this is simple code . var filteredUsers = monstersBox.values .where((Monster) => Monster.name == "Vampire") .toList(); print(filteredUsers.length); and this is my class : @HiveType(typeId: 0) class Monster { @HiveField(0) String? name; @HiveField(1) int? level; Monster(this.name, this.level); } A: To Edit Your Model Object ,you will need hive model key soon and later. For that I have some kind of filtering keys specific and use those to read data. Do not use index from box.values because it can misleading issue when you delete or update some data on a model like box.putAt(index,updatedModel) or box.deleteAt(index,toBeDeletedModel) when multi selecting models. dbBox = Box<YourModel>(); final filterdList = dbBox.values.where((element) => element.isFavourite!); final filteredKeys = filterdList.map((element) { return dbBox.keyAt(dbBox.values.toList().indexOf(element)); }).toList(); List<Widget> myLists = filteredKeys.map((key) { final currentModel = dbBox.get(key); return YourModelCardWidget(modelKey : key , model : currentModel); }).toList(); // then, you can use that key below .. // dbBox.put(key, updatedModel) ( Update ) // dbBox.delete(key, currentModel) ( Delete )
How to filter Hive data in flutter by data values?
In Flutter, I using ValueListenableBuilder widget to get list of hive data, and I'm trying to filter my data by data values. Example:- Key: 1 name(value) : mydata1 des(value) : mydescription1 value(value) : 1 here in this example I want to filter data by data value called value(value) by help of dropdown, like: if (value.compareTo(1) == 1){ print('All First Value Data Showing Result'); } Something like that: Expanded( child: ValueListenableBuilder( valueListenable: msgbox.listenable(), builder: (context, box, _) { Map<dynamic, dynamic> raw = box.toMap(); List list = raw.values.toList(); return ListView.builder( itemCount: list.length, itemBuilder: (context, index){ MsgModel msges = list[index]; return GestureDetector( onDoubleTap: () {}, child: Padding( padding: EdgeInsets.only(left: 8, right: 8), child: Column( children: [ ... ValueListenableBuilder mycode Image
[ "You can simply filter the list using the where() function.\nExample:\nlist.where((item) => item.value == 1)\n .forEach((item) => print('All First Value Data Showing Result'));\n\nThis will filter the list and retain objects only where the value is equal to 1.\nOr for other people that are using Box to retrieve your values you can do like this example:\nBox<Item> itemBox = Hive.box<Item>(\"Item\");\nitemBox.values.where((item) => item.value == 1)\n .forEach((item) => print('All First Value Data Showing Result'));\n\nHope this is what you were searching for.\n", "this is simple code .\n var filteredUsers = monstersBox.values\n .where((Monster) => Monster.name == \"Vampire\")\n .toList();\n print(filteredUsers.length);\n\nand this is my class :\n@HiveType(typeId: 0)\nclass Monster {\n @HiveField(0)\n String? name;\n @HiveField(1)\n int? level;\n Monster(this.name, this.level);\n}\n\n", "To Edit Your Model Object ,you will need hive model key soon and later.\nFor that I have some kind of filtering keys specific and use those to read data. Do not use index from box.values because it can misleading issue when you delete or update some data on a model like box.putAt(index,updatedModel) or box.deleteAt(index,toBeDeletedModel) when multi selecting models.\ndbBox = Box<YourModel>();\nfinal filterdList =\n dbBox.values.where((element) => element.isFavourite!);\n\nfinal filteredKeys = filterdList.map((element) {\n return dbBox.keyAt(dbBox.values.toList().indexOf(element));\n }).toList();\nList<Widget> myLists = filteredKeys.map((key) { \n final currentModel = dbBox.get(key);\n return YourModelCardWidget(modelKey : key , model : currentModel);\n }).toList();\n // then, you can use that key below ..\n // dbBox.put(key, updatedModel) ( Update ) \n // dbBox.delete(key, currentModel) ( Delete )\n \n\n" ]
[ 12, 5, 0 ]
[]
[]
[ "dart", "flutter", "flutter_hive" ]
stackoverflow_0064272936_dart_flutter_flutter_hive.txt
Q: How to correctly upload image to an item in LazyList in Jetpack Compose? I would like to let user add image to each item (Card) in LazyColumn. But it seems that images are getting deleted on recomposition. How can I fix that? @Composable fun PhotoUpload( ) { val imageUri = remember { mutableStateOf<Uri?>(null) } val context = LocalContext.current val bitmap = remember { mutableStateOf<Bitmap?>(null) } val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.GetContent() ) { uri: Uri? -> imageUri.value = uri } imageUri.value?.let { LaunchedEffect(Unit) { if (Build.VERSION.SDK_INT < 28) { bitmap.value = MediaStore.Images .Media.getBitmap(context.contentResolver, it) } else { val source = ImageDecoder .createSource(context.contentResolver, it) bitmap.value = ImageDecoder.decodeBitmap(source) } } } bitmap.value?.let { btm -> Image( bitmap = btm.asImageBitmap(), contentDescription = null, modifier = Modifier.size(400.dp) ) } Button(onClick = { launcher.launch("image/*") }) { Icon(Icons.Filled.PhotoAlbum, "") } } Images get deleted (they're not coming back, it's a loop gif) PS: For LazyColumn I do use keys. And I also tried using AsyncImage from Coil, but it had the same issue A: You can store Uris or Uris as String inside a data class such as @Immutable data class MyModel( val title: String, val description: String, val uri: Uri? = null ) And create a ViewModel with items and a function to update Uri when it's set class MyViewModel : ViewModel() { val items = mutableStateListOf<MyModel>() .apply { repeat(15) { add(MyModel(title = "Title$it", description = "Description$it")) } } fun update(index: Int, uri: Uri) { val item = items[index].copy(uri = uri) items[index] = item } } And getting Uri via clicking a Button @Composable fun PhotoUpload( onError: (() -> Unit)? = null, onImageSelected: (Uri) -> Unit ) { val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.GetContent() ) { uri: Uri? -> if (uri == null) { onError?.invoke() } else { onImageSelected(uri) } } Button(onClick = { launcher.launch("image/*") }) { Icon(Icons.Filled.PhotoAlbum, "") } } Row that returns Uri via callback when it's set @Composable private fun MyRow( title: String, description: String, uri: Uri?, onImageSelected: (Uri) -> Unit ) { Column( modifier = Modifier .shadow(ambientColor = Color.LightGray, elevation = 4.dp) .fillMaxWidth() .background(Color.White, RoundedCornerShape(8.dp)) .padding(8.dp) ) { Text(title) Text(description) uri?.let { imageUri -> AsyncImage( modifier = Modifier .fillMaxWidth() .aspectRatio(4 / 3f), model = imageUri, contentDescription = null ) } PhotoUpload(onImageSelected = onImageSelected) } } Usage @Composable private fun ImageUploadSample(viewModel: MyViewModel) { LazyColumn { itemsIndexed( key = { _, item -> item.hashCode() }, items = viewModel.items ) { index, myModel -> MyRow( title = myModel.title, description = myModel.description, uri = myModel.uri, onImageSelected = { uri -> viewModel.update(index, uri) } ) } } } Result
How to correctly upload image to an item in LazyList in Jetpack Compose?
I would like to let user add image to each item (Card) in LazyColumn. But it seems that images are getting deleted on recomposition. How can I fix that? @Composable fun PhotoUpload( ) { val imageUri = remember { mutableStateOf<Uri?>(null) } val context = LocalContext.current val bitmap = remember { mutableStateOf<Bitmap?>(null) } val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.GetContent() ) { uri: Uri? -> imageUri.value = uri } imageUri.value?.let { LaunchedEffect(Unit) { if (Build.VERSION.SDK_INT < 28) { bitmap.value = MediaStore.Images .Media.getBitmap(context.contentResolver, it) } else { val source = ImageDecoder .createSource(context.contentResolver, it) bitmap.value = ImageDecoder.decodeBitmap(source) } } } bitmap.value?.let { btm -> Image( bitmap = btm.asImageBitmap(), contentDescription = null, modifier = Modifier.size(400.dp) ) } Button(onClick = { launcher.launch("image/*") }) { Icon(Icons.Filled.PhotoAlbum, "") } } Images get deleted (they're not coming back, it's a loop gif) PS: For LazyColumn I do use keys. And I also tried using AsyncImage from Coil, but it had the same issue
[ "You can store Uris or Uris as String inside a data class such as\n@Immutable\ndata class MyModel(\n val title: String,\n val description: String,\n val uri: Uri? = null\n)\n\nAnd create a ViewModel with items and a function to update Uri when it's set\nclass MyViewModel : ViewModel() {\n val items = mutableStateListOf<MyModel>()\n .apply {\n repeat(15) {\n add(MyModel(title = \"Title$it\", description = \"Description$it\"))\n }\n }\n\n fun update(index: Int, uri: Uri) {\n val item = items[index].copy(uri = uri)\n items[index] = item\n }\n}\n\nAnd getting Uri via clicking a Button\n@Composable\nfun PhotoUpload(\n onError: (() -> Unit)? = null,\n onImageSelected: (Uri) -> Unit\n) {\n\n val launcher = rememberLauncherForActivityResult(\n contract = ActivityResultContracts.GetContent()\n ) { uri: Uri? ->\n if (uri == null) {\n onError?.invoke()\n } else {\n onImageSelected(uri)\n }\n\n }\n\n Button(onClick = {\n launcher.launch(\"image/*\")\n }) {\n Icon(Icons.Filled.PhotoAlbum, \"\")\n }\n}\n\nRow that returns Uri via callback when it's set\n@Composable\nprivate fun MyRow(\n title: String,\n description: String,\n uri: Uri?,\n onImageSelected: (Uri) -> Unit\n) {\n Column(\n modifier = Modifier\n .shadow(ambientColor = Color.LightGray, elevation = 4.dp)\n .fillMaxWidth()\n .background(Color.White, RoundedCornerShape(8.dp))\n .padding(8.dp)\n ) {\n Text(title)\n Text(description)\n uri?.let { imageUri ->\n AsyncImage(\n modifier = Modifier\n .fillMaxWidth()\n .aspectRatio(4 / 3f),\n model = imageUri, contentDescription = null\n )\n }\n PhotoUpload(onImageSelected = onImageSelected)\n }\n}\n\nUsage\n@Composable\nprivate fun ImageUploadSample(viewModel: MyViewModel) {\n LazyColumn {\n\n itemsIndexed(\n key = { _, item ->\n item.hashCode()\n },\n items = viewModel.items\n ) { index, myModel ->\n MyRow(\n title = myModel.title,\n description = myModel.description,\n uri = myModel.uri,\n onImageSelected = { uri ->\n viewModel.update(index, uri)\n }\n )\n }\n }\n}\n\nResult\n\n" ]
[ 0 ]
[]
[]
[ "android", "android_jetpack_compose", "kotlin", "lazycolumn" ]
stackoverflow_0074678368_android_android_jetpack_compose_kotlin_lazycolumn.txt
Q: Using charAt to enumerate letters one by one in a loop, without getting stuck in a loop, in JavaScript This is my first post on here, hopefully I'm doing this right. So my friend is trying to get this green raining Matrix code to rain a sentence instead of random letters. html { background: black; height: 100%; overflow: hidden; } body { margin: 0; padding: 0; height: 100%; } const canvas = document.getElementById('Matrix'); const context = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; const alphabet = "Where they at though?" const fontSize = 16; const columns = canvas.width/fontSize; const rainDrops = []; for( let x = 0; x < columns; x++ ) { rainDrops[x] = 1; } const draw = () => { context.fillStyle = 'rgba(0, 0, 0, 0.05)'; context.fillRect(0, 0, canvas.width, canvas.height); context.fillStyle = '#0F0'; context.font = fontSize + 'px monospace'; for(let i = 0; i < rainDrops.length; i++) { const text = alphabet.charAt(Math.floor(Math.random() * alphabet.length)); context.fillText(text, i*fontSize, rainDrops[i]*fontSize); if(rainDrops[i]*fontSize > canvas.height && Math.random() > 0.975){ rainDrops[i] = 0; } rainDrops[i]++; } }; setInterval(draw, 30); If you want to see it in action, here it is on CodePen. I do understand a decent chunk of JavaScript, and I understand that how this works is that after setting the canvas width and height to the screen size, we set the fontSize to 16, and we divide the page into columns for the width of each letter. So we have a bunch of columns for the rain. Then those columns each have a rainDrops array index that each start with a value of 1 initially. So on a 1080x1920 screen, there are 120 columns of rain, because 1920/16. In the draw function, which will be called every 30ms, the canvas is filled with an rgba value which is light grey. The font will be assigned 16px monospace green with hex #00FF00. In the for loop, rainDrops.length will be dependent on the number of columns that fit in the screen. 120 columns fit in a 1920 screen. So i will iterate to 120 in that case. alphabet.length is 21 I believe, and the alphabet.charAt() method will look at the letter that is randomly chosen by (Math.floor(Math.random() * alphabet.length)). And this is where the problem is, actually. It's random here, and I'm trying to make it enumerate a sentence out of charAt selections, possibly with a forEach loop or spread operator or something, but nothing I've tried works. fillText is how the letters get displayed in the way that they do. The first parameter takes a string for text, which is the letter. and then the code after that is what determines the strand effect. Parameters 2 and 3 are x and y positions, so it's (16px * array index) and (16px * index value) for i*fontSize and rainDrops[i]*fontSize. 16px * 120 = 1920 on a 1080p screen, filling the x axis. So it goes in the x parameter. So rainDrops[i]*fontSize is what makes the rain fall down. The "if" conditional determines if the rain has fallen too far and then sets index to zero to make it restart from the top. And rainDrops[i]++ is what makes the 1 in every array index grow. They all grow simultaneously at first, that's why the rain all comes down together uniformly at first. The Math.random() in the conditional makes the rain come down more randomly later. So I think I know how this code works. But I don't know how to get a clear sentence out instead of random letters. If someone could help, I would greatly appreciate it. If I could make an enumeration loop but break out of it and increment the initializer I think that could do it. Otherwise it gets stuck in a loop that completes the sentence, but we're trying to get a single letter each time to feed the charAt method. Sorry for writing a novel. Edit: the rgba is used to create the fading letter shader effect, actually, I think, as it is the alpha, which is like transparency. A: In my comment on the original question, I suggested changing line 27 to this: const text = alphabet.charAt((rainDrops[i]-1) % alphabet.length); You can see it applied here. The raindrops array contains integers that represent each stream of text's progress down the window, which may increase to a value beyond the length of the alphabet string. By using the modulo of the number of characters in the alphabet string, the value of text will loop through the string. I subtract 1 because the values in the raindrops array are initialised at 1, so the first character would be skipped if 1 was not subtracted.
Using charAt to enumerate letters one by one in a loop, without getting stuck in a loop, in JavaScript
This is my first post on here, hopefully I'm doing this right. So my friend is trying to get this green raining Matrix code to rain a sentence instead of random letters. html { background: black; height: 100%; overflow: hidden; } body { margin: 0; padding: 0; height: 100%; } const canvas = document.getElementById('Matrix'); const context = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; const alphabet = "Where they at though?" const fontSize = 16; const columns = canvas.width/fontSize; const rainDrops = []; for( let x = 0; x < columns; x++ ) { rainDrops[x] = 1; } const draw = () => { context.fillStyle = 'rgba(0, 0, 0, 0.05)'; context.fillRect(0, 0, canvas.width, canvas.height); context.fillStyle = '#0F0'; context.font = fontSize + 'px monospace'; for(let i = 0; i < rainDrops.length; i++) { const text = alphabet.charAt(Math.floor(Math.random() * alphabet.length)); context.fillText(text, i*fontSize, rainDrops[i]*fontSize); if(rainDrops[i]*fontSize > canvas.height && Math.random() > 0.975){ rainDrops[i] = 0; } rainDrops[i]++; } }; setInterval(draw, 30); If you want to see it in action, here it is on CodePen. I do understand a decent chunk of JavaScript, and I understand that how this works is that after setting the canvas width and height to the screen size, we set the fontSize to 16, and we divide the page into columns for the width of each letter. So we have a bunch of columns for the rain. Then those columns each have a rainDrops array index that each start with a value of 1 initially. So on a 1080x1920 screen, there are 120 columns of rain, because 1920/16. In the draw function, which will be called every 30ms, the canvas is filled with an rgba value which is light grey. The font will be assigned 16px monospace green with hex #00FF00. In the for loop, rainDrops.length will be dependent on the number of columns that fit in the screen. 120 columns fit in a 1920 screen. So i will iterate to 120 in that case. alphabet.length is 21 I believe, and the alphabet.charAt() method will look at the letter that is randomly chosen by (Math.floor(Math.random() * alphabet.length)). And this is where the problem is, actually. It's random here, and I'm trying to make it enumerate a sentence out of charAt selections, possibly with a forEach loop or spread operator or something, but nothing I've tried works. fillText is how the letters get displayed in the way that they do. The first parameter takes a string for text, which is the letter. and then the code after that is what determines the strand effect. Parameters 2 and 3 are x and y positions, so it's (16px * array index) and (16px * index value) for i*fontSize and rainDrops[i]*fontSize. 16px * 120 = 1920 on a 1080p screen, filling the x axis. So it goes in the x parameter. So rainDrops[i]*fontSize is what makes the rain fall down. The "if" conditional determines if the rain has fallen too far and then sets index to zero to make it restart from the top. And rainDrops[i]++ is what makes the 1 in every array index grow. They all grow simultaneously at first, that's why the rain all comes down together uniformly at first. The Math.random() in the conditional makes the rain come down more randomly later. So I think I know how this code works. But I don't know how to get a clear sentence out instead of random letters. If someone could help, I would greatly appreciate it. If I could make an enumeration loop but break out of it and increment the initializer I think that could do it. Otherwise it gets stuck in a loop that completes the sentence, but we're trying to get a single letter each time to feed the charAt method. Sorry for writing a novel. Edit: the rgba is used to create the fading letter shader effect, actually, I think, as it is the alpha, which is like transparency.
[ "In my comment on the original question, I suggested changing line 27 to this:\nconst text = alphabet.charAt((rainDrops[i]-1) % alphabet.length);\n\nYou can see it applied here.\nThe raindrops array contains integers that represent each stream of text's progress down the window, which may increase to a value beyond the length of the alphabet string. By using the modulo of the number of characters in the alphabet string, the value of text will loop through the string. I subtract 1 because the values in the raindrops array are initialised at 1, so the first character would be skipped if 1 was not subtracted.\n" ]
[ 0 ]
[]
[]
[ "css", "for_loop", "javascript" ]
stackoverflow_0074670813_css_for_loop_javascript.txt
Q: How to make DOM object mouse movement fluid? I'm trying to create a function which can move a page element without having to reference it specifically. function testmove(obj, event) { document.getElementById(obj.id).addEventListener("mousemove", move(obj,event)); } function move(obj, event) { document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY; document.getElementById(obj.id).style.position = 'absolute'; document.getElementById(obj.id).style.left = event.clientX + "px"; document.getElementById(obj.id).style.top = event.clientY + "px"; } This is the original code which worked fluidly: function testmove(e) { document.addEventListener('mousemove', logmovement); } function logmovement(e) { document.getElementById("test").innerText = e.clientX + ' ' + e.clientY; document.getElementById("test").style.position = 'absolute'; document.getElementById("test").style.left = e.clientX + "px"; document.getElementById("test").style.top = e.clientY + "px"; mousemove = true; } Any help is greatly appreciated! A: You're attaching the listener to the element rather than the document so it will only respond when the mouse is positioned on that element. You need to assign a function to the listener. At the moment you're assigning the result of calling the move function to the listener. // Pass in the object function testmove(obj) { // Add the listener to the document element as in the // working example. Pass a function that calls `move` to the // listener. document.addEventListener("mousemove", () => move(obj, event)); } function move(obj, event) { document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY; document.getElementById(obj.id).style.position = 'absolute'; document.getElementById(obj.id).style.left = event.clientX + "px"; document.getElementById(obj.id).style.top = event.clientY + "px"; } const obj = { id: 'move' }; testmove(obj); <div id="move">Move</div> A: function testmove(obj, event) { document.getElementById(obj.id).addEventListener("mousemove", move); } function move(event) { document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY; document.getElementById(obj.id).style.position = 'absolute'; document.getElementById(obj.id).style.left = event.clientX + "px"; document.getElementById(obj.id).style.top = event.clientY + "px"; } function testmove(obj, event) { document.getElementById(obj.id).addEventListener("mousemove", function() { testmove(obj, event); }); } This will allow the move function to access the event object and use its clientX and clientY properties to update the position of the DOM object in a more fluid manner.
How to make DOM object mouse movement fluid?
I'm trying to create a function which can move a page element without having to reference it specifically. function testmove(obj, event) { document.getElementById(obj.id).addEventListener("mousemove", move(obj,event)); } function move(obj, event) { document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY; document.getElementById(obj.id).style.position = 'absolute'; document.getElementById(obj.id).style.left = event.clientX + "px"; document.getElementById(obj.id).style.top = event.clientY + "px"; } This is the original code which worked fluidly: function testmove(e) { document.addEventListener('mousemove', logmovement); } function logmovement(e) { document.getElementById("test").innerText = e.clientX + ' ' + e.clientY; document.getElementById("test").style.position = 'absolute'; document.getElementById("test").style.left = e.clientX + "px"; document.getElementById("test").style.top = e.clientY + "px"; mousemove = true; } Any help is greatly appreciated!
[ "\nYou're attaching the listener to the element rather than the document so it will only respond when the mouse is positioned on that element.\n\nYou need to assign a function to the listener. At the moment you're assigning the result of calling the move function to the listener.\n\n\n\n\n// Pass in the object\nfunction testmove(obj) {\n\n // Add the listener to the document element as in the\n // working example. Pass a function that calls `move` to the\n // listener.\n document.addEventListener(\"mousemove\", () => move(obj, event));\n}\n\nfunction move(obj, event) {\n document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY;\n document.getElementById(obj.id).style.position = 'absolute';\n document.getElementById(obj.id).style.left = event.clientX + \"px\";\n document.getElementById(obj.id).style.top = event.clientY + \"px\";\n}\n\nconst obj = { id: 'move' };\n\ntestmove(obj);\n<div id=\"move\">Move</div>\n\n\n\n", "function testmove(obj, event) {\n document.getElementById(obj.id).addEventListener(\"mousemove\", move);\n}\nfunction move(event) {\n document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY;\n document.getElementById(obj.id).style.position = 'absolute';\n document.getElementById(obj.id).style.left = event.clientX + \"px\";\n document.getElementById(obj.id).style.top = event.clientY + \"px\";\n}\nfunction testmove(obj, event) {\n document.getElementById(obj.id).addEventListener(\"mousemove\", function() {\n testmove(obj, event);\n });\n}\n\nThis will allow the move function to access the event object and use its clientX and clientY properties to update the position of the DOM object in a more fluid manner.\n" ]
[ 1, 0 ]
[]
[]
[ "dom", "html", "javascript" ]
stackoverflow_0074678498_dom_html_javascript.txt
Q: Svelte custom event on svelte typescript I'm using clickOutside directive on my svelte-typescript project and I'm getting this error when I assign custom event to the related element Type '{ class: string; onclick_outside: () => boolean; }' is not assignable to type 'HTMLProps<HTMLDivElement>'. Property 'onclick_outside' does not exist on type 'HTMLProps<HTMLDivElement>' here's a snippet of my code {#if profileToolbar} <div transition:fly={{ y: -20, duration: 300 }} use:clickOutside={profileToolbarContainer} on:click_outside={() => (profileToolbar = !profileToolbar)} class="origin-top-right absolute right-0 mt-2 w-48 rounded-md shadow-lg z-10 shadow-md"> this is the clickOutside directive that I'm using currently https://svelte.dev/repl/0ace7a508bd843b798ae599940a91783?version=3.16.7 I'm new to typescript so I don't really know where to start with my google search, anyone knows how to tackle this issue? thanks for your help A: According to the doc, you can create a .d.ts file in your project somewhere. And put inside that file the following: declare namespace svelte.JSX { interface HTMLAttributes<T> { onclick_outside: () => void } } Please read the doc for more detail. A: This declaration worked for me declare namespace svelte.JSX { interface DOMAttributes<T> { onclick_outside?: CompositionEventHandler<T>; } } Don't forget to specify the location of your custom type declarations in tsconfig.json A: Ok, so existing answers did work only partly for me. Given that the clickOutside action fires a custom event named click_outside i arrive at following solution: declare namespace svelte.JSX { interface HTMLProps<T> { onclick_outside?: (e: CustomEvent) => void; } } A: For me the following worked: declare namespace svelteHTML { interface HTMLAttributes<T> { "on:click_outside"?: CompositionEventHandler<T>; } } inside your src/app.d.ts. based on this
Svelte custom event on svelte typescript
I'm using clickOutside directive on my svelte-typescript project and I'm getting this error when I assign custom event to the related element Type '{ class: string; onclick_outside: () => boolean; }' is not assignable to type 'HTMLProps<HTMLDivElement>'. Property 'onclick_outside' does not exist on type 'HTMLProps<HTMLDivElement>' here's a snippet of my code {#if profileToolbar} <div transition:fly={{ y: -20, duration: 300 }} use:clickOutside={profileToolbarContainer} on:click_outside={() => (profileToolbar = !profileToolbar)} class="origin-top-right absolute right-0 mt-2 w-48 rounded-md shadow-lg z-10 shadow-md"> this is the clickOutside directive that I'm using currently https://svelte.dev/repl/0ace7a508bd843b798ae599940a91783?version=3.16.7 I'm new to typescript so I don't really know where to start with my google search, anyone knows how to tackle this issue? thanks for your help
[ "According to the doc, you can create a .d.ts file in your project somewhere. And put inside that file the following:\ndeclare namespace svelte.JSX {\n interface HTMLAttributes<T> {\n onclick_outside: () => void\n }\n}\n\nPlease read the doc for more detail.\n", "This declaration worked for me\ndeclare namespace svelte.JSX {\n interface DOMAttributes<T> {\n onclick_outside?: CompositionEventHandler<T>;\n }\n}\n\nDon't forget to specify the location of your custom type declarations in tsconfig.json\n", "Ok, so existing answers did work only partly for me. Given that the clickOutside action fires a custom event named click_outside i arrive at following solution:\ndeclare namespace svelte.JSX {\n interface HTMLProps<T> {\n onclick_outside?: (e: CustomEvent) => void;\n }\n}\n\n", "For me the following worked:\ndeclare namespace svelteHTML {\n interface HTMLAttributes<T> {\n \"on:click_outside\"?: CompositionEventHandler<T>;\n }\n}\n\ninside your src/app.d.ts.\nbased on this\n" ]
[ 26, 15, 11, 0 ]
[]
[]
[ "javascript", "svelte", "svelte_3", "typescript", "typescript_typings" ]
stackoverflow_0064131176_javascript_svelte_svelte_3_typescript_typescript_typings.txt
Q: Fetched content disappears when I refresh the page whenever I refresh my page the fetched content I've loaded decides to disappear, it will load the first time but every time after that it will go. I have another component that has almost the same code and that one works fine so I'm not entirely sure why it doesn't with this component. the feeling I have is in my standings.svelte component I have a flatMap function which is the main difference compared to my other components. here is a video showing what happens when I refresh the page. This won't happen to any other component but this one. (https://imgur.com/a/Ew4bwgB) This is my standings.svelte component <script> import {leagueStandings} from "../../stores/league-standings-stores" const tablePositions = $leagueStandings.flatMap(({ standings: { data } }) => data); </script> <div class="bg-[#1C1C25] p-8 rounded-lg box-border w-fit"> {#each tablePositions as tablePosition} <div class="standings-table flex gap-9 mb-2 pb-4 pt-3 border-b border-[#303041]"> <div class="team-details flex gap-4 w-full" id="td"> <p class="w-[18px]">{tablePosition.position}</p> <img src="{tablePosition.team.data.logo_path}" alt="" class="w-[1.5em] object-scale-down"> <p class="">{tablePosition.team_name}</p> </div> <div class="team-stats flex gap-5 text-left child:w-5 child:text-center w-full"> <p>{tablePosition.overall.games_played}</p> <p>{tablePosition.overall.won}</p> <p>{tablePosition.overall.draw}</p> <p>{tablePosition.overall.lost}</p> <p>{tablePosition.overall.goals_scored}</p> <p>{tablePosition.overall.goals_against}</p> <p>{tablePosition.total.goal_difference}</p> <p>{tablePosition.overall.points}</p> <p class="!w-[78px] !text-left">{tablePosition.recent_form}</p> </div> </div> {/each} </div> Here is my svelte store import { writable } from "svelte/store"; export const leagueStandings = writable([]); const fetchStandings = async () => { const url = `https://soccer.sportmonks.com/api/v2.0/standings/season/19734?api_token=API_KEY`; const res = await fetch(url); const data = await res.json(); leagueStandings.set(data.data); } fetchStandings(); id love some advice on what im doing wrong :) A: It looks like you are using the writable store from Svelte, which means that the data in the store will be reset whenever the component is re-rendered. This is why the data disappears when you refresh the page. One way to fix this is to use the derived store from Svelte, which allows you to create a store that is derived from other stores. This way, you can ensure that the data in the store is not reset when the component is re-rendered. Here is how you can modify your code to use a derived store: import { writable } from "svelte/store"; import { derived } from "svelte/store"; // Create a writable store to store the league standings data const leagueStandingsData = writable([]); // Create a derived store to flatten the data from the leagueStandingsData store export const leagueStandings = derived(leagueStandingsData, $leagueStandingsData => { return $leagueStandingsData.flatMap(({ standings: { data } }) => data); }); // Function to fetch the league standings data and update the leagueStandingsData store const fetchStandings = async () => { const url = `https://soccer.sportmonks.com/api/v2.0/standings/season/19734?api_token=API_KEY`; const res = await fetch(url); const data = await res.json(); leagueStandingsData.set(data.data); } // Fetch the data when the component is mounted fetchStandings(); Now, in your component, you can use the leagueStandings store to access the flattened data, like this: <script> import { leagueStandings } from "../../stores/league-standings-stores" // Access the flattened data from the leagueStandings store const tablePositions = $leagueStandings; </script> <!-- Use the tablePositions variable to render the standings table --> <div class="bg-[#1C1C25] p-8 rounded-lg box-border w-fit"> {#each tablePositions as tablePosition} <div class="standings-table flex gap-9 mb-2 pb-4 pt-3 border-b border-[#303041]"> <div class="team-details flex gap-4 w-full" id="td"> <p class="w-[18px]">{tablePosition.position}</p> <img src="{tablePosition.team.data.logo_path}" alt="" class="w-[1.5em] object-scale-down"> <p class="">{tablePosition.team_name}</p> </div> <div class="team-stats flex gap-5 text-left child:w-5 child:text-center w-full"> <p>{tablePosition.overall.games_played}</p> <p>{tablePosition.overall.won}</p> <p>{tablePosition.overall.draw}</p> <p>{tablePosition.overall.lost}</p> <p>{tablePosition.overall.goals_scored}</p> A: Data by default doesn't persist in svelte/store. When you transition from one component to another the data get passed on to the child or linked component. But on refreshing the page that data is not accessible since you are directly accessing the child/linked component. To be able to access the data after refresh you need to store them in Browser's localStorage. You can try this solution https://stackoverflow.com/a/56489832/14018280
Fetched content disappears when I refresh the page
whenever I refresh my page the fetched content I've loaded decides to disappear, it will load the first time but every time after that it will go. I have another component that has almost the same code and that one works fine so I'm not entirely sure why it doesn't with this component. the feeling I have is in my standings.svelte component I have a flatMap function which is the main difference compared to my other components. here is a video showing what happens when I refresh the page. This won't happen to any other component but this one. (https://imgur.com/a/Ew4bwgB) This is my standings.svelte component <script> import {leagueStandings} from "../../stores/league-standings-stores" const tablePositions = $leagueStandings.flatMap(({ standings: { data } }) => data); </script> <div class="bg-[#1C1C25] p-8 rounded-lg box-border w-fit"> {#each tablePositions as tablePosition} <div class="standings-table flex gap-9 mb-2 pb-4 pt-3 border-b border-[#303041]"> <div class="team-details flex gap-4 w-full" id="td"> <p class="w-[18px]">{tablePosition.position}</p> <img src="{tablePosition.team.data.logo_path}" alt="" class="w-[1.5em] object-scale-down"> <p class="">{tablePosition.team_name}</p> </div> <div class="team-stats flex gap-5 text-left child:w-5 child:text-center w-full"> <p>{tablePosition.overall.games_played}</p> <p>{tablePosition.overall.won}</p> <p>{tablePosition.overall.draw}</p> <p>{tablePosition.overall.lost}</p> <p>{tablePosition.overall.goals_scored}</p> <p>{tablePosition.overall.goals_against}</p> <p>{tablePosition.total.goal_difference}</p> <p>{tablePosition.overall.points}</p> <p class="!w-[78px] !text-left">{tablePosition.recent_form}</p> </div> </div> {/each} </div> Here is my svelte store import { writable } from "svelte/store"; export const leagueStandings = writable([]); const fetchStandings = async () => { const url = `https://soccer.sportmonks.com/api/v2.0/standings/season/19734?api_token=API_KEY`; const res = await fetch(url); const data = await res.json(); leagueStandings.set(data.data); } fetchStandings(); id love some advice on what im doing wrong :)
[ "It looks like you are using the writable store from Svelte, which means that the data in the store will be reset whenever the component is re-rendered. This is why the data disappears when you refresh the page.\nOne way to fix this is to use the derived store from Svelte, which allows you to create a store that is derived from other stores. This way, you can ensure that the data in the store is not reset when the component is re-rendered.\nHere is how you can modify your code to use a derived store:\nimport { writable } from \"svelte/store\";\nimport { derived } from \"svelte/store\";\n\n// Create a writable store to store the league standings data\nconst leagueStandingsData = writable([]);\n\n// Create a derived store to flatten the data from the leagueStandingsData store\nexport const leagueStandings = derived(leagueStandingsData, $leagueStandingsData => {\n return $leagueStandingsData.flatMap(({ standings: { data } }) => data);\n});\n\n// Function to fetch the league standings data and update the leagueStandingsData store\nconst fetchStandings = async () => {\n const url = `https://soccer.sportmonks.com/api/v2.0/standings/season/19734?api_token=API_KEY`;\n const res = await fetch(url);\n const data = await res.json();\n leagueStandingsData.set(data.data);\n}\n\n// Fetch the data when the component is mounted\nfetchStandings();\n\nNow, in your component, you can use the leagueStandings store to access the flattened data, like this:\n<script>\nimport { leagueStandings } from \"../../stores/league-standings-stores\"\n\n// Access the flattened data from the leagueStandings store\nconst tablePositions = $leagueStandings;\n</script>\n\n<!-- Use the tablePositions variable to render the standings table -->\n<div class=\"bg-[#1C1C25] p-8 rounded-lg box-border w-fit\">\n {#each tablePositions as tablePosition}\n <div class=\"standings-table flex gap-9 mb-2 pb-4 pt-3 border-b border-[#303041]\">\n <div class=\"team-details flex gap-4 w-full\" id=\"td\">\n <p class=\"w-[18px]\">{tablePosition.position}</p>\n <img src=\"{tablePosition.team.data.logo_path}\" alt=\"\" class=\"w-[1.5em] object-scale-down\">\n <p class=\"\">{tablePosition.team_name}</p>\n </div>\n\n <div class=\"team-stats flex gap-5 text-left child:w-5 child:text-center w-full\">\n <p>{tablePosition.overall.games_played}</p>\n <p>{tablePosition.overall.won}</p>\n <p>{tablePosition.overall.draw}</p>\n <p>{tablePosition.overall.lost}</p>\n <p>{tablePosition.overall.goals_scored}</p>\n\n", "Data by default doesn't persist in svelte/store. When you transition from one component to another the data get passed on to the child or linked component. But on refreshing the page that data is not accessible since you are directly accessing the child/linked component. To be able to access the data after refresh you need to store them in Browser's localStorage. You can try this solution https://stackoverflow.com/a/56489832/14018280\n" ]
[ 0, 0 ]
[]
[]
[ "fetch_api", "javascript", "svelte", "sveltekit" ]
stackoverflow_0074678598_fetch_api_javascript_svelte_sveltekit.txt
Q: Database indexes and their Big-O notation I'm trying to understand the performance of database indexes in terms of Big-O notation. Without knowing much about it, I would guess that: Querying on a primary key or unique index will give you a O(1) lookup time. Querying on a non-unique index will also give a O(1) time, albeit maybe the '1' is slower than for the unique index (?) Querying on a column without an index will give a O(N) lookup time (full table scan). Is this generally correct ? Will querying on a primary key ever give worse performance than O(1) ? My specific concern is for SQLite, but I'd be interested in knowing to what extent this varies between different databases too. A: Most relational databases structure indices as B-trees. If a table has a clustering index, the data pages are stored as the leaf nodes of the B-tree. Essentially, the clustering index becomes the table. For tables w/o a clustering index, the data pages of the table are stored in a heap. Any non-clustered indices are B-trees where the leaf node of the B-tree identifies a particular page in the heap. The worst case height of a B-tree is O(log n), and since a search is dependent on height, B-tree lookups run in something like (on the average) O(logt n) where t is the minimization factor ( each node must have at least t-1 keys and at most 2*t* -1 keys (e.g., 2*t* children). That's the way I understand it. And different database systems, of course, may well use different data structures under the hood. And if the query does not use an index, of course, then the search is an iteration over the heap or B-tree containing the data pages. Searches are a little cheaper if the index used can satisfy the query; otherwise, a lookaside to fetch the corresponding datapage in memory is required. A: The indexed queries (unique or not) are more typically O(log n). Very simplistically, you can think of it as being similar to a binary search in a sorted array. More accurately, it depends on the index type. But a b-tree search, for example, is still O(log n). If there is no index, then, yes, it is O(N). A: If you SELECT the same columns you search for then Primary or Unqiue will be O(log n): it's a b-tree search non-unique index is also O(log n) + a bit: it's a b-tree search no index = O(N) If you require information from another "source" (index intersection, bookmark/key lookup etc) because the index is non-covering, then you could have O(n + log n) or O(log n + log n + log n) because of multiple index hits + intermediate sorting. If statistics show that you require a high % of rows (eg not very selective index) then the index may be ignored and become a scan = O(n) A: Other answers give a good starting point; but I would just add that to get O(1), primary index itself would need to be hash-based (which is typically not the default choice); so more commonly it is logarithmic (B-tree). You are correct in that secondary indexes typically have same complexity, but worse actual performance -- this because index and data are not clustered, so the constant (number of disk seeks) is bigger. A: It depends on what your query is. A condition of the form Column = Value allows the use of a hash-based index, which has O(1) lookup time. However, many databases, including SQLite, do not support them. A condition using relational operators (<, >, <=, >=) can make use of an ordered index, typically implemented with a binary tree, which has O(log n) lookup time. More complicated expressions which cannot use an index require O(n) time. Since you're primarily interested in SQLite, you might want to read its Query Optimizer Overview which explains in more detail how indexes are selected. A: That's a great question. It deserves a book to be written! The three major things here are the search algorithm applied and the size of the read blocks to process the type of the index (hashed, B-Tree, or other) The complexity of O(1), in general, is applied to hashed indexes, and the data that the database engine has in the cache. Most DB engines use B-Tree indexes by default. The clustered indexes are not an exception. That's why when searching by a primary key, you should expect complexity O(log N). In this nice article you can find more details on what is going on under the hood:
Database indexes and their Big-O notation
I'm trying to understand the performance of database indexes in terms of Big-O notation. Without knowing much about it, I would guess that: Querying on a primary key or unique index will give you a O(1) lookup time. Querying on a non-unique index will also give a O(1) time, albeit maybe the '1' is slower than for the unique index (?) Querying on a column without an index will give a O(N) lookup time (full table scan). Is this generally correct ? Will querying on a primary key ever give worse performance than O(1) ? My specific concern is for SQLite, but I'd be interested in knowing to what extent this varies between different databases too.
[ "Most relational databases structure indices as B-trees.\nIf a table has a clustering index, the data pages are stored as the leaf nodes of the B-tree. Essentially, the clustering index becomes the table.\nFor tables w/o a clustering index, the data pages of the table are stored in a heap. Any non-clustered indices are B-trees where the leaf node of the B-tree identifies a particular page in the heap.\nThe worst case height of a B-tree is O(log n), and since a search is dependent on height, B-tree lookups run in something like (on the average)\nO(logt n)\nwhere t is the minimization factor ( each node must have at least t-1 keys and at most 2*t* -1 keys (e.g., 2*t* children).\nThat's the way I understand it.\nAnd different database systems, of course, may well use different data structures under the hood.\nAnd if the query does not use an index, of course, then the search is an iteration over the heap or B-tree containing the data pages.\nSearches are a little cheaper if the index used can satisfy the query; otherwise, a lookaside to fetch the corresponding datapage in memory is required.\n", "The indexed queries (unique or not) are more typically O(log n). Very simplistically, you can think of it as being similar to a binary search in a sorted array. More accurately, it depends on the index type. But a b-tree search, for example, is still O(log n).\nIf there is no index, then, yes, it is O(N).\n", "If you SELECT the same columns you search for then \n\nPrimary or Unqiue will be O(log n): it's a b-tree search\nnon-unique index is also O(log n) + a bit: it's a b-tree search\nno index = O(N)\n\nIf you require information from another \"source\" (index intersection, bookmark/key lookup etc) because the index is non-covering, then you could have O(n + log n) or O(log n + log n + log n) because of multiple index hits + intermediate sorting.\nIf statistics show that you require a high % of rows (eg not very selective index) then the index may be ignored and become a scan = O(n)\n", "Other answers give a good starting point; but I would just add that to get O(1), primary index itself would need to be hash-based (which is typically not the default choice); so more commonly it is logarithmic (B-tree).\nYou are correct in that secondary indexes typically have same complexity, but worse actual performance -- this because index and data are not clustered, so the constant (number of disk seeks) is bigger.\n", "It depends on what your query is.\n\nA condition of the form Column = Value allows the use of a hash-based index, which has O(1) lookup time. However, many databases, including SQLite, do not support them.\nA condition using relational operators (<, >, <=, >=) can make use of an ordered index, typically implemented with a binary tree, which has O(log n) lookup time.\nMore complicated expressions which cannot use an index require O(n) time.\n\nSince you're primarily interested in SQLite, you might want to read its Query Optimizer Overview which explains in more detail how indexes are selected.\n", "That's a great question. It deserves a book to be written!\nThe three major things here are\n\nthe search algorithm applied and\nthe size of the read blocks to process\nthe type of the index (hashed, B-Tree, or other)\n\nThe complexity of O(1), in general, is applied to hashed indexes, and the data that the database engine has in the cache.\nMost DB engines use B-Tree indexes by default. The clustered indexes are not an exception. That's why when searching by a primary key, you should expect complexity O(log N).\nIn this nice article you can find more details on what is going on under the hood:\n\n" ]
[ 40, 11, 5, 4, 3, 0 ]
[]
[]
[ "big_o", "database", "indexing", "sql", "sqlite" ]
stackoverflow_0004694574_big_o_database_indexing_sql_sqlite.txt
Q: How to disable Neptune callback in transformers trainer runs? After installing Neptune.ai for occasional ML experiments logging, it became included by default into the list of callbacks in all transformers.trainer runs. As a result, it requires proper initialisation with token or else throws NeptuneMissingConfiguration error, demanding token and project name. This is really annoying, I'd prefer Neptune callback to limit itself to warning or just have it disabled if no token is provided. Unfortunately there is no obvious way to disable this callback, short of uninstalling Neptune.ai altogether. The doc page at https://huggingface.co/docs/transformers/main_classes/callback states that this callback is enabled by default and gives no way to disable it (unlike some other callbacks that can be disabled by environment variable). Question: how to disable Neptune callback on per run basis? A: To disable Neptune callback in transformers trainer runs, you can pass the --no-neptune flag to the trainer.train() function. trainer = Trainer( model=model, args=args, train_dataset=train_dataset, eval_dataset=eval_dataset, no_neptune=True ) trainer.train() A: Apparently this piece of code after trainer initialization helps: for cb in trainer.callback_handler.callbacks: if isinstance(cb, transformers.integrations.NeptuneCallback): trainer.callback_handler.remove_callback(cb) Still it would be good if Transformers or Neptune team provided more flexibility with this callback.
How to disable Neptune callback in transformers trainer runs?
After installing Neptune.ai for occasional ML experiments logging, it became included by default into the list of callbacks in all transformers.trainer runs. As a result, it requires proper initialisation with token or else throws NeptuneMissingConfiguration error, demanding token and project name. This is really annoying, I'd prefer Neptune callback to limit itself to warning or just have it disabled if no token is provided. Unfortunately there is no obvious way to disable this callback, short of uninstalling Neptune.ai altogether. The doc page at https://huggingface.co/docs/transformers/main_classes/callback states that this callback is enabled by default and gives no way to disable it (unlike some other callbacks that can be disabled by environment variable). Question: how to disable Neptune callback on per run basis?
[ "To disable Neptune callback in transformers trainer runs, you can pass the --no-neptune flag to the trainer.train() function.\ntrainer = Trainer(\n model=model,\n args=args,\n train_dataset=train_dataset,\n eval_dataset=eval_dataset,\n no_neptune=True\n)\ntrainer.train()\n\n", "Apparently this piece of code after trainer initialization helps:\nfor cb in trainer.callback_handler.callbacks:\n if isinstance(cb, transformers.integrations.NeptuneCallback):\n trainer.callback_handler.remove_callback(cb)\n\nStill it would be good if Transformers or Neptune team provided more flexibility with this callback.\n" ]
[ 0, 0 ]
[]
[]
[ "callback", "huggingface_transformers", "neptune", "python", "pytorch" ]
stackoverflow_0074678703_callback_huggingface_transformers_neptune_python_pytorch.txt
Q: HTML table CSS colour only for text, not for border? I have tried the following, but it makes the border also red. I want to make only text red. Is that possible? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <style> .class2, .class2 tr, .class2 td { border: solid 2px; border-collapse: collapse; } .class1{ color: red; } </style> </head> <body> <table class="class2"> <tr class="class1"> <td>hello</td> <td>world</td> </tr> <tr> <td>hello</td> <td>world</td> </tr> </table> </body> </html> A: You could add a rule into the class to override the border-color: .class1 td { color: red; border-color: #000; } However, I would normally add the color to the main border declaration like so: .class2, .class2 tr, .class2 td { border: solid 2px #000; border-collapse: collapse; } A: you need to specify a tag with the color class for the text, like this with the span element and it should only color the text while keeping borders in the original color. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <style> .class2, .class2 tr, .class2 td { border: solid 2px; border-collapse: collapse; } .class1{ color: red; } </style> </head> <body> <table class="class2"> <tr> <td><span class="class1">hello</span></td> <td><span class="class1">world</span></td> </tr> <tr> <td>hello</td> <td>world</td> </tr> </table> </body> </html> A: Remove td from .class1 td , that td is causing to apply the style on table too , and the color tag works just on text if nothing else is specified A: Having read your comments since my original posting, it maybe worth you having a look at media queries, as it seems you can target user themes using them (although this may currently have limited browser support). For me, running dark theme on my machine, I see a yellow border, but in light theme, I see red. (For reference I'm using Google Chrome). This way, you can set a border color for both light and dark themes. <html> <head> <meta charset="utf-8"> <style> .class2, .class2 tr, .class2 td { border: solid 2px currentcolor; border-collapse: collapse; } .class1 td { color: red; } @media (prefers-color-scheme: dark) { .class1 td { border-color: #FF0; } } </style> </head> <body> <table class="class2"> <tr class="class1"> <td>hello</td> <td>world</td> </tr> <tr> <td>hello</td> <td>world</td> </tr> </table> </body> </html> A: You can add the border-color rule to your table to set the border color as black. .class2, .class2 tr, .class2 td { border: solid 2px; border-collapse: collapse; border-color: #000; }
HTML table CSS colour only for text, not for border?
I have tried the following, but it makes the border also red. I want to make only text red. Is that possible? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <style> .class2, .class2 tr, .class2 td { border: solid 2px; border-collapse: collapse; } .class1{ color: red; } </style> </head> <body> <table class="class2"> <tr class="class1"> <td>hello</td> <td>world</td> </tr> <tr> <td>hello</td> <td>world</td> </tr> </table> </body> </html>
[ "You could add a rule into the class to override the border-color:\n.class1 td {\n color: red;\n border-color: #000;\n}\n\nHowever, I would normally add the color to the main border declaration like so:\n.class2,\n.class2 tr,\n.class2 td {\n border: solid 2px #000;\n border-collapse: collapse;\n}\n\n", "you need to specify a tag with the color class for the text, like this with the span element and it should only color the text while keeping borders in the original color.\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"utf-8\">\n <style>\n .class2,\n .class2 tr,\n .class2 td {\n border: solid 2px;\n border-collapse: collapse;\n }\n \n .class1{\n color: red;\n }\n </style>\n</head>\n\n<body>\n <table class=\"class2\">\n <tr>\n <td><span class=\"class1\">hello</span></td>\n <td><span class=\"class1\">world</span></td>\n </tr>\n <tr>\n <td>hello</td>\n <td>world</td>\n </tr>\n </table>\n</body>\n\n</html>\n\n\n\n", "Remove td from .class1 td , that td is causing to apply the style on table too , and the color tag works just on text if nothing else is specified\n", "Having read your comments since my original posting, it maybe worth you having a look at media queries, as it seems you can target user themes using them (although this may currently have limited browser support). For me, running dark theme on my machine, I see a yellow border, but in light theme, I see red. (For reference I'm using Google Chrome). This way, you can set a border color for both light and dark themes.\n<html>\n<head>\n <meta charset=\"utf-8\">\n <style>\n .class2,\n .class2 tr,\n .class2 td {\n border: solid 2px currentcolor;\n border-collapse: collapse;\n }\n \n .class1 td {\n color: red;\n \n }\n \n @media (prefers-color-scheme: dark) {\n .class1 td {\n border-color: #FF0;\n }\n }\n </style>\n</head>\n\n<body>\n <table class=\"class2\">\n <tr class=\"class1\">\n <td>hello</td>\n <td>world</td>\n </tr>\n <tr>\n <td>hello</td>\n <td>world</td>\n </tr>\n </table>\n</body>\n</html>\n\n", "You can add the border-color rule to your table to set the border color as black.\n .class2,\n .class2 tr,\n .class2 td {\n border: solid 2px;\n border-collapse: collapse;\n\n border-color: #000;\n\n }\n\n" ]
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "css" ]
stackoverflow_0074677799_css.txt
Q: What is the keyboard shortcut for getting into Variables section in Debug Window in PyCharm I try to avoid usage of mouse. When the process is stopped in debugging, I am in Debugger window. Specifically in section called "Frames" which displays current stacktrace. How can I navigate to section called "Variables" with a keyboard only? A: I guess ALT+5 will help you ; https://www.shortcutfoo.com/app/dojos/pycharm-win/cheatsheet Keyboard shortcut to switch between python console and the editor in pycharm
What is the keyboard shortcut for getting into Variables section in Debug Window in PyCharm
I try to avoid usage of mouse. When the process is stopped in debugging, I am in Debugger window. Specifically in section called "Frames" which displays current stacktrace. How can I navigate to section called "Variables" with a keyboard only?
[ "I guess ALT+5 will help you ;\nhttps://www.shortcutfoo.com/app/dojos/pycharm-win/cheatsheet\n\nKeyboard shortcut to switch between python console and the editor in pycharm\n\n" ]
[ 0 ]
[]
[]
[ "debugging", "jetbrains_ide", "keyboard_shortcuts", "pycharm" ]
stackoverflow_0039511440_debugging_jetbrains_ide_keyboard_shortcuts_pycharm.txt
Q: route cloud static IP to home private network I have my own servers and have hosted a few services (game servers, web servers, ...), and use to host these on a publicly accessible dynamic IP using DuckDNS. I have recently moved to a rural area and use a satellite service for my internet that does not support publicly accessible IP address. I would really like to host these things again, but the only way I can think of doing that, is to have an IP somewhere in the cloud and route that back into my network. I have been messing around in Azure but I can't seem to get what I want working. I am not stuck on Azure, just happens to be the one I am message about with. I have pfSense as my router, so I can setup a VPN client on that and pretty much keep that alive indefinitely, so here is what I am thinking and I hope someone can point my in the right direction, or if you like, poke holes in the idea. I configure a VPN client on pfSense to be an WAN interface create a VPN gateway in the cloud connect pfSense VPN client to the VPN gateway create a static external IP in the cloud route traffic from the external ip through the VPN back to my pfSense server and into my internal network once I get the traffic coming into pfSense , I can route to computers / VMs on my internal network. This way, I do not need a publicly accessible IP from my ISP, I can connect to the Azure and use its external IP and route back through the VPN to my internal network. If this was real hardware, I would have had this built in 30 minutes, seems this virtual world is messing me up. Any ideas on how to configure this or maybe another solution? I am struggling with the whole Azure setup and have watch hours of videos about each of the bit in Azure, but I am lacking some key bits of knowledge to bring this together. A: If you know what you are doing with pfSense... cloudfanatic.net $2.99 US a month for a VPS running pfSense. They will spin up a VPS with pfSense on it at no extra charge. Open an account, send support an email. Gives you a static permanent IP. Shared 1GB Internet link. No data limits. I see between 150 and 500Mbps. Perfectly fine for what I use it for. Wireguard on that pfSense, people connect in, etc... I've been using it for about 6+ months. Been very impressed. Chunky A: It sounds like you have a good understanding of the overall setup that you want to achieve. One approach that you could take is to create a virtual network in Azure, and then create a VPN gateway in that virtual network. Next, you can configure your pfSense router to connect to the VPN gateway using a VPN client. Once you have established the VPN connection between your pfSense router and the VPN gateway in Azure, you can create a static external IP in Azure and associate it with the VPN gateway. This will allow you to access your services on your internal network using the static external IP. In terms of routing traffic from the external IP to your internal network, you will need to configure your pfSense router to route traffic from the VPN client interface to your internal network. This can be done by creating a static route in pfSense that points to the IP range of your internal network, and specifying the VPN client interface as the gateway for that route. It's worth noting that Azure does provide detailed documentation on how to set up a VPN gateway and connect to it using various VPN clients, including pfSense. You may find it helpful to refer to these guides to help you configure your setup. Additionally, there are many online resources and tutorials available that can provide step-by-step instructions on how to set up a VPN connection in Azure and route traffic between your internal network and the VPN gateway.
route cloud static IP to home private network
I have my own servers and have hosted a few services (game servers, web servers, ...), and use to host these on a publicly accessible dynamic IP using DuckDNS. I have recently moved to a rural area and use a satellite service for my internet that does not support publicly accessible IP address. I would really like to host these things again, but the only way I can think of doing that, is to have an IP somewhere in the cloud and route that back into my network. I have been messing around in Azure but I can't seem to get what I want working. I am not stuck on Azure, just happens to be the one I am message about with. I have pfSense as my router, so I can setup a VPN client on that and pretty much keep that alive indefinitely, so here is what I am thinking and I hope someone can point my in the right direction, or if you like, poke holes in the idea. I configure a VPN client on pfSense to be an WAN interface create a VPN gateway in the cloud connect pfSense VPN client to the VPN gateway create a static external IP in the cloud route traffic from the external ip through the VPN back to my pfSense server and into my internal network once I get the traffic coming into pfSense , I can route to computers / VMs on my internal network. This way, I do not need a publicly accessible IP from my ISP, I can connect to the Azure and use its external IP and route back through the VPN to my internal network. If this was real hardware, I would have had this built in 30 minutes, seems this virtual world is messing me up. Any ideas on how to configure this or maybe another solution? I am struggling with the whole Azure setup and have watch hours of videos about each of the bit in Azure, but I am lacking some key bits of knowledge to bring this together.
[ "If you know what you are doing with pfSense...\ncloudfanatic.net\n$2.99 US a month for a VPS running pfSense. They will spin up a VPS with pfSense on it at no extra charge. Open an account, send support an email.\nGives you a static permanent IP. Shared 1GB Internet link. No data limits. I see between 150 and 500Mbps. Perfectly fine for what I use it for.\nWireguard on that pfSense, people connect in, etc...\nI've been using it for about 6+ months. Been very impressed.\nChunky\n", "It sounds like you have a good understanding of the overall setup that you want to achieve. One approach that you could take is to create a virtual network in Azure, and then create a VPN gateway in that virtual network. Next, you can configure your pfSense router to connect to the VPN gateway using a VPN client.\nOnce you have established the VPN connection between your pfSense router and the VPN gateway in Azure, you can create a static external IP in Azure and associate it with the VPN gateway. This will allow you to access your services on your internal network using the static external IP.\nIn terms of routing traffic from the external IP to your internal network, you will need to configure your pfSense router to route traffic from the VPN client interface to your internal network. This can be done by creating a static route in pfSense that points to the IP range of your internal network, and specifying the VPN client interface as the gateway for that route.\nIt's worth noting that Azure does provide detailed documentation on how to set up a VPN gateway and connect to it using various VPN clients, including pfSense. You may find it helpful to refer to these guides to help you configure your setup. Additionally, there are many online resources and tutorials available that can provide step-by-step instructions on how to set up a VPN connection in Azure and route traffic between your internal network and the VPN gateway.\n" ]
[ 0, 0 ]
[]
[]
[ "azure", "cloud", "pfsense", "routes" ]
stackoverflow_0074370634_azure_cloud_pfsense_routes.txt
Q: Acessing class methods from another class? Lets say I have this: Main: public class Main { public static void main(String[] args) { Orchestra orchestra = new Orchestra(); Drum drum = new Drum(); Xylophone xylophone = new Xylophone(); //---------------------------------- drum.sendToOrchestra(); xylophone.sendToOrchestra(); } } Drum: public class Drum{ public void play(String note){ System.out.println("Playing... drums (note " + note + ")"); } public void sendToOrchestra(){ Orchestra orchestra = new Orchestra(this); } } Xylophone: public class Xylophone{ public void play(String note){ System.out.println("Playing... xylophone (note " + note + ")"); } public void sendToOrchestra(){ Orchestra orchestra = new Orchestra(this); } } Orchestra: public class Orchestra { static Object[] instrumentsArray = new Object[2]; public Orchestra(){ } public Orchestra(Xylophone xylophone){ // this works: xylophone.play() instrumentArray[0] = xylophone; // but this does not: instrumentsArray[0].play() } public Orchestra(Drum drum){ // this works: drum.play() instrumentArray[1] = drum; // but this does not: instrumentsArray[1].play() } public void playInstruments(){ // here is where I will iterate through the instrumentsArray, and make all elements inside it: .play() } } My question would be, how can access the instances methods, after they are inserted into the array? Because I can access them before they go into the array. A: I would argue that you have mixed up your class' concerns and have caused too much coupling between your classes. Main, should be to create all the objects. It would create the Orchestra, Drum, and Xylophone. The Drum and Xylophone instances would then be added to the Orchestra instance directly in the main method. The Drum and Xylophone shouldn't know about the Orchestra class at all. Then Main will have access to the playInstruments() method of Orchestra. Side Notes I would recommend that both Drum and Xylophone implement an interface called Instrument that has one method called play(String note). So then the Orchestra doesn't have to be coupled to specifically Drums and Xylophones, it could just have Instruments and you could add all kinds of Instruments later without every having to edit your base Orchestra class. Examples Possible new Orchestra class: import java.util.ArrayList; import java.util.List; public class Orchestra { private List<Instrument> instruments; public Orchestra() { this.instruments = new ArrayList<>(); } public Orchestra(List<Instrument> instruments) { this.instruments = instruments; } public void add(Instrument instrument) { this.instruments.add(instrument); } public void play() { this.instruments.forEach(i -> i.play("b flat")); } } Instrument interface: public interface Instrument { void play(String note); } Drum: public class Drum implements Instrument { @Override public void play(String note) { System.out.println("Drums: " + note); } } Xylophone: public class Xylophone implements Instrument { @Override public void play(String note) { System.out.println("Xylophone: " + note); } } And finally, Main: public class Main { public static void main(String[] args) { Orchestra orchestra = new Orchestra(); orchestra.add(new Drum()); orchestra.add(new Xylophone()); orchestra.play(); } }
Acessing class methods from another class?
Lets say I have this: Main: public class Main { public static void main(String[] args) { Orchestra orchestra = new Orchestra(); Drum drum = new Drum(); Xylophone xylophone = new Xylophone(); //---------------------------------- drum.sendToOrchestra(); xylophone.sendToOrchestra(); } } Drum: public class Drum{ public void play(String note){ System.out.println("Playing... drums (note " + note + ")"); } public void sendToOrchestra(){ Orchestra orchestra = new Orchestra(this); } } Xylophone: public class Xylophone{ public void play(String note){ System.out.println("Playing... xylophone (note " + note + ")"); } public void sendToOrchestra(){ Orchestra orchestra = new Orchestra(this); } } Orchestra: public class Orchestra { static Object[] instrumentsArray = new Object[2]; public Orchestra(){ } public Orchestra(Xylophone xylophone){ // this works: xylophone.play() instrumentArray[0] = xylophone; // but this does not: instrumentsArray[0].play() } public Orchestra(Drum drum){ // this works: drum.play() instrumentArray[1] = drum; // but this does not: instrumentsArray[1].play() } public void playInstruments(){ // here is where I will iterate through the instrumentsArray, and make all elements inside it: .play() } } My question would be, how can access the instances methods, after they are inserted into the array? Because I can access them before they go into the array.
[ "I would argue that you have mixed up your class' concerns and have caused too much coupling between your classes.\nMain, should be to create all the objects. It would create the Orchestra, Drum, and Xylophone. The Drum and Xylophone instances would then be added to the Orchestra instance directly in the main method.\nThe Drum and Xylophone shouldn't know about the Orchestra class at all.\nThen Main will have access to the playInstruments() method of Orchestra.\nSide Notes\nI would recommend that both Drum and Xylophone implement an interface called Instrument that has one method called play(String note). So then the Orchestra doesn't have to be coupled to specifically Drums and Xylophones, it could just have Instruments and you could add all kinds of Instruments later without every having to edit your base Orchestra class.\nExamples\nPossible new Orchestra class:\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class Orchestra {\n\n private List<Instrument> instruments;\n\n public Orchestra() {\n this.instruments = new ArrayList<>();\n }\n\n public Orchestra(List<Instrument> instruments) {\n this.instruments = instruments;\n }\n\n public void add(Instrument instrument) {\n this.instruments.add(instrument);\n }\n\n public void play() {\n this.instruments.forEach(i -> i.play(\"b flat\"));\n }\n}\n\nInstrument interface:\npublic interface Instrument {\n\n void play(String note);\n}\n\nDrum:\npublic class Drum implements Instrument {\n\n @Override\n public void play(String note) {\n System.out.println(\"Drums: \" + note);\n }\n}\n\nXylophone:\npublic class Xylophone implements Instrument {\n\n @Override\n public void play(String note) {\n System.out.println(\"Xylophone: \" + note);\n }\n}\n\nAnd finally, Main:\npublic class Main {\n\n public static void main(String[] args) {\n\n Orchestra orchestra = new Orchestra();\n orchestra.add(new Drum());\n orchestra.add(new Xylophone());\n orchestra.play();\n }\n}\n\n" ]
[ 1 ]
[]
[]
[ "java", "methods" ]
stackoverflow_0074678669_java_methods.txt
Q: Type array length dynamically with Typescript Is it possible to do type array length based on a number variable? example: func(1); // returns [string] func(2); // returns [string, string] func(5); // returns [string, string, string, string, string] A: You can declare a recursive conditional type StringTuple to create string tuples of a specific length N: type StringTuple<N extends number, T extends string[] = []> = N extends T['length'] ? T : StringTuple<N, [...T, string]> StringTuple constructs the desired string tuple in an accumulating parameter T, to which an extra string is added until its length is equal to N. type Test = StringTuple<3> // type Test = [string, string, string] Given StringToTuple, the signature of func is straightforward: declare const func: <N extends number>(length: N) => StringTuple<N> const t1 = func(1) // const t1: [string] const t2 = func(2) // const t2: [string, string] const t5 = func(5) // const t5: [string, string, string, string, string] TypeScript playground
Type array length dynamically with Typescript
Is it possible to do type array length based on a number variable? example: func(1); // returns [string] func(2); // returns [string, string] func(5); // returns [string, string, string, string, string]
[ "You can declare a recursive conditional type StringTuple to create string tuples of a specific length N:\ntype StringTuple<N extends number, T extends string[] = []> =\n N extends T['length'] ? T : StringTuple<N, [...T, string]>\n\nStringTuple constructs the desired string tuple in an accumulating parameter T, to which an extra string is added until its length is equal to N.\ntype Test = StringTuple<3>\n// type Test = [string, string, string]\n\nGiven StringToTuple, the signature of func is straightforward:\ndeclare const func: <N extends number>(length: N) => StringTuple<N>\n\nconst t1 = func(1)\n// const t1: [string]\n\nconst t2 = func(2)\n// const t2: [string, string]\n\nconst t5 = func(5)\n// const t5: [string, string, string, string, string]\n\nTypeScript playground\n" ]
[ 0 ]
[]
[]
[ "typescript", "typescript_generics" ]
stackoverflow_0074677930_typescript_typescript_generics.txt
Q: How does the C# compiler resolve types before applying a binary operator? I'm working on a typed scripting language backed by C# Expression Trees. I'm stuck on one issue around proper type conversion with binary operators. Here is an example of the behavior I'm trying to mimic: (The conversion rules should be the same C#'s compiler) var value = "someString" + 10; // yields a string var value = 5 + "someString"; // also yields a string, I don't know why var x = 10f + 10; // yields a float var y = 10 + 10f; // also yields a float, I don't know why How does the C# compiler know to call ToString() on the integer in the first line and to convert the integers to floats in both directions when adding with a float? Are these conversion rules hard coded? My compiler basically works like this now for binary operators: Expression Visit(Type tryToConvertTo, ASTNode node) { // details don't matter. If tryToConvertTo is not null // the resulting expression is cast to that type if not already of that type } // very simplified but this is the gist of it Expression VisitBinaryOperator(Operator operator) { Expression lhs = Visit(null, operator.lhs); Expression rhs = Visit(lhs, operator.rhs); // wrong, but mostly works unless we hit one of the example cases or something similar switch(operator.opType) { case OperatorType.Add: { return Expression.Add(lhs, rhs); } // other operators / error handling etc omitted } } I know always accepting the left hand side's type is wrong, but I have no idea what the proper approach to resolving the example expressions might be other than hard coding the rules for primitive types. If anyone can point me in the right direction I'd be very grateful! A: In C#, the behavior of binary operators such as + is determined by the types of the operands. When one of the operands is a string, the + operator is treated as a string concatenation operator, and the other operand is automatically converted to a string before the concatenation is performed. For example, in the expression "someString" + 10, the 10 is automatically converted to a string before the concatenation is performed, so the result is a string. Similarly, in the expression 5 + "someString", the 5 is automatically converted to a string before the concatenation is performed, so the result is also a string. In the case of floating-point numbers, the + operator is treated as a numeric addition operator, and the operands are automatically converted to floating-point numbers if they are not already floating-point numbers. For example, in the expression 10f + 10, the 10 is automatically converted to a floating-point number (specifically, a float) before the addition is performed, so the result is a float. Similarly, in the expression 10 + 10f, the 10 is automatically converted to a floating-point number (a float in this case) before the addition is performed, so the result is also a float. These conversion rules are not hard-coded in the C# compiler. Instead, they are determined by the types of the operands, and the C# language specification defines how the different types should behave with the various binary operators. The binary + operator, when one operand is of type string, performs string concatenation. The other operand must be of a type that can be converted to a string. The binary + operator performs addition when the operands have the type int, uint, long, or ulong, or have a type that is an enum type with an underlying type in the previous set. When the operands have the type float or double, the binary + operator performs floating-point addition. The operands of the binary + operator may be of any floating-point type. You can find the full C# language specification here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/ To mimic this behaviour in your own typed scripting language, you will need to determine the types of the operands in your binary operator expressions, and apply the appropriate conversion rules based on the types of the operands. This may involve defining your own conversion rules for different types, or using built-in conversion functions provided by the .NET framework, such as Convert.ToString() and Convert.ToSingle(). For example, in your VisitBinaryOperator() method, you could determine the types of the operands by examining the Type of the lhs and rhs expressions, and then apply the appropriate conversion rules based on those types.
How does the C# compiler resolve types before applying a binary operator?
I'm working on a typed scripting language backed by C# Expression Trees. I'm stuck on one issue around proper type conversion with binary operators. Here is an example of the behavior I'm trying to mimic: (The conversion rules should be the same C#'s compiler) var value = "someString" + 10; // yields a string var value = 5 + "someString"; // also yields a string, I don't know why var x = 10f + 10; // yields a float var y = 10 + 10f; // also yields a float, I don't know why How does the C# compiler know to call ToString() on the integer in the first line and to convert the integers to floats in both directions when adding with a float? Are these conversion rules hard coded? My compiler basically works like this now for binary operators: Expression Visit(Type tryToConvertTo, ASTNode node) { // details don't matter. If tryToConvertTo is not null // the resulting expression is cast to that type if not already of that type } // very simplified but this is the gist of it Expression VisitBinaryOperator(Operator operator) { Expression lhs = Visit(null, operator.lhs); Expression rhs = Visit(lhs, operator.rhs); // wrong, but mostly works unless we hit one of the example cases or something similar switch(operator.opType) { case OperatorType.Add: { return Expression.Add(lhs, rhs); } // other operators / error handling etc omitted } } I know always accepting the left hand side's type is wrong, but I have no idea what the proper approach to resolving the example expressions might be other than hard coding the rules for primitive types. If anyone can point me in the right direction I'd be very grateful!
[ "In C#, the behavior of binary operators such as + is determined by the types of the operands. When one of the operands is a string, the + operator is treated as a string concatenation operator, and the other operand is automatically converted to a string before the concatenation is performed.\nFor example, in the expression \"someString\" + 10, the 10 is automatically converted to a string before the concatenation is performed, so the result is a string. Similarly, in the expression 5 + \"someString\", the 5 is automatically converted to a string before the concatenation is performed, so the result is also a string.\nIn the case of floating-point numbers, the + operator is treated as a numeric addition operator, and the operands are automatically converted to floating-point numbers if they are not already floating-point numbers. For example, in the expression 10f + 10, the 10 is automatically converted to a floating-point number (specifically, a float) before the addition is performed, so the result is a float. Similarly, in the expression 10 + 10f, the 10 is automatically converted to a floating-point number (a float in this case) before the addition is performed, so the result is also a float.\nThese conversion rules are not hard-coded in the C# compiler. Instead, they are determined by the types of the operands, and the C# language specification defines how the different types should behave with the various binary operators.\n\nThe binary + operator, when one operand is of type string, performs\nstring concatenation. The other operand must be of a type that can be\nconverted to a string.\n\n\nThe binary + operator performs addition when the operands have the\ntype int, uint, long, or ulong, or have a type that is an enum type\nwith an underlying type in the previous set. When the operands have\nthe type float or double, the binary + operator performs\nfloating-point addition. The operands of the binary + operator may be\nof any floating-point type.\n\nYou can find the full C# language specification here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/\nTo mimic this behaviour in your own typed scripting language, you will need to determine the types of the operands in your binary operator expressions, and apply the appropriate conversion rules based on the types of the operands. This may involve defining your own conversion rules for different types, or using built-in conversion functions provided by the .NET framework, such as Convert.ToString() and Convert.ToSingle().\nFor example, in your VisitBinaryOperator() method, you could determine the types of the operands by examining the Type of the lhs and rhs expressions, and then apply the appropriate conversion rules based on those types.\n" ]
[ 0 ]
[]
[]
[ "c#", "compiler_construction", "expression_trees", "roslyn" ]
stackoverflow_0074671309_c#_compiler_construction_expression_trees_roslyn.txt
Q: JS- Merge multi demensional array object to array object I have data as below: [ { propertyId: '3257', amenityId: '98' } ], [ { propertyId: '3258', amenityId: '98' } ], [ { propertyId: '3259', amenityId: '98' } ], [ { propertyId: '3260', amenityId: '98' } ], [ { propertyId: '3261', amenityId: '98' } ], [ { propertyId: '3262', amenityId: '98' } ], [ { propertyId: '3263', amenityId: '98' } ], [ { propertyId: '3264', amenityId: '98' } ], [ { propertyId: '3265', amenityId: '98' } ], [ { propertyId: '3266', amenityId: '98' } ] expect: [ { propertyId: '3257', amenityId: '98' }, { propertyId: '3258', amenityId: '98' } …...................... ] Thank beforehand. A: If you're targeting a newer version of JS that supports this, you could simply use: const flattenedArray = myMultiDimArray.flat() Otherwise, you could achieve this with a simple reducer: const flattenedArray = myMultiDimArray.reduce((acc, curr) => { acc.push(...curr) return acc; }, [])
JS- Merge multi demensional array object to array object
I have data as below: [ { propertyId: '3257', amenityId: '98' } ], [ { propertyId: '3258', amenityId: '98' } ], [ { propertyId: '3259', amenityId: '98' } ], [ { propertyId: '3260', amenityId: '98' } ], [ { propertyId: '3261', amenityId: '98' } ], [ { propertyId: '3262', amenityId: '98' } ], [ { propertyId: '3263', amenityId: '98' } ], [ { propertyId: '3264', amenityId: '98' } ], [ { propertyId: '3265', amenityId: '98' } ], [ { propertyId: '3266', amenityId: '98' } ] expect: [ { propertyId: '3257', amenityId: '98' }, { propertyId: '3258', amenityId: '98' } …...................... ] Thank beforehand.
[ "If you're targeting a newer version of JS that supports this, you could simply use:\nconst flattenedArray = myMultiDimArray.flat()\n\nOtherwise, you could achieve this with a simple reducer:\nconst flattenedArray = myMultiDimArray.reduce((acc, curr) => {\n acc.push(...curr)\n return acc;\n}, [])\n\n" ]
[ 0 ]
[]
[]
[ "javascript", "lodash" ]
stackoverflow_0074678603_javascript_lodash.txt
Q: How to change string on every iteration in ncurses widow? I need to make programm which take value of pressed key and displays on window corresponding string. While user not press key enter, he can press keys arrow again and string will change every time after pressing. I tried to write this, but programm don't work how i exept (When I press key right and then key left, there is piece of previous string). Please, hellp me to solve this problem ` #define _POSIX_C_SOURCE 200201L #include <stdlib.h> #include <curses.h> #include <time.h> int main () { srand(time(NULL)); initscr(); cbreak(); noecho(); // get screen sizes int yMax, xMax; getmaxyx(stdscr, yMax, xMax); //create a new window for input int height = 10; int width = 120; WINDOW * inputwin = newwin(height, width, yMax/2 - 5, (xMax/2 - width/2)); box(inputwin, 0, 0); refresh(); wrefresh(inputwin); // get amount rows echo(); wmove(inputwin, 4, width/2 - 38); wprintw(inputwin, "Press key left to choose beginner level, key right - intermediate, key up - advances."); int amount_rows = 0; keypad(inputwin, TRUE); while (true) { move(6, 50); // move to begining of line clrtoeol(); // clear line move(6, 50); // move back to where you were wrefresh(inputwin); int c = wgetch(inputwin); if (c == KEY_LEFT) { mvwprintw(inputwin, 6, 50, "You chose beginner"); amount_rows = 2; } else if (c == KEY_RIGHT) { mvwprintw(inputwin, 6, 50, "You chose intermediate"); amount_rows = 3; } else if (c == KEY_UP) { mvwprintw(inputwin, 6, 50, "You chose advanced"); amount_rows = 5; } else mvwprintw(inputwin, 6, 50, "INCORRECT INPUT. TRY AGAIN"); wrefresh(inputwin); mvwprintw(inputwin, 7, 47, "Press enter to continue"); int a = wgetch(inputwin); if (a == KEY_ENTER) break; wrefresh(inputwin); } // mvwprintw(inputwin, 7, 47, "Press enter to continue"); // int a = wgetch(inputwin); // // if (a == KEY_ENTER) { // // delwin(inputwin); // // } getch(); endwin(); return EXIT_SUCCESS; } when I press key right, It works normal`There is piece of previous string
How to change string on every iteration in ncurses widow?
I need to make programm which take value of pressed key and displays on window corresponding string. While user not press key enter, he can press keys arrow again and string will change every time after pressing. I tried to write this, but programm don't work how i exept (When I press key right and then key left, there is piece of previous string). Please, hellp me to solve this problem ` #define _POSIX_C_SOURCE 200201L #include <stdlib.h> #include <curses.h> #include <time.h> int main () { srand(time(NULL)); initscr(); cbreak(); noecho(); // get screen sizes int yMax, xMax; getmaxyx(stdscr, yMax, xMax); //create a new window for input int height = 10; int width = 120; WINDOW * inputwin = newwin(height, width, yMax/2 - 5, (xMax/2 - width/2)); box(inputwin, 0, 0); refresh(); wrefresh(inputwin); // get amount rows echo(); wmove(inputwin, 4, width/2 - 38); wprintw(inputwin, "Press key left to choose beginner level, key right - intermediate, key up - advances."); int amount_rows = 0; keypad(inputwin, TRUE); while (true) { move(6, 50); // move to begining of line clrtoeol(); // clear line move(6, 50); // move back to where you were wrefresh(inputwin); int c = wgetch(inputwin); if (c == KEY_LEFT) { mvwprintw(inputwin, 6, 50, "You chose beginner"); amount_rows = 2; } else if (c == KEY_RIGHT) { mvwprintw(inputwin, 6, 50, "You chose intermediate"); amount_rows = 3; } else if (c == KEY_UP) { mvwprintw(inputwin, 6, 50, "You chose advanced"); amount_rows = 5; } else mvwprintw(inputwin, 6, 50, "INCORRECT INPUT. TRY AGAIN"); wrefresh(inputwin); mvwprintw(inputwin, 7, 47, "Press enter to continue"); int a = wgetch(inputwin); if (a == KEY_ENTER) break; wrefresh(inputwin); } // mvwprintw(inputwin, 7, 47, "Press enter to continue"); // int a = wgetch(inputwin); // // if (a == KEY_ENTER) { // // delwin(inputwin); // // } getch(); endwin(); return EXIT_SUCCESS; } when I press key right, It works normal`There is piece of previous string
[]
[]
[ "var key = document.createElement('div');\ndocument.body.appendChild(key);\ndocument.addEventListener('keydown', function(event) {\nif (event.keyCode == 13) {\nkey.innerHTML = 'Enter';\n\n} else if (event.keyCode == 37) {\nkey.innerHTML = 'Left';\n\n} else if (event.keyCode == 38) {\nkey.innerHTML = 'Up';\n\n} else if (event.keyCode == 39) {\nkey.innerHTML = 'Right';\n\n} else if (event.keyCode == 40) {\nkey.innerHTML = 'Down';\n\n}\n});\n" ]
[ -1 ]
[ "c", "ncurses" ]
stackoverflow_0074678708_c_ncurses.txt
Q: Spurious wake-up and safety property In mutual exclusion, we should satisfy the safety and progress properties. However, if we have a spurious wake-ups, is the safety property still satisfied? A: If your system has lock semantics that allow for spurious wakeups, then the programmer has to handle them accordingly. At each wakeup, check whether it was real or spurious. This information could be returned by the wait function, or the program could just check whether the desired event has occurred (e.g. do we hold the mutex we were waiting on). If yes, it's safe to enter the critical section. If no, then go back to sleep, or maybe do some other work. So pseudo-code to protect a critical section could look like: Mutex m; void do_critical_stuff() { while (true) { m.wait(); if (m.held()) { critical_code(); m.unlock(); return; } else { // No critical code allowed here, but you could do something else. print("You have waked me too soon, I must slumber again."); } } }
Spurious wake-up and safety property
In mutual exclusion, we should satisfy the safety and progress properties. However, if we have a spurious wake-ups, is the safety property still satisfied?
[ "If your system has lock semantics that allow for spurious wakeups, then the programmer has to handle them accordingly. At each wakeup, check whether it was real or spurious. This information could be returned by the wait function, or the program could just check whether the desired event has occurred (e.g. do we hold the mutex we were waiting on). If yes, it's safe to enter the critical section. If no, then go back to sleep, or maybe do some other work.\nSo pseudo-code to protect a critical section could look like:\nMutex m;\n\nvoid do_critical_stuff() {\n while (true) {\n m.wait();\n if (m.held()) {\n critical_code();\n m.unlock();\n return;\n } else {\n // No critical code allowed here, but you could do something else.\n print(\"You have waked me too soon, I must slumber again.\");\n }\n }\n}\n\n" ]
[ 0 ]
[]
[]
[ "concurrency", "multithreading", "mutual_exclusion", "spurious_wakeup", "thread_safety" ]
stackoverflow_0074661930_concurrency_multithreading_mutual_exclusion_spurious_wakeup_thread_safety.txt
Q: Why (True in pd.Series([True,False]) ) return False? I wanted to know, if I have missed values in my Series or DataFrame, but I found, that I can't just use True in series. Why it does't work? I've done it by using series.isna().sum() != 0 , but this problem is interesting for me. mass = [True,False] print(True in mass) #return True mass = pd.Series([True,False]) print(True in mass) #return False mass = pd.DataFrame([True,False]) print(True in mass) #return False A: The in operator in Python checks if a value is present in a list or other sequence. When you use the in operator on a list or array of values, it will return True if the value is present in the list, and False otherwise. However, when you use the in operator on a Pandas Series or DataFrame, it will only return True if the value is present in the index of the Series or DataFrame, not in the values themselves. For example, in your code, the mass variable is a list of values [True, False], so when you use the in operator on this list, it will return True because the value True is present in the list. However, when you convert the list to a Pandas Series or DataFrame, the in operator will only check the index of the Series or DataFrame, which will be a range of integers by default. Since the value True is not present in the index of the Series or DataFrame, the in operator will return False. If you want to check if a value is present in the values of a Pandas Series or DataFrame, you can use the isin method. This method will return a boolean array indicating which values in the Series or DataFrame are equal to the value you are checking for. For example: mass = pd.Series([True, False]) print(mass.isin([True])) # Output: [True, False] In this code, the isin method is used to check if the value True is present in the mass Series. It returns a boolean array indicating that the first value in the Series is True and the second value is False. You can also use the notnull method to check if any values in a Pandas Series or DataFrame are missing. This method will return a boolean array indicating which values are not missing (i.e. not None or NaN). For example: mass = pd.Series([True, None]) print(mass.notnull()) # Output: [True, False] In this code, the notnull method is used to check if any values in the mass Series are missing. It returns a boolean array indicating that the first value in the Series is not missing, but the second value is missing. In summary, the in operator will not work as expected when used on Pandas Series or DataFrames, because it only checks the index of the Series or DataFrame, not the values. To check if a value is present in the values of a Series or DataFrame, you can use the isin method. To check if any values are missing in a Series or DataFrame, you can use the notnull method.
Why (True in pd.Series([True,False]) ) return False?
I wanted to know, if I have missed values in my Series or DataFrame, but I found, that I can't just use True in series. Why it does't work? I've done it by using series.isna().sum() != 0 , but this problem is interesting for me. mass = [True,False] print(True in mass) #return True mass = pd.Series([True,False]) print(True in mass) #return False mass = pd.DataFrame([True,False]) print(True in mass) #return False
[ "The in operator in Python checks if a value is present in a list or other sequence. When you use the in operator on a list or array of values, it will return True if the value is present in the list, and False otherwise. However, when you use the in operator on a Pandas Series or DataFrame, it will only return True if the value is present in the index of the Series or DataFrame, not in the values themselves.\nFor example, in your code, the mass variable is a list of values [True, False], so when you use the in operator on this list, it will return True because the value True is present in the list. However, when you convert the list to a Pandas Series or DataFrame, the in operator will only check the index of the Series or DataFrame, which will be a range of integers by default. Since the value True is not present in the index of the Series or DataFrame, the in operator will return False.\nIf you want to check if a value is present in the values of a Pandas Series or DataFrame, you can use the isin method. This method will return a boolean array indicating which values in the Series or DataFrame are equal to the value you are checking for. For example:\nmass = pd.Series([True, False])\nprint(mass.isin([True])) # Output: [True, False]\n\nIn this code, the isin method is used to check if the value True is present in the mass Series. It returns a boolean array indicating that the first value in the Series is True and the second value is False.\nYou can also use the notnull method to check if any values in a Pandas Series or DataFrame are missing. This method will return a boolean array indicating which values are not missing (i.e. not None or NaN). For example:\nmass = pd.Series([True, None])\nprint(mass.notnull()) # Output: [True, False]\n\nIn this code, the notnull method is used to check if any values in the mass Series are missing. It returns a boolean array indicating that the first value in the Series is not missing, but the second value is missing.\nIn summary, the in operator will not work as expected when used on Pandas Series or DataFrames, because it only checks the index of the Series or DataFrame, not the values. To check if a value is present in the values of a Series or DataFrame, you can use the isin method. To check if any values are missing in a Series or DataFrame, you can use the notnull method.\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python_3.x", "series" ]
stackoverflow_0074678338_dataframe_pandas_python_3.x_series.txt
Q: VS Code code terminal loading freezes on me when I run 'npm start' When I put npm start, it freezes in the loading section, attached pic:loading image frozen link For me to write in the VS code terminal, I will need to trash or kill terminal and start another one. [i have a macos] I tried closing out the application, did not work. I reopened VS Code and it still didn't work. I installed all the necessary dependencies and the my code starts fine when I 'npm start' it, it is just the process of terminal loading that is acting up. A: Try clearing the terminal cache by running the 'clear', if not working then try running the npm start command with the --no-deps flag. If the issue still persists, try reinstalling VS Code and all of your dependencies to see if that fixes the issue. A: what's the command specified in the package.json? at the line like the one bellow. replace <COMMAND_WRITTEN_IN_HERE> with yours. "scripts": { "start": "<COMMAND_WRITTEN_IN_HERE>" },
VS Code code terminal loading freezes on me when I run 'npm start'
When I put npm start, it freezes in the loading section, attached pic:loading image frozen link For me to write in the VS code terminal, I will need to trash or kill terminal and start another one. [i have a macos] I tried closing out the application, did not work. I reopened VS Code and it still didn't work. I installed all the necessary dependencies and the my code starts fine when I 'npm start' it, it is just the process of terminal loading that is acting up.
[ "Try clearing the terminal cache by running the 'clear', if not working then try running the npm start command with the\n\n--no-deps\n\nflag.\nIf the issue still persists, try reinstalling VS Code and all of your dependencies to see if that fixes the issue.\n", "what's the command specified in the package.json? at the line like the one bellow. replace <COMMAND_WRITTEN_IN_HERE> with yours.\n\"scripts\": {\n\"start\": \"<COMMAND_WRITTEN_IN_HERE>\"\n},\n\n" ]
[ 0, 0 ]
[]
[]
[ "javascript", "macos", "visual_studio_code" ]
stackoverflow_0074678720_javascript_macos_visual_studio_code.txt
Q: Tkinter - How to disable button when window opened I'm new to the 'Tkinter' library and I wanted to know how to disable a button when a new window has been opened. For example, if a button on the main window is clicked, a new window will open, and all buttons on the main window will be disabled. After the window is closed, the buttons should be re-enabled again. Here's a sample of my code: from tkinter import * root = Tk() def z(): w = Toplevel() bu = Button(w, text = "Click!", font = 'bold') bu.pack() b = Button(root, text = "Click!", command = z) b.pack() root.mainloop() Extra: I would also be grateful if someone could tell me how to close the 'root' window without closing the whole 'Tkinter' program. For example, if a secondary window is open, I would like to be able to close the first window, or at least minimize it. A: You can hide window root.withdraw() # or root.iconify() and show again root.deiconify() To disable button b['state'] = 'disabled' To enable button b['state'] = 'normal' EDIT: as @acw1668 noted in comment it needs win.protocol() to run close_second when user used closing button [X] on title bar import tkinter as tk # PEP8: `import *` is not preferred #--- functions --- def close_second(): win.destroy() b['state'] = 'normal' root.deiconify() def open_second(): global win b['state'] = 'disabled' #root.iconify() root.withdraw() win = tk.Toplevel() win_b = tk.Button(win, text="Close Second", command=close_second) win_b.pack() # run `close_second` when user used closing button [X] on title bar win.protocol("WM_DELETE_WINDOW", close_second) # --- main --- root = tk.Tk() b = tk.Button(root, text="Open Second", command=open_second) b.pack() root.mainloop() A: You can use .grab_set() to disable interacting with the main window. You can close the window when the button is clicked and reopen the last window when the other button is clicked one is closed like so: from tkinter import * root = Tk() def reopen(): root.mainloop() w.withdraw() def z(): w = Toplevel() w.grab_set() bu = Button(w, text = "Click!", font = 'bold', command=reopen) bu.pack() root.withdraw() w.mainloop() b = Button(root, text = "Click!", command = z) b.pack() root.mainloop()
Tkinter - How to disable button when window opened
I'm new to the 'Tkinter' library and I wanted to know how to disable a button when a new window has been opened. For example, if a button on the main window is clicked, a new window will open, and all buttons on the main window will be disabled. After the window is closed, the buttons should be re-enabled again. Here's a sample of my code: from tkinter import * root = Tk() def z(): w = Toplevel() bu = Button(w, text = "Click!", font = 'bold') bu.pack() b = Button(root, text = "Click!", command = z) b.pack() root.mainloop() Extra: I would also be grateful if someone could tell me how to close the 'root' window without closing the whole 'Tkinter' program. For example, if a secondary window is open, I would like to be able to close the first window, or at least minimize it.
[ "You can hide window\nroot.withdraw()\n\n# or \n\nroot.iconify()\n\nand show again\nroot.deiconify()\n\n\nTo disable button \nb['state'] = 'disabled' \n\nTo enable button \nb['state'] = 'normal'\n\n\nEDIT: as @acw1668 noted in comment it needs win.protocol() to run close_second when user used closing button [X] on title bar\nimport tkinter as tk # PEP8: `import *` is not preferred\n\n#--- functions ---\n\ndef close_second():\n win.destroy()\n\n b['state'] = 'normal'\n\n root.deiconify()\n\ndef open_second():\n global win\n\n b['state'] = 'disabled'\n #root.iconify()\n root.withdraw()\n\n win = tk.Toplevel()\n\n win_b = tk.Button(win, text=\"Close Second\", command=close_second)\n win_b.pack()\n\n # run `close_second` when user used closing button [X] on title bar\n win.protocol(\"WM_DELETE_WINDOW\", close_second)\n\n# --- main ---\n\nroot = tk.Tk()\n\nb = tk.Button(root, text=\"Open Second\", command=open_second)\nb.pack()\n\nroot.mainloop()\n\n", "You can use .grab_set() to disable interacting with the main window. You can close the window when the button is clicked and reopen the last window when the other button is clicked one is closed like so:\nfrom tkinter import *\n\nroot = Tk()\n\ndef reopen():\n root.mainloop()\n w.withdraw()\n\ndef z():\n w = Toplevel()\n w.grab_set()\n bu = Button(w, text = \"Click!\", font = 'bold', command=reopen)\n bu.pack()\n root.withdraw()\n w.mainloop()\n\nb = Button(root, text = \"Click!\", command = z)\nb.pack()\n\nroot.mainloop() \n\n" ]
[ 1, 0 ]
[ "Welcome to Tkinter Library.\nI done why you are using that 'w' you can just use root and it work.\nfrom tkinter import *\nroot = Tk()\n\ndef z():\n\n bu = Button(root, text = \"Click!\", font = 'bold')\n bu.pack()\n\nb = Button(root, text = \"Click!\", command = z)\nb.pack()\n\nroot.mainloop()\n\nAsk me if you get any problem in python and tkinter\n" ]
[ -3 ]
[ "python", "python_3.x", "tk_toolkit", "tkinter" ]
stackoverflow_0060470329_python_python_3.x_tk_toolkit_tkinter.txt
Q: conditionalPanel does not show up textinput based on choices made at selectizeInput | R Shiny I am trying to create a few textInput-fields based on the choices of my selectizeInput. So if the user selects somename22, the UI should add a new textInput. Same for somename33 The MRE: ui <- fluidPage( fluidRow( column(12, selectizeInput( inputId = "select_id", label = NULL, multiple = TRUE, width = "100%", choices = list( "Select value ..." = "", "somename22", "somename33" ) )) ), fluidRow( conditionalPanel( condition = "input.select_id != null && input.select_id.indexOf('22') > -1", column(4, textInput("textid_1", NULL) ) ), conditionalPanel( condition = "input.select_id != null && input.select_id.indexOf('33') > -1", column(4, textInput("textid_2", NULL) ) ) ) ) server <- function(input, output, session) { } shinyApp(ui, server) btw in the real app the choices-names in selectize are a little bit more complex because of Katex, so I need to use some kind of partial matching like indexOf. Any hints, maybe? :) A: The issue is that your choices are called somename22 and somename33 while in the ´conditionalPanelyour are looking for22and33. Fixing that will solve your issue and your textInput`s will show up: library(shiny) ui <- fluidPage( fluidRow( column( 12, selectizeInput( inputId = "select_id", label = NULL, multiple = TRUE, width = "100%", choices = list( "Select value ..." = "", "somename22", "somename33" ) ) ) ), fluidRow( conditionalPanel( condition = "input.select_id != null && input.select_id.indexOf('somename22') > -1", column( 4, textInput("textid_1", NULL) ) ), conditionalPanel( condition = "input.select_id != null && input.select_id.indexOf('somename33') > -1", column( 4, textInput("textid_2", NULL) ) ) ) ) server <- function(input, output, session) { } shinyApp(ui, server)
conditionalPanel does not show up textinput based on choices made at selectizeInput | R Shiny
I am trying to create a few textInput-fields based on the choices of my selectizeInput. So if the user selects somename22, the UI should add a new textInput. Same for somename33 The MRE: ui <- fluidPage( fluidRow( column(12, selectizeInput( inputId = "select_id", label = NULL, multiple = TRUE, width = "100%", choices = list( "Select value ..." = "", "somename22", "somename33" ) )) ), fluidRow( conditionalPanel( condition = "input.select_id != null && input.select_id.indexOf('22') > -1", column(4, textInput("textid_1", NULL) ) ), conditionalPanel( condition = "input.select_id != null && input.select_id.indexOf('33') > -1", column(4, textInput("textid_2", NULL) ) ) ) ) server <- function(input, output, session) { } shinyApp(ui, server) btw in the real app the choices-names in selectize are a little bit more complex because of Katex, so I need to use some kind of partial matching like indexOf. Any hints, maybe? :)
[ "The issue is that your choices are called somename22 and somename33 while in the ´conditionalPanelyour are looking for22and33. Fixing that will solve your issue and your textInput`s will show up:\nlibrary(shiny)\n\nui <- fluidPage(\n fluidRow(\n column(\n 12,\n selectizeInput(\n inputId = \"select_id\", label = NULL, multiple = TRUE,\n width = \"100%\",\n choices =\n list(\n \"Select value ...\" = \"\",\n \"somename22\",\n \"somename33\"\n )\n )\n )\n ),\n fluidRow(\n conditionalPanel(\n condition = \"input.select_id != null && input.select_id.indexOf('somename22') > -1\",\n column(\n 4,\n textInput(\"textid_1\", NULL)\n )\n ),\n conditionalPanel(\n condition = \"input.select_id != null && input.select_id.indexOf('somename33') > -1\",\n column(\n 4,\n textInput(\"textid_2\", NULL)\n )\n )\n )\n)\nserver <- function(input, output, session) {\n}\nshinyApp(ui, server)\n\n\n" ]
[ 0 ]
[]
[]
[ "javascript", "r", "shiny" ]
stackoverflow_0074677565_javascript_r_shiny.txt
Q: FlutterFire iOS Google Sign In not working, Platform Exception I've been very successful in not getting iOS Google Sign In to work. No problem with Android. I got iOS and Android to work once together but I don't know how. I've failed five times after that, starting from scratch. I'm able to click the Sign in with Google button and the modal appears, but there's nothing in the modal. Not sure how that happens. Then when I cancel the modal the app crashes. I was following this video Here is the blank modal: Here is the PlatformException: Here is what I've done: Ran flutterfire configure Selected android, ios, web applied Firebase configuration for Android, yes Created a new Firebase project In Firebase Console Downloaded GoogleService-Info.plist Didn't do Steps 3 or 4 in SDK Instructions since the one time I got it to work I didn't do those steps, and every video I've watched skips them (though I did try two times doing them, but to no avail) In Xcode chose add files to "Runner", and added GoogleService-Info.plist that was downloaded from Firebase In ios/Runner/Info.plist Following the google_sign_in package, I added this code right before the last tag, and change the ID as stated, which I got from the GoogleService-Info.plist <!-- Put me in the [my_project]/ios/Runner/Info.plist file --> <!-- Google Sign-in Section --> <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleTypeRole</key> <string>Editor</string> <key>CFBundleURLSchemes</key> <array> <!-- TODO Replace this value: --> <!-- Copied from GoogleService-Info.plist key REVERSED_CLIENT_ID --> <string>com.googleusercontent.apps.85...</string> </array> </dict> </array> <!-- End of the Google Sign-in Section --> In main() added: then changed the clientId, which I got from the GoogleService-Info.plist WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); runApp(const MyApp()); FlutterFireUIAuth.configureProviders([ // iOS const GoogleProviderConfiguration( clientId: '85... .apps.googleusercontent.com', ), ]); import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:iosfire/auth_gate.dart'; import 'firebase_options.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const AuthGate()); } } UPDATE: This exception happens when the user cancels the modal. I'm not too concerned about this because it would probably not be an issue if the login worked correctly. A: There are a few things you could consider doing Check the bundle id in info. Plist and Google services plist file. If they are different then there's a problem in configuration Delete the application from your device and rebuild again Make sure that your flutter channel is stable Don't use the latest xcode. You can probably try 13.2 or 13.3 Delete Pods folder, Podfile.lock and. Symlinks folder and pod install and try again A: In my case the problem is caused by CFBundleURLTypes which is duplicate from the deep linking. I resolved by merge the custom scheme and domain. please refer to my code below: <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleTypeRole</key> <string>Editor</string> <key>CFBundleURLSchemes</key> <array> <!-- TODO Replace this value: --> <!-- Copied from GoogleService-Info.plist key REVERSED_CLIENT_ID --> <string>com.googleusercontent.apps.105469875803-qwerty</string> <string>customscheme</string> </array> <key>CFBundleURLName</key> <string>patp.com</string> </dict> </array>
FlutterFire iOS Google Sign In not working, Platform Exception
I've been very successful in not getting iOS Google Sign In to work. No problem with Android. I got iOS and Android to work once together but I don't know how. I've failed five times after that, starting from scratch. I'm able to click the Sign in with Google button and the modal appears, but there's nothing in the modal. Not sure how that happens. Then when I cancel the modal the app crashes. I was following this video Here is the blank modal: Here is the PlatformException: Here is what I've done: Ran flutterfire configure Selected android, ios, web applied Firebase configuration for Android, yes Created a new Firebase project In Firebase Console Downloaded GoogleService-Info.plist Didn't do Steps 3 or 4 in SDK Instructions since the one time I got it to work I didn't do those steps, and every video I've watched skips them (though I did try two times doing them, but to no avail) In Xcode chose add files to "Runner", and added GoogleService-Info.plist that was downloaded from Firebase In ios/Runner/Info.plist Following the google_sign_in package, I added this code right before the last tag, and change the ID as stated, which I got from the GoogleService-Info.plist <!-- Put me in the [my_project]/ios/Runner/Info.plist file --> <!-- Google Sign-in Section --> <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleTypeRole</key> <string>Editor</string> <key>CFBundleURLSchemes</key> <array> <!-- TODO Replace this value: --> <!-- Copied from GoogleService-Info.plist key REVERSED_CLIENT_ID --> <string>com.googleusercontent.apps.85...</string> </array> </dict> </array> <!-- End of the Google Sign-in Section --> In main() added: then changed the clientId, which I got from the GoogleService-Info.plist WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); runApp(const MyApp()); FlutterFireUIAuth.configureProviders([ // iOS const GoogleProviderConfiguration( clientId: '85... .apps.googleusercontent.com', ), ]); import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:iosfire/auth_gate.dart'; import 'firebase_options.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const AuthGate()); } } UPDATE: This exception happens when the user cancels the modal. I'm not too concerned about this because it would probably not be an issue if the login worked correctly.
[ "There are a few things you could consider doing\n\nCheck the bundle id in info. Plist and Google services plist file. If they are different then there's a problem in configuration\nDelete the application from your device and rebuild again\nMake sure that your flutter channel is stable\nDon't use the latest xcode. You can probably try 13.2 or 13.3\nDelete Pods folder, Podfile.lock and. Symlinks folder and pod install and try again\n\n", "In my case the problem is caused by CFBundleURLTypes which is duplicate from the deep linking.\nI resolved by merge the custom scheme and domain.\nplease refer to my code below:\n<key>CFBundleURLTypes</key>\n <array>\n <dict>\n <key>CFBundleTypeRole</key>\n <string>Editor</string>\n <key>CFBundleURLSchemes</key>\n <array>\n <!-- TODO Replace this value: -->\n <!-- Copied from GoogleService-Info.plist key REVERSED_CLIENT_ID -->\n <string>com.googleusercontent.apps.105469875803-qwerty</string>\n <string>customscheme</string>\n </array>\n <key>CFBundleURLName</key>\n <string>patp.com</string>\n </dict>\n </array>\n\n" ]
[ 0, 0 ]
[]
[]
[ "firebase_authentication", "firebaseui", "flutter", "flutter_ios", "google_signin" ]
stackoverflow_0073073901_firebase_authentication_firebaseui_flutter_flutter_ios_google_signin.txt
Q: can access url by navigating website but not if entering direct url - Netlify I have deployed a react app to Netlify and if I navigate via the navbar I can access everything and it all works fine. If I however type something like https://example.com/contact I get a not found error. I am using react-router-dom for navigation. Is there something I have to do on the Netlify side or React to fix this? page not found - Looks like you've followed a broken link or entered a URL that doesn't exist on this site. A: Its because your react app is a SPA (Single page application) so you just have a one HTML document so when you type /contact will not find your HTML called "contact" so you need to redirect your app to your HTML page, here is a tutorial that you can follow up link: https://www.freecodecamp.org/news/how-to-deploy-a-react-application-to-netlify-363b8a98a985/ A: To fix this issue create a rewrite rule in the build folder. create a new file with the file name: _redirects with no file extension. add /* /index.html 200 rebuild and publish your file
can access url by navigating website but not if entering direct url - Netlify
I have deployed a react app to Netlify and if I navigate via the navbar I can access everything and it all works fine. If I however type something like https://example.com/contact I get a not found error. I am using react-router-dom for navigation. Is there something I have to do on the Netlify side or React to fix this? page not found - Looks like you've followed a broken link or entered a URL that doesn't exist on this site.
[ "Its because your react app is a SPA (Single page application) so you just have a one HTML document so when you type /contact will not find your HTML called \"contact\" so you need to redirect your app to your HTML page, here is a tutorial that you can follow up\nlink: https://www.freecodecamp.org/news/how-to-deploy-a-react-application-to-netlify-363b8a98a985/\n", "To fix this issue create a rewrite rule in the build folder.\n\ncreate a new file with the file name: _redirects with no file extension.\nadd /* /index.html 200\nrebuild and publish your file\n\n" ]
[ 2, 0 ]
[]
[]
[ "netlify", "reactjs" ]
stackoverflow_0062852371_netlify_reactjs.txt
Q: How to animate object color changing with Manim? I want to animate Dot object to periodically change its color. Something like this: I've only found AnimatedBoundary class but it changes only the object's boundary (as the name says ofc). Is there any way to achieve that with already existing tools? A: Maybe something like this could work for you class ColoredDot(Scene): def construct(self): tracker = ValueTracker(0) def update_color(obj): T=tracker.get_value() rgbcolor=[1,1-T,0+T] m_color=rgb_to_color(rgbcolor) upd_dot=Dot(color=m_color) obj.become(upd_dot) dot=Dot() dot.add_updater(update_color) self.add(dot) self.play(tracker.set_value,1,run_time=5) self.wait() where the specific color choice is given by the line rgbcolor=[1,1-T,0+T] and the parameter T ranges from 0 to 1. This gives you values for rgb colors that depend on that parameter T. You can change this to any function of T you like to give you whatever color change you need. If you want a periodic change, use something like np.sin(T) and change the ranges of T to (0,2*pi), and I would also set the rate_func to linear at that point. A: This is an approximation/improvement upon @NickGreefpool's answer above, to more closely resemble the question's source animation. The inner label is added to better see where the Circle is on the path. class ColoredDot(Scene): def construct(self): tracker = ValueTracker(0) def update_color(obj): T = tracker.get_value() rgbcolor = [1, 1 - T, 0 + T] m_color = rgb_to_color(rgbcolor) upd_dot = Dot(color=m_color, radius=0.5) upd_dot.shift(2*DOWN) obj.become(upd_dot) dot = Dot() dot.add_updater(update_color) self.add(dot) tracker_label = DecimalNumber( tracker.get_value(), color=WHITE, num_decimal_places=8, show_ellipsis=True ) tracker_label.add_updater( lambda mob: mob.set_value(tracker.get_value()) ) self.add(tracker_label) self.play( Rotate(dot, -360*DEGREES, about_point=ORIGIN, rate_func=rate_functions.smooth), tracker.animate.set_value(1) run_time=4 ) self.wait()
How to animate object color changing with Manim?
I want to animate Dot object to periodically change its color. Something like this: I've only found AnimatedBoundary class but it changes only the object's boundary (as the name says ofc). Is there any way to achieve that with already existing tools?
[ "Maybe something like this could work for you\nclass ColoredDot(Scene):\n def construct(self):\n \n tracker = ValueTracker(0)\n \n def update_color(obj):\n T=tracker.get_value()\n rgbcolor=[1,1-T,0+T]\n m_color=rgb_to_color(rgbcolor)\n upd_dot=Dot(color=m_color)\n obj.become(upd_dot)\n \n dot=Dot()\n dot.add_updater(update_color)\n self.add(dot)\n \n self.play(tracker.set_value,1,run_time=5)\n self.wait()\n\nwhere the specific color choice is given by the line\nrgbcolor=[1,1-T,0+T]\n\nand the parameter T ranges from 0 to 1.\nThis gives you values for rgb colors that depend on that parameter T.\nYou can change this to any function of T you like to give you whatever color change you need. If you want a periodic change, use something like np.sin(T) and change the ranges of T to (0,2*pi), and I would also set the rate_func to linear at that point.\n", "\nThis is an approximation/improvement upon @NickGreefpool's answer above, to more closely resemble the question's source animation.\nThe inner label is added to better see where the Circle is on the path.\nclass ColoredDot(Scene):\n def construct(self):\n\n tracker = ValueTracker(0)\n\n def update_color(obj):\n T = tracker.get_value()\n rgbcolor = [1, 1 - T, 0 + T]\n m_color = rgb_to_color(rgbcolor)\n upd_dot = Dot(color=m_color, radius=0.5)\n upd_dot.shift(2*DOWN)\n obj.become(upd_dot)\n\n dot = Dot()\n dot.add_updater(update_color)\n\n self.add(dot)\n\n tracker_label = DecimalNumber(\n tracker.get_value(),\n color=WHITE,\n num_decimal_places=8,\n show_ellipsis=True\n )\n tracker_label.add_updater(\n lambda mob: mob.set_value(tracker.get_value())\n )\n self.add(tracker_label)\n\n\n self.play(\n Rotate(dot, -360*DEGREES,\n about_point=ORIGIN,\n rate_func=rate_functions.smooth),\n tracker.animate.set_value(1)\n run_time=4\n )\n self.wait()\n\n" ]
[ 2, 0 ]
[]
[]
[ "colors", "manim", "python" ]
stackoverflow_0067693569_colors_manim_python.txt
Q: How to assign a "null" value from another column? I would like to create a new column called "season_new", where I want to maintain the non-null season and extract the season for null values from the programme name. My dataframe is something like this: programme season grey's anatomy s1 null friends season 1 1 grey's anatomy s2 null big bang theory s2 2 big bang theory 1 peaky blinders 1 I'd try using regex. dt['season_new'] = dt['programme'].str.extract(r'(season\s?\d+|s\s?\d+)') But it gave me this result: programme season season_new grey's anatomy s1 null 1 friends season 1 1 1 grey's anatomy s2 null 2 big bang theory s2 2 2 big bang theory 1 null peaky blinders 1 null The result that I expected is: programme season season_new grey's anatomy s1 null 1 friends season 1 1 1 grey's anatomy s2 null 2 big bang theory s2 2 2 big bang theory 1 1 peaky blinders 1 1 A: When trying your code, for some reason the regex didn't return only the integers: 0 grey's anatomy s1 NaN s1 1 friends season 1 1.0 season 1 2 grey's anatomy s2 NaN s2 3 big bang theory s2 2.0 s2 4 big bang theory 1.0 NaN 5 peaky blinders 1.0 NaN I am not so great at regex so looked into another option which is below. df = pd.read_excel(source_file) # Empty list for data capture season_data = [] # Loop thought all rows for idx in df.index: # Grab value to check check_val = df["season"][idx] # If value is not null then keep it if pd.notnull(check_val): # Add value to list season_data.append(int(check_val)) else: # Extract digits from programme description extract_result = "".join(i for i in df["programme"][idx] if i.isdigit()) # Add value to list season_data.append(extract_result) # Add full list to dataframe df["season_new"] = season_data print(df) Result is: programme season season_new 0 grey's anatomy s1 NaN 1 1 friends season 1 1.0 1 2 grey's anatomy s2 NaN 2 3 big bang theory s2 2.0 2 4 big bang theory 1.0 1 5 peaky blinders 1.0 1 A: I think that the easiest way to do this is using the apply() method. I also used Regex I first tried this, using a piece of your code: data['season_new'] = data.apply(lambda x: x.season if pd.notna(x.season) else re.search(r'(season\s?\d+|s\s?\d+)',x.programme).group(1), axis=1) The output was this: programme season season_new 0 grey's anatomy s1 NaN s1 1 friends season 1 1.0 1.0 2 grey's anatomy s2 NaN s2 3 big bang theory s2 2.0 2.0 4 big bang theory 1.0 1.0 5 peaky blinders 1.0 1.0 As we can see the column season_new is not a 100% correct. So i tried in another way: data['season_new'] = data.apply(lambda x: x.season if pd.notna(x.season) else (x.programme[-1] if x.programme[-1].isdigit() else np.nan), axis=1).astype('int') The expected output: programme season season_new 0 grey's anatomy s1 NaN 1 1 friends season 1 1.0 1 2 grey's anatomy s2 NaN 2 3 big bang theory s2 2.0 2 4 big bang theory 1.0 1 5 peaky blinders 1.0 1
How to assign a "null" value from another column?
I would like to create a new column called "season_new", where I want to maintain the non-null season and extract the season for null values from the programme name. My dataframe is something like this: programme season grey's anatomy s1 null friends season 1 1 grey's anatomy s2 null big bang theory s2 2 big bang theory 1 peaky blinders 1 I'd try using regex. dt['season_new'] = dt['programme'].str.extract(r'(season\s?\d+|s\s?\d+)') But it gave me this result: programme season season_new grey's anatomy s1 null 1 friends season 1 1 1 grey's anatomy s2 null 2 big bang theory s2 2 2 big bang theory 1 null peaky blinders 1 null The result that I expected is: programme season season_new grey's anatomy s1 null 1 friends season 1 1 1 grey's anatomy s2 null 2 big bang theory s2 2 2 big bang theory 1 1 peaky blinders 1 1
[ "When trying your code, for some reason the regex didn't return only the integers:\n0 grey's anatomy s1 NaN s1\n1 friends season 1 1.0 season 1\n2 grey's anatomy s2 NaN s2\n3 big bang theory s2 2.0 s2\n4 big bang theory 1.0 NaN\n5 peaky blinders 1.0 NaN\n\nI am not so great at regex so looked into another option which is below.\ndf = pd.read_excel(source_file)\n\n# Empty list for data capture\nseason_data = []\n\n# Loop thought all rows\nfor idx in df.index:\n\n # Grab value to check\n check_val = df[\"season\"][idx]\n\n # If value is not null then keep it\n if pd.notnull(check_val):\n\n # Add value to list\n season_data.append(int(check_val))\n\n else:\n # Extract digits from programme description\n extract_result = \"\".join(i for i in df[\"programme\"][idx] if i.isdigit())\n\n # Add value to list\n season_data.append(extract_result)\n\n# Add full list to dataframe\ndf[\"season_new\"] = season_data\n\nprint(df)\n\nResult is:\n programme season season_new\n0 grey's anatomy s1 NaN 1\n1 friends season 1 1.0 1\n2 grey's anatomy s2 NaN 2\n3 big bang theory s2 2.0 2\n4 big bang theory 1.0 1\n5 peaky blinders 1.0 1\n\n", "I think that the easiest way to do this is using the apply() method. I also used Regex\nI first tried this, using a piece of your code:\ndata['season_new'] = data.apply(lambda x: x.season if pd.notna(x.season) else re.search(r'(season\\s?\\d+|s\\s?\\d+)',x.programme).group(1), axis=1)\n\nThe output was this:\n programme season season_new\n0 grey's anatomy s1 NaN s1\n1 friends season 1 1.0 1.0\n2 grey's anatomy s2 NaN s2\n3 big bang theory s2 2.0 2.0\n4 big bang theory 1.0 1.0\n5 peaky blinders 1.0 1.0\n\nAs we can see the column season_new is not a 100% correct. So i tried in another way:\ndata['season_new'] = data.apply(lambda x: x.season if pd.notna(x.season) else (x.programme[-1] if x.programme[-1].isdigit() else np.nan), axis=1).astype('int')\n\nThe expected output:\n programme season season_new\n0 grey's anatomy s1 NaN 1\n1 friends season 1 1.0 1\n2 grey's anatomy s2 NaN 2\n3 big bang theory s2 2.0 2\n4 big bang theory 1.0 1\n5 peaky blinders 1.0 1\n\n" ]
[ 0, 0 ]
[ "You can use pandas.Series.fillna since this one accepts Series as a value.\n\nvalue: scalar, dict, Series, or DataFrame\n\nTry this :\ndt['season_new'] = (\n dt['programme']\n .str.extract(r'[season\\s?|s](\\d+)', expand=False)\n .fillna(dt['season'])\n .astype(int)\n )\n\nIf you want to remove the old season, use pandas.Series.pop :\ndt['season_new'] = (\n dt['programme']\n .str.extract(r'[season\\s?|s](\\d+)', expand=False)\n .fillna(dt.pop('season'))\n .astype(int)\n )\n\n# Output :\nprint(dt)\n\n programme season_new\n0 grey's anatomy s1 1\n1 friends season 1 1\n2 grey's anatomy s2 2\n3 big bang theory s2 2\n4 big bang theory 1\n5 peaky blinders 1\n \n\n", "use following code:\npat = r'[season|s]\\s?(\\d+$)'\ndf.assign(season_new=df['season'].fillna(df['programme'].str.extract(pat)[0]))\n\nresult:\nprogramme season season_new\ngrey's anatomy s1 NaN 1\nfriends season 1 1 1\ngrey's anatomy s2 NaN 2\nbig bang theory s2 2 2\nbig bang theory 1 1\npeaky blinders 1 1\n\n" ]
[ -1, -1 ]
[ "pandas", "python", "regex" ]
stackoverflow_0074677738_pandas_python_regex.txt
Q: How to access a struct tag from inside a field-type in golang I want to know if and how it is possible to access a struct tag set from a custom type used inside this struct. type Out struct { C Custom `format:"asd"` } type Custom struct { } func (c Custom) GetTag() string { // somehow get access to `format:"asd"` } My goal is to be able to define a timeformat for un/marshaling and handle the actual time-unmarshalling parameterized by the structtag. Thanks A: That's not possible. Tags belong to struct fields, not types. So type C has no way of knowing what tag was used. Also, how would it work if: type A struct { C Custom `tag1` } type B struct { C Custom `tag2` } A: Since the question has reflection tagged, to go that route you'd need to pass in the Out-type in some fashion to your un/marshalling methods e.g. var o *Out // nil-pointer so we don't waste any space c := Custom{} // bs is of type []byte{} err := MyUnmarshalerWithReflect(bs, &c, o) So maybe this is an XY problem and it's more intuitive to Unmarshal directly with the desired time-format e.g. err := MyUnmarshalerWithTimeFormat(bs, &c, "2006-01-02") A: You can do this with reflection. type Out struct { C Custom `format:"asd"` } type Custom struct { } func (c Custom) GetTag() string { t := reflect.TypeOf(Out{}) f, ok := t.FieldByName("C") if !ok { return "" } return f.Tag.Get("format") }
How to access a struct tag from inside a field-type in golang
I want to know if and how it is possible to access a struct tag set from a custom type used inside this struct. type Out struct { C Custom `format:"asd"` } type Custom struct { } func (c Custom) GetTag() string { // somehow get access to `format:"asd"` } My goal is to be able to define a timeformat for un/marshaling and handle the actual time-unmarshalling parameterized by the structtag. Thanks
[ "That's not possible. Tags belong to struct fields, not types. So type C has no way of knowing what tag was used. Also, how would it work if:\ntype A struct {\n C Custom `tag1`\n}\ntype B struct {\n C Custom `tag2`\n}\n\n", "Since the question has reflection tagged, to go that route you'd need to pass in the Out-type in some fashion to your un/marshalling methods e.g.\nvar o *Out // nil-pointer so we don't waste any space\n\nc := Custom{}\n\n// bs is of type []byte{}\n\nerr := MyUnmarshalerWithReflect(bs, &c, o)\n\nSo maybe this is an XY problem and it's more intuitive to Unmarshal directly with the desired time-format e.g.\nerr := MyUnmarshalerWithTimeFormat(bs, &c, \"2006-01-02\")\n\n", "You can do this with reflection.\ntype Out struct {\n C Custom `format:\"asd\"`\n}\n\ntype Custom struct {\n}\n\nfunc (c Custom) GetTag() string {\n t := reflect.TypeOf(Out{})\n\n f, ok := t.FieldByName(\"C\")\n if !ok {\n return \"\"\n }\n\n return f.Tag.Get(\"format\")\n}\n\n" ]
[ 1, 0, 0 ]
[]
[]
[ "go", "reflection", "tags", "time" ]
stackoverflow_0057895092_go_reflection_tags_time.txt
Q: The changes you requested to the table were not successful because they would create duplicate values So I have a database with two tables. There is a primary key in both tables, AccountID which has a relationship.Image1 Image2Image3 DonationsTable HOAFeesTable(All the entries on the HOAFees table are just test entries, the data entered aren't important) I have a form that adds records to the HOAFees table. The code on the form is designed to find if an AccountID exists in the table already and if it does it edits the record. If the ID is not on the table already, it should add the record. ` Option Compare Database Private Sub btnAddRecord_Click() 'Declare variables Dim db As DAO.Database Dim rst As Recordset Dim intID As Integer 'Set the current database Set db = Application.CurrentDb 'Set the recordset Set rst = db.OpenRecordset("tblHOAFees", dbOpenDynaset) 'Set value for variable intID = lstAccountID.Value 'Finds the Account ID selected on the form With rst rst.FindFirst "AccountID=" & intID 'If the record has not yet been added to the form adds a new record If .NoMatch Then rst.AddNew rst!AccountID = intID rst!HOAID = txtHOAID.Value rst!Location = txtLocation.Value rst!House = chkHouse.Value rst!Rooms = txtRooms.Value rst!SquareFeet = txtSquareFeet.Value rst!HOAFees = txtHOAFees.Value rst.Update 'If the Account ID is already in the form edits the record Else rst.Edit rst!AccountID = intID rst!HOAID = txtHOAID.Value rst!Location = txtLocation.Value rst!House = chkHouse.Value rst!Rooms = txtRooms.Value rst!SquareFeet = txtSquareFeet.Value rst!HOAFees = txtHOAFees.Value rst.Update End If End With 'Closes the recordset rst.Close Set rst = Nothing Set db = Nothing End Sub ` It works without any issues when editing an existing record. But when I add a new record and then try to close the form I get this: ErrorImage The strange thing is though, when I click through all the errors and check the table. The new record is still added to the table despite it saying it can't save. How can I get this to stop coming up? Everything I keep finding is saying that an autonumber field is causing the error. But I don't have any auto number fields. I've tried removing primary key from the HOAFees table, but it makes no difference. I need the primary key for the Donations table, so I can't change or have any duplicates on that. A: If you don't have a problem with the error itself, and everything works fine, you just don't want the error message to appear, add code in the OnError event of the form, which checks if it's the error number you want to ignore. Private Sub Form_Error(DataErr As Integer, Response As Integer) Const ErrNumber = your_err_number If DataErr = ErrNumber Then Response = acDataErrContinue End If End Sub
The changes you requested to the table were not successful because they would create duplicate values
So I have a database with two tables. There is a primary key in both tables, AccountID which has a relationship.Image1 Image2Image3 DonationsTable HOAFeesTable(All the entries on the HOAFees table are just test entries, the data entered aren't important) I have a form that adds records to the HOAFees table. The code on the form is designed to find if an AccountID exists in the table already and if it does it edits the record. If the ID is not on the table already, it should add the record. ` Option Compare Database Private Sub btnAddRecord_Click() 'Declare variables Dim db As DAO.Database Dim rst As Recordset Dim intID As Integer 'Set the current database Set db = Application.CurrentDb 'Set the recordset Set rst = db.OpenRecordset("tblHOAFees", dbOpenDynaset) 'Set value for variable intID = lstAccountID.Value 'Finds the Account ID selected on the form With rst rst.FindFirst "AccountID=" & intID 'If the record has not yet been added to the form adds a new record If .NoMatch Then rst.AddNew rst!AccountID = intID rst!HOAID = txtHOAID.Value rst!Location = txtLocation.Value rst!House = chkHouse.Value rst!Rooms = txtRooms.Value rst!SquareFeet = txtSquareFeet.Value rst!HOAFees = txtHOAFees.Value rst.Update 'If the Account ID is already in the form edits the record Else rst.Edit rst!AccountID = intID rst!HOAID = txtHOAID.Value rst!Location = txtLocation.Value rst!House = chkHouse.Value rst!Rooms = txtRooms.Value rst!SquareFeet = txtSquareFeet.Value rst!HOAFees = txtHOAFees.Value rst.Update End If End With 'Closes the recordset rst.Close Set rst = Nothing Set db = Nothing End Sub ` It works without any issues when editing an existing record. But when I add a new record and then try to close the form I get this: ErrorImage The strange thing is though, when I click through all the errors and check the table. The new record is still added to the table despite it saying it can't save. How can I get this to stop coming up? Everything I keep finding is saying that an autonumber field is causing the error. But I don't have any auto number fields. I've tried removing primary key from the HOAFees table, but it makes no difference. I need the primary key for the Donations table, so I can't change or have any duplicates on that.
[ "If you don't have a problem with the error itself, and everything works fine, you just don't want the error message to appear, add code in the OnError event of the form, which checks if it's the error number you want to ignore.\nPrivate Sub Form_Error(DataErr As Integer, Response As Integer)\n Const ErrNumber = your_err_number\n If DataErr = ErrNumber Then\n Response = acDataErrContinue\n End If\nEnd Sub\n\n" ]
[ 0 ]
[]
[]
[ "ms_access", "vba" ]
stackoverflow_0074672843_ms_access_vba.txt
Q: TypeError: Cannot read properties of undefined (reading 'after') at card.js:20:13 card.js export class Cards { constructor(domain, topic, limit) { this.domain = domain; this.after = ''; this.topic = topic; this.limit = limit; } addCards(parentElement) { let url = `https://www.${this.domain}.com/r/${this.topic}.json?after=${this.after}&limit=${this.limit}`; fetch(url).then(function(response) { return response.json(); }) .then(function(data) { this.after = data.data.after; let children = data.data.children; children.map(function(val) { let div = document.createElement('div'); div.setAttribute('class', 'card'); let img = document.createElement('img'); img.setAttribute('width', '200'); img.src = val.data.url; div.appendChild(img); parentElement.appendChild(div); }) }) .catch(function(error) { console.log(error) }); } } main.js import { Cards } from "./card.js"; // `<div>` Element that contains all cards. const container = document.querySelector('.container'); // Creating all cards with class Cards. let memeCards = new Cards('reddit', 'memes', 50); // Binding Cards to Container. memeCards.addCards(container); I’m trying to fetch new images each time I click on a button. That’s the reason why I’ve created the property this.after, but for some reason I get the error “TypeError: Cannot read properties of undefined (reading 'after') at card.js:20:13”.
TypeError: Cannot read properties of undefined (reading 'after') at card.js:20:13
card.js export class Cards { constructor(domain, topic, limit) { this.domain = domain; this.after = ''; this.topic = topic; this.limit = limit; } addCards(parentElement) { let url = `https://www.${this.domain}.com/r/${this.topic}.json?after=${this.after}&limit=${this.limit}`; fetch(url).then(function(response) { return response.json(); }) .then(function(data) { this.after = data.data.after; let children = data.data.children; children.map(function(val) { let div = document.createElement('div'); div.setAttribute('class', 'card'); let img = document.createElement('img'); img.setAttribute('width', '200'); img.src = val.data.url; div.appendChild(img); parentElement.appendChild(div); }) }) .catch(function(error) { console.log(error) }); } } main.js import { Cards } from "./card.js"; // `<div>` Element that contains all cards. const container = document.querySelector('.container'); // Creating all cards with class Cards. let memeCards = new Cards('reddit', 'memes', 50); // Binding Cards to Container. memeCards.addCards(container); I’m trying to fetch new images each time I click on a button. That’s the reason why I’ve created the property this.after, but for some reason I get the error “TypeError: Cannot read properties of undefined (reading 'after') at card.js:20:13”.
[]
[]
[ "It looks like you're trying to access the after property of the Cards object in the addCards method, but it hasn't been defined yet. You can fix this error by setting a default value for the after property in the Cards class constructor, like this:\nexport class Cards {\n constructor(domain, topic, limit){\n this.domain = domain;\n this.after = ''; // default value for after property\n this.topic = topic;\n this.limit = limit;\n }\n\n addCards(parentElement){\n // ... rest of the code here\n }\n}\n\nThis way, when you create a new Cards object, the after property will be automatically initialized to an empty string, and you won't get the \"Cannot read properties of undefined\" error when trying to access it.\n" ]
[ -1 ]
[ "javascript" ]
stackoverflow_0074678666_javascript.txt
Q: how to apply Slack app_home_opened event in Python Flask Slack App I am currently working on Slack Event API to show the Home tab in the existed Slack App. So, I am struggling to implement app_home_opened from the Slack Event API to the app. The app is developed by Python Flask. And when I tried to show home tab in the dummy app which is not using flask, it was succeed. But I want to implement in Python Flask. Here is the code I was succeed in my dummy app. import os from slack_bolt import App from slack_bolt.adapter.socket_mode import SocketModeHandler ... app = App(token=os.environ.get("SLACK_BOT_TOKEN")) ... @app.event("app_home_opened") def update_home_tab(client, event, logger): try: client.views_publish( user_id=event["user"], view={ "type": "home", "callback_id": "home_view", "blocks": [ ... ] } ) except Exception as e: logger.error(f"Error publishing home tab: {e}") ... if __name__ == "__main__": SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start() And I want to apply the code above to the code something like below to show the home tab. from slack_bolt.adapter.flask import SlackRequestHandler from flask import Flask ... app = Flask(__name__) ... @app.route('/', methods=['GET']) def main(): ... @app.route('/', methods=['POST']) def slack_events(): ... ... if __name__ == '__main__': app.run(host='...', port=..., debug=True) A: Something like this should work. import os from slack_bolt import App ... app = App(token=os.environ.get("SLACK_BOT_TOKEN")) ... @app.event("app_home_opened") def update_home_tab(client, event, logger): try: client.views_publish( user_id=event["user"], view={ "type": "home", "callback_id": "home_view", "blocks": [ ... ] } ) except Exception as e: logger.error(f"Error publishing home tab: {e}") ... from flask import Flask, request from slack_bolt.adapter.flask import SlackRequestHandler flask_app = Flask(__name__) handler = SlackRequestHandler(app) # endpoint for handling all slack events @flask_app.route("/slack/events", methods=["POST"]) def slack_events(): return handler.handle(request) # run flask app if __name__ == "__main__": flask_app.run(debug=True,host="0.0.0.0", port=8080) Reference - https://github.com/slackapi/bolt-python/blob/main/examples/flask/app.py
how to apply Slack app_home_opened event in Python Flask Slack App
I am currently working on Slack Event API to show the Home tab in the existed Slack App. So, I am struggling to implement app_home_opened from the Slack Event API to the app. The app is developed by Python Flask. And when I tried to show home tab in the dummy app which is not using flask, it was succeed. But I want to implement in Python Flask. Here is the code I was succeed in my dummy app. import os from slack_bolt import App from slack_bolt.adapter.socket_mode import SocketModeHandler ... app = App(token=os.environ.get("SLACK_BOT_TOKEN")) ... @app.event("app_home_opened") def update_home_tab(client, event, logger): try: client.views_publish( user_id=event["user"], view={ "type": "home", "callback_id": "home_view", "blocks": [ ... ] } ) except Exception as e: logger.error(f"Error publishing home tab: {e}") ... if __name__ == "__main__": SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start() And I want to apply the code above to the code something like below to show the home tab. from slack_bolt.adapter.flask import SlackRequestHandler from flask import Flask ... app = Flask(__name__) ... @app.route('/', methods=['GET']) def main(): ... @app.route('/', methods=['POST']) def slack_events(): ... ... if __name__ == '__main__': app.run(host='...', port=..., debug=True)
[ "Something like this should work.\nimport os\nfrom slack_bolt import App\n\n...\n\napp = App(token=os.environ.get(\"SLACK_BOT_TOKEN\"))\n\n...\n\n@app.event(\"app_home_opened\")\ndef update_home_tab(client, event, logger):\n try:\n client.views_publish(\n user_id=event[\"user\"],\n view={\n \"type\": \"home\",\n \"callback_id\": \"home_view\",\n \"blocks\": [\n\n ...\n\n ]\n }\n )\n \n except Exception as e:\n logger.error(f\"Error publishing home tab: {e}\")\n\n...\n\nfrom flask import Flask, request\nfrom slack_bolt.adapter.flask import SlackRequestHandler\n\nflask_app = Flask(__name__)\nhandler = SlackRequestHandler(app)\n\n# endpoint for handling all slack events\n@flask_app.route(\"/slack/events\", methods=[\"POST\"])\ndef slack_events():\n return handler.handle(request)\n\n# run flask app\nif __name__ == \"__main__\":\n flask_app.run(debug=True,host=\"0.0.0.0\", port=8080)\n\nReference - https://github.com/slackapi/bolt-python/blob/main/examples/flask/app.py\n" ]
[ 0 ]
[]
[]
[ "flask", "python", "slack", "slack_api", "slack_block_kit" ]
stackoverflow_0073482118_flask_python_slack_slack_api_slack_block_kit.txt
Q: How to check is Jenkins Job workspace is in use Let's say I have 2 jobs JobA JobB JobA and JobB use the same workspace. I don't want JobA to run when JobB is running through checking if the workspace is in use. How can a check if a given Jenkins workspace is in use by a Job? FYI - this is just a simple scenario. There are more complex scenarios to handle which is why I need it to work this way. Expected Result: Let's say Workspace is "c:\workspace" JobB is running in "c:\workspace". JobA is attempts to start, JobA checks and sees workspace is in use. Pipeline aborts. (or even better if possible, the pipeline waits for JobB to finish and then runs) A: The ideal solution is to use Lockable Resource Plugin, which allows you to acquire locks on resources and wait until they are released to perform certain pipeline operations. First, create a lock called workspaceLock, and the following are two sample pipelines, which utilize the lock. JobA pipeline { agent any parameters { string(name: 'foo', defaultValue: '', description: '') } options { lock ('workspaceLock') } stages { stage("StageA") { steps { echo "Do Something in JObA" } } } } } JobB pipeline { agent any parameters { string(name: 'foo', defaultValue: '', description: '') } options { lock ('workspaceLock') } stages { stage("StageB") { steps { echo "Do Something in JObB" } } } } }
How to check is Jenkins Job workspace is in use
Let's say I have 2 jobs JobA JobB JobA and JobB use the same workspace. I don't want JobA to run when JobB is running through checking if the workspace is in use. How can a check if a given Jenkins workspace is in use by a Job? FYI - this is just a simple scenario. There are more complex scenarios to handle which is why I need it to work this way. Expected Result: Let's say Workspace is "c:\workspace" JobB is running in "c:\workspace". JobA is attempts to start, JobA checks and sees workspace is in use. Pipeline aborts. (or even better if possible, the pipeline waits for JobB to finish and then runs)
[ "The ideal solution is to use Lockable Resource Plugin, which allows you to acquire locks on resources and wait until they are released to perform certain pipeline operations.\nFirst, create a lock called workspaceLock, and the following are two sample pipelines, which utilize the lock.\nJobA\npipeline {\n agent any\n parameters { string(name: 'foo', defaultValue: '', description: '') }\n options {\n lock ('workspaceLock')\n }\n stages {\n stage(\"StageA\") {\n steps {\n echo \"Do Something in JObA\" \n }\n }\n\n }\n }\n}\n\nJobB\npipeline {\n agent any\n parameters { string(name: 'foo', defaultValue: '', description: '') }\n options {\n lock ('workspaceLock')\n }\n stages {\n stage(\"StageB\") {\n steps {\n echo \"Do Something in JObB\" \n }\n }\n\n }\n }\n}\n\n" ]
[ 0 ]
[]
[]
[ "continuous_integration", "jenkins", "jenkins_pipeline", "jenkins_plugins" ]
stackoverflow_0074658501_continuous_integration_jenkins_jenkins_pipeline_jenkins_plugins.txt
Q: Extension methods must be defined in a non-generic static class I'm getting the error: Extension methods must be defined in a non-generic static class On the line: public class LinqHelper Here is the helper class, based on Mark Gavells code. I'm really confused as to what this error means as I am sure it was working fine when I left it on Friday! using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Linq.Expressions; using System.Reflection; /// <summary> /// Helper methods for link /// </summary> public class LinqHelper { public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderBy"); } public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderByDescending"); } public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "ThenBy"); } public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "ThenByDescending"); } static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName) { string[] props = property.Split('.'); Type type = typeof(T); ParameterExpression arg = Expression.Parameter(type, "x"); Expression expr = arg; foreach (string prop in props) { // use reflection (not ComponentModel) to mirror LINQ PropertyInfo pi = type.GetProperty(prop); expr = Expression.Property(expr, pi); type = pi.PropertyType; } Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type); LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg); object result = typeof(Queryable).GetMethods().Single( method => method.Name == methodName && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 2 && method.GetParameters().Length == 2) .MakeGenericMethod(typeof(T), type) .Invoke(null, new object[] { source, lambda }); return (IOrderedQueryable<T>)result; } } A: change public class LinqHelper to public static class LinqHelper Following points need to be considered when creating an extension method: The class which defines an extension method must be non-generic, static and non-nested Every extension method must be a static method The first parameter of the extension method should use the this keyword. A: if you do not intend to have static functions just get rid of the "this" keyword in the arguments. A: Add keyword static to class declaration: // this is a non-generic static class public static class LinqHelper { } A: Try changing public class LinqHelper to public static class LinqHelper A: A work-around for people who are experiencing a bug like Nathan: The on-the-fly compiler seems to have a problem with this Extension Method error... adding static didn't help me either. I'd like to know what causes the bug? But the work-around is to write a new Extension class (not nested) even in same file and re-build. Figured that this thread is getting enough views that it's worth passing on (the limited) solution I found. Most people probably tried adding 'static' before google-ing for a solution! and I didn't see this work-around fix anywhere else. A: Change it to public static class LinqHelper A: I was scratching my head with this compiler error. My class was not an extension method, was working perfectly since months and needed to stay non-static. I had included a new method inside the class: private static string TrimNL(this string Value) {...} I had copied the method from a sample and didn't notice the "this" modifier in the method signature, which is used in extension methods. Removing it solved the issue. A: I ran into this when converting a project to use dependency injection. If a method declaration contains the “this” keyword, VS will give the warning. In my case, I was able to remove “this” from all of the method declarations. If using “this” is required, you will have to make it static. public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property) changed to public static IOrderedQueryable<T> OrderBy<T>(IQueryable<T> source, string property) You might need to code around not using the “this” keyword for the method declaration if you want to avoid using a static class with static methods. If “this” is only required for some methods, those methods can be moved to a separate public static class. A: Extension method should be inside a static class. So please add your extension method inside a static class. so for example it should be like this public static class myclass { public static Byte[] ToByteArray(this Stream stream) { Int32 length = stream.Length > Int32.MaxValue ? Int32.MaxValue : Convert.ToInt32(stream.Length); Byte[] buffer = new Byte[length]; stream.Read(buffer, 0, length); return buffer; } } A: Try changing it to static class and back. That might resolve visual studio complaining when it's a false positive. A: I encountered a similar issue, I created a 'foo' folder and created a "class" inside foo, then I get the aforementioned error. One fix is to add "static" as earlier mentioned to the class which will be "public static class LinqHelper". My assumption is that when you create a class inside the foo folder it regards it as an extension class, hence the following inter alia rule apply to it: 1) Every extension method must be a static method WORKAROUND If you don't want static. My workaround was to create a class directly under the namespace and then drag it to the "foo" folder.
Extension methods must be defined in a non-generic static class
I'm getting the error: Extension methods must be defined in a non-generic static class On the line: public class LinqHelper Here is the helper class, based on Mark Gavells code. I'm really confused as to what this error means as I am sure it was working fine when I left it on Friday! using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Linq.Expressions; using System.Reflection; /// <summary> /// Helper methods for link /// </summary> public class LinqHelper { public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderBy"); } public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderByDescending"); } public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "ThenBy"); } public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "ThenByDescending"); } static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName) { string[] props = property.Split('.'); Type type = typeof(T); ParameterExpression arg = Expression.Parameter(type, "x"); Expression expr = arg; foreach (string prop in props) { // use reflection (not ComponentModel) to mirror LINQ PropertyInfo pi = type.GetProperty(prop); expr = Expression.Property(expr, pi); type = pi.PropertyType; } Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type); LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg); object result = typeof(Queryable).GetMethods().Single( method => method.Name == methodName && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 2 && method.GetParameters().Length == 2) .MakeGenericMethod(typeof(T), type) .Invoke(null, new object[] { source, lambda }); return (IOrderedQueryable<T>)result; } }
[ "change \npublic class LinqHelper\n\nto \npublic static class LinqHelper\n\nFollowing points need to be considered when creating an extension method:\n\nThe class which defines an extension method must be non-generic, static and non-nested\nEvery extension method must be a static method\nThe first parameter of the extension method should use the this keyword. \n\n", "if you do not intend to have static functions just get rid of the \"this\" keyword in the arguments.\n", "Add keyword static to class declaration:\n// this is a non-generic static class\npublic static class LinqHelper\n{\n}\n\n", "Try changing \npublic class LinqHelper\n\nto\n public static class LinqHelper\n\n", "A work-around for people who are experiencing a bug like Nathan:\nThe on-the-fly compiler seems to have a problem with this Extension Method error... adding static didn't help me either. \nI'd like to know what causes the bug?\nBut the work-around is to write a new Extension class (not nested) even in same file and re-build.\nFigured that this thread is getting enough views that it's worth passing on (the limited) solution I found. Most people probably tried adding 'static' before google-ing for a solution! and I didn't see this work-around fix anywhere else.\n", "Change it to\npublic static class LinqHelper\n\n", "I was scratching my head with this compiler error. My class was not an extension method, was working perfectly since months and needed to stay non-static. I had included a new method inside the class:\nprivate static string TrimNL(this string Value)\n{...}\n\nI had copied the method from a sample and didn't notice the \"this\" modifier in the method signature, which is used in extension methods. Removing it solved the issue.\n", "I ran into this when converting a project to use dependency injection. If a method declaration contains the “this” keyword, VS will give the warning. In my case, I was able to remove “this” from all of the method declarations. If using “this” is required, you will have to make it static.\n public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)\n\nchanged to\n public static IOrderedQueryable<T> OrderBy<T>(IQueryable<T> source, string property)\n\nYou might need to code around not using the “this” keyword for the method declaration if you want to avoid using a static class with static methods. If “this” is only required for some methods, those methods can be moved to a separate public static class.\n", "Extension method should be inside a static class.\nSo please add your extension method inside a static class.\nso for example it should be like this\npublic static class myclass\n {\n public static Byte[] ToByteArray(this Stream stream)\n {\n Int32 length = stream.Length > Int32.MaxValue ? Int32.MaxValue : Convert.ToInt32(stream.Length);\n Byte[] buffer = new Byte[length];\n stream.Read(buffer, 0, length);\n return buffer;\n }\n\n }\n\n", "Try changing it to static class and back. That might resolve visual studio complaining when it's a false positive.\n", "I encountered a similar issue, I created a 'foo' folder and created a \"class\" inside foo, then I get the aforementioned error. One fix is to add \"static\" as earlier mentioned to the class which will be \"public static class LinqHelper\". \nMy assumption is that when you create a class inside the foo folder it regards it as an extension class, hence the following inter alia rule apply to it:\n1) Every extension method must be a static method\nWORKAROUND If you don't want static.\nMy workaround was to create a class directly under the namespace and then drag it to the \"foo\" folder.\n" ]
[ 367, 85, 24, 20, 20, 16, 11, 3, 1, 1, 0 ]
[ "If any method in your class has [this] keyword visual studio will think that you are building an extension so remove the [this] keyword from every method in your class and the error will disappear\n" ]
[ -1 ]
[ ".net", "c#", "compiler_errors", "extension_methods", "linq" ]
stackoverflow_0006096299_.net_c#_compiler_errors_extension_methods_linq.txt
Q: Unity2D C# - Player Jumping never works regardless of what i try working on a small platformer for my university assignment, and so far its going well enough, only problem right now is that i can never get jumping to work. Either the player physically cant jump, or can jump as much as he likes even midair. All i want him to do is jump when touching the ground, but not when in air. And as easy as that would seem... IT REFUSES TO WORK. i use code i find online, nope. i use 2022 tutorials on player jumping scripts, nope. no matter what, he refuses to do this simple task and im so close to pulling my hair out sobs I posted my code on the unity forum and all i got was "thats messy". no actual solution to the problem. Has anyone got some basic jumping code i can learn from? everything i can find is just outdated or broken... This is the original code: using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { private float horizontal; private float speed = 5f; private float jumpingPower = 15f; private bool isFacingRight = true; [SerializeField] private Rigidbody2D rb; [SerializeField] private Transform groundCheck; [SerializeField] private LayerMask groundLayer; void Update() //determining if player is grounded for the jumping mechanic { horizontal = Input.GetAxisRaw("Horizontal"); if (Input.GetButtonDown("Jump") && IsGrounded()) { rb.velocity = new Vector2(rb.velocity.x, jumpingPower); } //determining jump velocity if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f) { rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f); } //Controlling the jumping mechanic //Adding force vertically if (Input.GetKeyDown(KeyCode.Space)) { rb.AddForce(Vector3.up * jumpingPower, ForceMode2D.Impulse); } Flip(); } private void FixedUpdate() { rb.velocity = new Vector2(horizontal * speed, rb.velocity.y); } private bool IsGrounded() { return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer); } //Flip mechanic private void Flip() { if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f) { isFacingRight = !isFacingRight; Vector3 localScale = transform.localScale; localScale.x *= -1f; transform.localScale = localScale; } } Wanted him to single jump, either wouldnt jump or jumped constantly in air. A: This piece of code making your player jump any time, when player presses space button without any ground check. Probably add ground check or just remove it, cuz you are already have jump logic above if (Input.GetKeyDown(KeyCode.Space)) { rb.AddForce(Vector3.up * jumpingPower, ForceMode2D.Impulse); }
Unity2D C# - Player Jumping never works regardless of what i try
working on a small platformer for my university assignment, and so far its going well enough, only problem right now is that i can never get jumping to work. Either the player physically cant jump, or can jump as much as he likes even midair. All i want him to do is jump when touching the ground, but not when in air. And as easy as that would seem... IT REFUSES TO WORK. i use code i find online, nope. i use 2022 tutorials on player jumping scripts, nope. no matter what, he refuses to do this simple task and im so close to pulling my hair out sobs I posted my code on the unity forum and all i got was "thats messy". no actual solution to the problem. Has anyone got some basic jumping code i can learn from? everything i can find is just outdated or broken... This is the original code: using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { private float horizontal; private float speed = 5f; private float jumpingPower = 15f; private bool isFacingRight = true; [SerializeField] private Rigidbody2D rb; [SerializeField] private Transform groundCheck; [SerializeField] private LayerMask groundLayer; void Update() //determining if player is grounded for the jumping mechanic { horizontal = Input.GetAxisRaw("Horizontal"); if (Input.GetButtonDown("Jump") && IsGrounded()) { rb.velocity = new Vector2(rb.velocity.x, jumpingPower); } //determining jump velocity if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f) { rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f); } //Controlling the jumping mechanic //Adding force vertically if (Input.GetKeyDown(KeyCode.Space)) { rb.AddForce(Vector3.up * jumpingPower, ForceMode2D.Impulse); } Flip(); } private void FixedUpdate() { rb.velocity = new Vector2(horizontal * speed, rb.velocity.y); } private bool IsGrounded() { return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer); } //Flip mechanic private void Flip() { if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f) { isFacingRight = !isFacingRight; Vector3 localScale = transform.localScale; localScale.x *= -1f; transform.localScale = localScale; } } Wanted him to single jump, either wouldnt jump or jumped constantly in air.
[ "This piece of code making your player jump any time, when player presses space button without any ground check. Probably add ground check or just remove it, cuz you are already have jump logic above\nif (Input.GetKeyDown(KeyCode.Space))\n{\n rb.AddForce(Vector3.up * jumpingPower, ForceMode2D.Impulse);\n}\n\n" ]
[ 0 ]
[]
[]
[ "unity3d" ]
stackoverflow_0074673746_unity3d.txt
Q: Executing the file loops infinitely but the assembler did not report any errors .MODEL SMALL .STACK 100H .DATA ARRAY DB 1,9,8,3,4,7 .CODE MAIN PROC MOV AX,@DATA MOV DS,AX MOV SI,OFFSET ARRAY MOV CX,6 MOV BL, [SI] LOOPX: CMP [SI], BL JGE UPDATE RESUME: INC SI LOOP LOOPX ADD BL,51 MOV DL,BL MOV AH,2 UPDATE: MOV BL,[SI] JMP RESUME MAIN ENDP END MAIN I want to read the largest number in the array. A: The program is incomplete With MOV DL,BL MOV AH,2 you have setup for using the DOS.PrintCharacter function 02h, but you forgot to actually invoke it. Just add int 21h. You forgot to end the program! You have allowed the code to fall-through into UPDATE where a jump to RESUME will create an infinite loop. Use the DOS.Terminate function 4Ch. The program has an error/typo To convert the single digit number into a printable character you need to add 48, so ADD BL,51 is wrong. The program is not optimal The first array element gets compared to itself and triggers a redundant reload of BL. In your array with 6 elements, this code needs 5 comparisons to arrive at the result. Because you want to output the result through the DL register, it would be better to use DL from the start. Unless you program for the 8086, it would be better to replace loop ... by dec cx jnz ... MOV SI, OFFSET ARRAY MOV CX, 6 - 1 ; 5 comparisons MOV DL, [SI] ; First element LOOPX: INC SI CMP [SI], DL JLE DONTUPDATE MOV DL, [SI] DONTUPDATE: DEC CX JNZ LOOPX ADD DL, 48 ; You could write this as ADD DL, '0' MOV AH, 02h INT 21h MOV AX, 4C00h INT 21h
Executing the file loops infinitely but the assembler did not report any errors
.MODEL SMALL .STACK 100H .DATA ARRAY DB 1,9,8,3,4,7 .CODE MAIN PROC MOV AX,@DATA MOV DS,AX MOV SI,OFFSET ARRAY MOV CX,6 MOV BL, [SI] LOOPX: CMP [SI], BL JGE UPDATE RESUME: INC SI LOOP LOOPX ADD BL,51 MOV DL,BL MOV AH,2 UPDATE: MOV BL,[SI] JMP RESUME MAIN ENDP END MAIN I want to read the largest number in the array.
[ "The program is incomplete\n\nWith MOV DL,BL MOV AH,2 you have setup for using the DOS.PrintCharacter function 02h, but you forgot to actually invoke it. Just add int 21h.\nYou forgot to end the program! You have allowed the code to fall-through into UPDATE where a jump to RESUME will create an infinite loop. Use the DOS.Terminate function 4Ch.\n\nThe program has an error/typo\nTo convert the single digit number into a printable character you need to add 48, so ADD BL,51 is wrong.\nThe program is not optimal\n\nThe first array element gets compared to itself and triggers a redundant reload of BL. In your array with 6 elements, this code needs 5 comparisons to arrive at the result.\n\nBecause you want to output the result through the DL register, it would be better to use DL from the start.\n\nUnless you program for the 8086, it would be better to replace loop ... by dec cx jnz ...\n MOV SI, OFFSET ARRAY\n MOV CX, 6 - 1 ; 5 comparisons\n MOV DL, [SI] ; First element\n LOOPX:\n INC SI\n CMP [SI], DL\n JLE DONTUPDATE\n MOV DL, [SI]\n DONTUPDATE:\n DEC CX\n JNZ LOOPX\n\n ADD DL, 48 ; You could write this as ADD DL, '0'\n MOV AH, 02h\n INT 21h\n\n MOV AX, 4C00h\n INT 21h\n\n\n\n" ]
[ 1 ]
[]
[]
[ "assembly", "masm", "x86_16" ]
stackoverflow_0074666306_assembly_masm_x86_16.txt
Q: Which is correct way of using MaxConnectionsPerServer in HttpClientHandler? I'm trying to find the correct value for HttpClientHandler.MaxConnectionsPerServer. My services conditions: I use ASP.NET Core 3.1 - 6.0 I have many services on a server. Services responses for many requests per second. Services make requests to other REST services via HttpClient. Usually HttpClient setups via HttpClientFactory in Startup.cs: services .AddHttpClient<IOtherService, OtherService>() .ConfigureHttpClient(httpClient => httpClient.Timeout = TimeSpan.FromSeconds(3)) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { MaxConnectionsPerServer = 10 }); Usually, it works pretty well, but sometimes (in a moment of high load) I get many TaskCanceledException and OtherService continues to respond as fast as it can. I understand that HttpClientHandler reaches the limit of MaxConnectionsPerServer. My questions: Is it the correct way of using MaxConnectionsPerServer? Maybe I should not use MaxConnectionsPerServer anymore? How can I find the correct value for MaxConnectionsPerServer? A: Questions asked by me do not have short answers. The approach described in my question is probably a superficial implementation of the Bulkhead pattern. My answers: Is it the correct way of using MaxConnectionsPerServer? Maybe I should not use MaxConnectionsPerServer anymore? It is the correct way if I want to reduce a load on called service (IOtherService) How can I find the correct value for MaxConnectionsPerServer? I have to collect monitoring data and analyze actual cases if I want to find the correct value for MaxConnectionsPerServer. Also, it can change after changing a load on my service or IOtherService
Which is correct way of using MaxConnectionsPerServer in HttpClientHandler?
I'm trying to find the correct value for HttpClientHandler.MaxConnectionsPerServer. My services conditions: I use ASP.NET Core 3.1 - 6.0 I have many services on a server. Services responses for many requests per second. Services make requests to other REST services via HttpClient. Usually HttpClient setups via HttpClientFactory in Startup.cs: services .AddHttpClient<IOtherService, OtherService>() .ConfigureHttpClient(httpClient => httpClient.Timeout = TimeSpan.FromSeconds(3)) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { MaxConnectionsPerServer = 10 }); Usually, it works pretty well, but sometimes (in a moment of high load) I get many TaskCanceledException and OtherService continues to respond as fast as it can. I understand that HttpClientHandler reaches the limit of MaxConnectionsPerServer. My questions: Is it the correct way of using MaxConnectionsPerServer? Maybe I should not use MaxConnectionsPerServer anymore? How can I find the correct value for MaxConnectionsPerServer?
[ "Questions asked by me do not have short answers. The approach described in my question is probably a superficial implementation of the Bulkhead pattern.\nMy answers:\n\nIs it the correct way of using MaxConnectionsPerServer? Maybe I should not use MaxConnectionsPerServer anymore?\n\nIt is the correct way if I want to reduce a load on called service (IOtherService)\n\nHow can I find the correct value for MaxConnectionsPerServer?\n\nI have to collect monitoring data and analyze actual cases if I want to find the correct value for MaxConnectionsPerServer. Also, it can change after changing a load on my service or IOtherService\n" ]
[ 0 ]
[]
[]
[ ".net", "asp.net_core", "dotnet_httpclient" ]
stackoverflow_0073437747_.net_asp.net_core_dotnet_httpclient.txt
Q: Vue Apply different CSS when pinned = 1 I'm trying to change the stylings for blogposts which are pinned. I have written some code that works A LITTLE (not as intended). So here's the code that works a little bit: HTML: Problem here is that it posts ALL titles in every single post (but the titles of the posts that were pinned, get the styling) <div class="row card-columns"> <div class="card-columns"> <div class="col justify-content-center card text-white bg-dark" v-for="(post, index) in collection" :key="index" :post="post" :index="index"> <div class="row g-0"> <img :src= post.image class="h-100 card-img" alt="Card image cap" style="object-fit: cover;"> <div class="col-sm-20"> <div class="card-body"> <div v-bind:class="{ 'pinned': post.pinned }" v-for="(post, index) in posts" :key="index"> <h3 class="card-title">{{ post.title }}</h3></div> <p class="truncate" onclick="RevealHiddenOverflow(this)" style="text-align: left"> {{ post.fullText }}</p> <div class="btn-group flex-column flex-md-row" role="group" aria-label="btn"> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#readPost" v-on:click="readPost(post, index)">Show</button> <button type="button" class="btn btn-success" data-toggle="modal" data-target="#editPost" v-on:click="editPost(post, index)">Edit</button> <button type="button" class="btn btn-danger" v-on:click="deletePost(post)">Delete</button> </div> </div> <div class="card-footer"> <p class="card-text">{{ post.tags }}</p> </div> </div> </div> </div> </div> </div> JavaScript/Vue new Vue({ el: "#app", data() { return { header: "My BookWriting Tool", post: {}, index: 0, newPost: {}, newComment: [], readingPost: {}, perPage: 9, pagination: {}, pinned: 0, //pinned: null, posts: [] }; }, ... I can say that posts work as follows: posts: [ {"id":4,"title":"4 pinned","pinned":true}, {"id":5,"title":"5","pinned":false}, {"id":3,"image":"https://picsum.photos/350/250?random=3","title":"Third","fullText":"Only truncates when text is longer than 2 lines. :)","pinned":false}, {"id":2,"image":"https://picsum.photos/350/450?random=2","title":"Second","fullText":"Second post, not gonna add much. Second post, not gonna add much. Second post, not gonna add much. Second post, not gonna add much. Second post, not gonna add much. Second post, not gonna add much. ","tags":"second, tag","pinned":false}, {"id":1,"image":"https://picsum.photos/430?random=1","title":"First","fullText":"First one okay. First one okay. First one okay. First one okay. First one okay. First one okay. First one okay. First one okay. ","tags":"first, tag, echo"} ] A: This works :) <div :class="post.pinned ? 'pinned' : 'blue'"> <h3 class="card-title">{{ post.title }}</h3></div> WORKS!
Vue Apply different CSS when pinned = 1
I'm trying to change the stylings for blogposts which are pinned. I have written some code that works A LITTLE (not as intended). So here's the code that works a little bit: HTML: Problem here is that it posts ALL titles in every single post (but the titles of the posts that were pinned, get the styling) <div class="row card-columns"> <div class="card-columns"> <div class="col justify-content-center card text-white bg-dark" v-for="(post, index) in collection" :key="index" :post="post" :index="index"> <div class="row g-0"> <img :src= post.image class="h-100 card-img" alt="Card image cap" style="object-fit: cover;"> <div class="col-sm-20"> <div class="card-body"> <div v-bind:class="{ 'pinned': post.pinned }" v-for="(post, index) in posts" :key="index"> <h3 class="card-title">{{ post.title }}</h3></div> <p class="truncate" onclick="RevealHiddenOverflow(this)" style="text-align: left"> {{ post.fullText }}</p> <div class="btn-group flex-column flex-md-row" role="group" aria-label="btn"> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#readPost" v-on:click="readPost(post, index)">Show</button> <button type="button" class="btn btn-success" data-toggle="modal" data-target="#editPost" v-on:click="editPost(post, index)">Edit</button> <button type="button" class="btn btn-danger" v-on:click="deletePost(post)">Delete</button> </div> </div> <div class="card-footer"> <p class="card-text">{{ post.tags }}</p> </div> </div> </div> </div> </div> </div> JavaScript/Vue new Vue({ el: "#app", data() { return { header: "My BookWriting Tool", post: {}, index: 0, newPost: {}, newComment: [], readingPost: {}, perPage: 9, pagination: {}, pinned: 0, //pinned: null, posts: [] }; }, ... I can say that posts work as follows: posts: [ {"id":4,"title":"4 pinned","pinned":true}, {"id":5,"title":"5","pinned":false}, {"id":3,"image":"https://picsum.photos/350/250?random=3","title":"Third","fullText":"Only truncates when text is longer than 2 lines. :)","pinned":false}, {"id":2,"image":"https://picsum.photos/350/450?random=2","title":"Second","fullText":"Second post, not gonna add much. Second post, not gonna add much. Second post, not gonna add much. Second post, not gonna add much. Second post, not gonna add much. Second post, not gonna add much. ","tags":"second, tag","pinned":false}, {"id":1,"image":"https://picsum.photos/430?random=1","title":"First","fullText":"First one okay. First one okay. First one okay. First one okay. First one okay. First one okay. First one okay. First one okay. ","tags":"first, tag, echo"} ]
[ "This works :)\n<div :class=\"post.pinned ? 'pinned' : 'blue'\">\n<h3 class=\"card-title\">{{ post.title }}</h3></div>\n\nWORKS!\n" ]
[ 1 ]
[]
[]
[ "css", "javascript", "vue.js" ]
stackoverflow_0074670013_css_javascript_vue.js.txt
Q: Method that reads user input until user types "q" public static String input(){ Scanner input = new Scanner(System.in); String key = ""; while(key != "q"){ key += input.nextLine(); return key; } return "hello"; } //if input is "1234" then it should return key = "1234", if the input is "1234q" then it should return "hello" The output im getting is >nothing< until I do it twice, and then it returns key = "1234q" How can I fix this? Thanks
Method that reads user input until user types "q"
public static String input(){ Scanner input = new Scanner(System.in); String key = ""; while(key != "q"){ key += input.nextLine(); return key; } return "hello"; } //if input is "1234" then it should return key = "1234", if the input is "1234q" then it should return "hello" The output im getting is >nothing< until I do it twice, and then it returns key = "1234q" How can I fix this? Thanks
[]
[]
[ " public static String input(){\n\n Scanner input = new Scanner(System.in);\n\n \n String key = input.nextLine();\n char[] keyCharArray = key.toCharArray();\n\n for (int i = 0; i<keyCharArray.length;i++) {\n\n if(keyCharArray[i]=='q') {\n return \"hello\";\n }\n }\n return key;\n \n }\n\nI would use toCharArray to loop through the characters and compare them to q. You can see my solution up there.\n", "Your code isn't finding if the key has q, rather if the key is q itself.\nimport java.util.Scanner;\npublic class Main {\n public static String input(){\n Scanner input = new Scanner(System.in);\n String key = input.nextLine();\n while(!key.contains(\"q\")){\n key += input.nextLine();\n return key;\n }\n return \"hello\";\n }\n public static void main(String[] args) {\n System.out.println(input());\n }\n}\n\n" ]
[ -1, -1 ]
[ "java" ]
stackoverflow_0074678662_java.txt
Q: How to explain calling a C function from an array of function pointers? This example https://godbolt.org/z/EKvvEKa6T calls MyFun() using this syntax (*((int(**)(void))CallMyFun))(); Is there a C breakdown of that obfuscated syntax to explain how it works? #include <stdio.h> int MyFun(void) { printf("Hello, World!"); return 0; } void *funarray[] = { NULL,NULL,&MyFun,NULL,NULL }; int main(void) { size_t CallMyFun = (size_t)&funarray + (2 * sizeof(funarray[0])); return (*((int(**)(void))CallMyFun))(); } A: The behavior of void *funarray[] = { NULL,NULL,&MyFun,NULL,NULL }; is not defined by the C standard because it converts a pointer to a function (MyFun) to a pointer to an object type (void *). Conversions to pointers are specified in C 2018 6.3.2.3, and none of them cover conversions between pointers to object types and pointers to function types except for null pointers. The code size_t CallMyFun = (size_t)&funarray + (2 * sizeof(funarray[0])); sets CallMyFun to the address of element 2 of funarray, provided that conversion of pointers to the integer size_t type works “naturally,” which is not required by the C standard but is intended. In (*((int(**)(void))CallMyFun))();, we have (int(**)(void)) CallMyFun. This says to convert CallMyFun to a pointer to a pointer to a function taking no arguments and returning an int. When using a table of heterogenous function pointers in C, it is necessary to convert between types, because C provides no generic function pointer mechanism, so we cannot fault the author for that. However, this converts not merely to a pointer to a function type but to a pointer to a pointer to a function type, and that is an error. The array contains pointers to void, not pointers to pointers to functions. The C standard does not require these to have the same size or representation. Then the code applies *, intending to retrieve the pointer. This is another error. If if a pointer to void had the same size and representation has a pointer to a pointer to a function, accessing a void * (which is what was stored in the array) as a pointer to a function (which is what retrieving it using this expression does) violates the aliasing rules in C 2018 6.5 7. However, if the C implementation does support this and all the prior conversions and issues, the result is a pointer to the function MyFun, and then applying () calls the function. A proper way to write the code, assuming the array must support heterogenous function types, could be: // Use array of pointers to functions (of a forced type). void (*funarray[])(void) = { NULL, NULL, (void (*)(void)) MyFun, NULL, NULL }; … // Get array element using ordinary subscript notation. void (*CallMyFunc)(void) = funarray[2]; // Convert pointer to function’s actual type, then call it. return ((int (*)(void)) CallMyFunc)(); If the array can be homogenous, then the code should be written: int (*funarray[])(void) = { NULL, NULL, MyFun, NULL, NULL }; … return funarray[2](); A: To understand what's going on here, we should look at each part of the code piece by piece (at least the odd pieces): void *funarray[] = { NULL,NULL,&MyFun,NULL,NULL }; In the above, we are creating an array of pointers initialized to be most "empty" (ie, NULL) but at index 2 we have a pointer to MyFunc. It's helpful to track the types as we go, so at this point, we have &MyFunc of type int (*)(void) (function pointer syntax in C is a bit odd as the * and possible identifier goes in the middle rather than at the end), which is immediately turned into a void * in the array. Why the array is of type void * when it appears to be containing function pointers is a bit odd but let's assume there is a good reason... size_t CallMyFun = (size_t)&funarray + (2 * sizeof(funarray[0])); This code is a rather complex way of accessing the array and getting the second element by converting the head of the array to a size_t then adding the correct number of bytes to get the address of the second entry (a simpler way would be (size_t) &funarray[2]). Here again, we have lost the type information, going from originally a int (*[])(void) to void*[] to size_t. return (*((int(**)(void))CallMyFun))(); Now that we know that CallMyFunc contains a pointer to a function pointer, ie the address of the MyFunc pointer in the array, if we want to call it we need to convert it back to the proper type and dereference it correctly. So, unwrapping the call, we direct have ((int(**)(void))CallMyFun) which casts the improperly typed CallMyFunc from size_t to a double function pointer, ie a pointer to a function pointer, which the syntax for is int (**)(void), just like any other double pointer which needs two * to denote. Next, as is isn't yet a function pointer, we need to dereference it to get the pointer of type int (*)(void), so (*((int(**)(void))CallMyFun)). Finally, we want to actually call the function pointer so the last set of parents. As mentioned in the comments, this code is rather obfuscated by changing types and using unusual ways of accessing arrays; it's usually best to keep types consistent as it lets the compiler help you avoid mistakes and makes the code more readable for yourself and others.
How to explain calling a C function from an array of function pointers?
This example https://godbolt.org/z/EKvvEKa6T calls MyFun() using this syntax (*((int(**)(void))CallMyFun))(); Is there a C breakdown of that obfuscated syntax to explain how it works? #include <stdio.h> int MyFun(void) { printf("Hello, World!"); return 0; } void *funarray[] = { NULL,NULL,&MyFun,NULL,NULL }; int main(void) { size_t CallMyFun = (size_t)&funarray + (2 * sizeof(funarray[0])); return (*((int(**)(void))CallMyFun))(); }
[ "The behavior of void *funarray[] = { NULL,NULL,&MyFun,NULL,NULL }; is not defined by the C standard because it converts a pointer to a function (MyFun) to a pointer to an object type (void *). Conversions to pointers are specified in C 2018 6.3.2.3, and none of them cover conversions between pointers to object types and pointers to function types except for null pointers.\nThe code size_t CallMyFun = (size_t)&funarray + (2 * sizeof(funarray[0])); sets CallMyFun to the address of element 2 of funarray, provided that conversion of pointers to the integer size_t type works “naturally,” which is not required by the C standard but is intended.\nIn (*((int(**)(void))CallMyFun))();, we have (int(**)(void)) CallMyFun. This says to convert CallMyFun to a pointer to a pointer to a function taking no arguments and returning an int. When using a table of heterogenous function pointers in C, it is necessary to convert between types, because C provides no generic function pointer mechanism, so we cannot fault the author for that. However, this converts not merely to a pointer to a function type but to a pointer to a pointer to a function type, and that is an error.\nThe array contains pointers to void, not pointers to pointers to functions. The C standard does not require these to have the same size or representation.\nThen the code applies *, intending to retrieve the pointer. This is another error. If if a pointer to void had the same size and representation has a pointer to a pointer to a function, accessing a void * (which is what was stored in the array) as a pointer to a function (which is what retrieving it using this expression does) violates the aliasing rules in C 2018 6.5 7.\nHowever, if the C implementation does support this and all the prior conversions and issues, the result is a pointer to the function MyFun, and then applying () calls the function.\nA proper way to write the code, assuming the array must support heterogenous function types, could be:\n// Use array of pointers to functions (of a forced type).\nvoid (*funarray[])(void) = { NULL, NULL, (void (*)(void)) MyFun, NULL, NULL };\n\n…\n\n// Get array element using ordinary subscript notation.\nvoid (*CallMyFunc)(void) = funarray[2];\n\n// Convert pointer to function’s actual type, then call it.\nreturn ((int (*)(void)) CallMyFunc)();\n\nIf the array can be homogenous, then the code should be written:\nint (*funarray[])(void) = { NULL, NULL, MyFun, NULL, NULL };\n\n…\n\nreturn funarray[2]();\n\n", "To understand what's going on here, we should look at each part of the code piece by piece (at least the odd pieces):\nvoid *funarray[] = { NULL,NULL,&MyFun,NULL,NULL };\n\nIn the above, we are creating an array of pointers initialized to be most \"empty\" (ie, NULL) but at index 2 we have a pointer to MyFunc. It's helpful to track the types as we go, so at this point, we have &MyFunc of type int (*)(void) (function pointer syntax in C is a bit odd as the * and possible identifier goes in the middle rather than at the end), which is immediately turned into a void * in the array. Why the array is of type void * when it appears to be containing function pointers is a bit odd but let's assume there is a good reason...\nsize_t CallMyFun = (size_t)&funarray + (2 * sizeof(funarray[0]));\n\nThis code is a rather complex way of accessing the array and getting the second element by converting the head of the array to a size_t then adding the correct number of bytes to get the address of the second entry (a simpler way would be (size_t) &funarray[2]). Here again, we have lost the type information, going from originally a int (*[])(void) to void*[] to size_t.\nreturn (*((int(**)(void))CallMyFun))();\n\nNow that we know that CallMyFunc contains a pointer to a function pointer, ie the address of the MyFunc pointer in the array, if we want to call it we need to convert it back to the proper type and dereference it correctly. So, unwrapping the call, we direct have ((int(**)(void))CallMyFun) which casts the improperly typed CallMyFunc from size_t to a double function pointer, ie a pointer to a function pointer, which the syntax for is int (**)(void), just like any other double pointer which needs two * to denote. Next, as is isn't yet a function pointer, we need to dereference it to get the pointer of type int (*)(void), so (*((int(**)(void))CallMyFun)). Finally, we want to actually call the function pointer so the last set of parents.\nAs mentioned in the comments, this code is rather obfuscated by changing types and using unusual ways of accessing arrays; it's usually best to keep types consistent as it lets the compiler help you avoid mistakes and makes the code more readable for yourself and others.\n" ]
[ 4, 1 ]
[ "Array is collection of similar data types in which each element is unique and located in contiguous memory location.\n" ]
[ -2 ]
[ "c" ]
stackoverflow_0074678473_c.txt
Q: NonUniformImage: numpy example gives 'cannot unpack non-iterable NoneType object' error 2D-Histogram I'm trying to run this very simple example from numpy page regarding histogram2d: https://numpy.org/doc/stable/reference/generated/numpy.histogram2d.html. from matplotlib.image import NonUniformImage import matplotlib.pyplot as plt xedges = [0, 1, 3, 5] yedges = [0, 2, 3, 4, 6] x = np.random.normal(2, 1, 100) y = np.random.normal(1, 1, 100) H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges)) H = H.T fig = plt.figure(figsize=(7, 3)) ax = fig.add_subplot(131, title='imshow: square bins') plt.imshow(H, interpolation='nearest', origin='lower',extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]]) ax = fig.add_subplot(132, title='pcolormesh: actual edges',aspect='equal') X, Y = np.meshgrid(xedges, yedges) ax.pcolormesh(X, Y, H) ax = fig.add_subplot(133, title='NonUniformImage: interpolated',aspect='equal', xlim=xedges[[0, -1]], ylim=yedges[[0, -1]]) im = NonUniformImage(ax, interpolation='bilinear') xcenters = (xedges[:-1] + xedges[1:]) / 2 ycenters = (yedges[:-1] + yedges[1:]) / 2 im.set_data(xcenters,ycenters,H) ax.images.append(im) plt.show() By running this code as in the example, I receive the error cannot unpack non-iterable NoneType object This happens as soon as I run the line ax.images.append(im). Does anyone know why this happens? Tried to run an example from numpy website and doesn't work as expected. A: The full error message is: TypeError Traceback (most recent call last) File ~\anaconda3\lib\site-packages\IPython\core\formatters.py:339, in BaseFormatter.__call__(self, obj) 337 pass 338 else: --> 339 return printer(obj) 340 # Finally look for special method names 341 method = get_real_method(obj, self.print_method) File ~\anaconda3\lib\site-packages\IPython\core\pylabtools.py:151, in print_figure(fig, fmt, bbox_inches, base64, **kwargs) 148 from matplotlib.backend_bases import FigureCanvasBase 149 FigureCanvasBase(fig) --> 151 fig.canvas.print_figure(bytes_io, **kw) 152 data = bytes_io.getvalue() 153 if fmt == 'svg': File ~\anaconda3\lib\site-packages\matplotlib\backend_bases.py:2299, in FigureCanvasBase.print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs) 2297 if bbox_inches: 2298 if bbox_inches == "tight": -> 2299 bbox_inches = self.figure.get_tightbbox( 2300 renderer, bbox_extra_artists=bbox_extra_artists) 2301 if pad_inches is None: 2302 pad_inches = rcParams['savefig.pad_inches'] File ~\anaconda3\lib\site-packages\matplotlib\figure.py:1632, in FigureBase.get_tightbbox(self, renderer, bbox_extra_artists) 1629 artists = bbox_extra_artists 1631 for a in artists: -> 1632 bbox = a.get_tightbbox(renderer) 1633 if bbox is not None and (bbox.width != 0 or bbox.height != 0): 1634 bb.append(bbox) File ~\anaconda3\lib\site-packages\matplotlib\axes\_base.py:4666, in _AxesBase.get_tightbbox(self, renderer, call_axes_locator, bbox_extra_artists, for_layout_only) 4662 if np.all(clip_extent.extents == axbbox.extents): 4663 # clip extent is inside the Axes bbox so don't check 4664 # this artist 4665 continue -> 4666 bbox = a.get_tightbbox(renderer) 4667 if (bbox is not None 4668 and 0 < bbox.width < np.inf 4669 and 0 < bbox.height < np.inf): 4670 bb.append(bbox) File ~\anaconda3\lib\site-packages\matplotlib\artist.py:355, in Artist.get_tightbbox(self, renderer) 340 def get_tightbbox(self, renderer): 341 """ 342 Like `.Artist.get_window_extent`, but includes any clipping. 343 (...) 353 The enclosing bounding box (in figure pixel coordinates). 354 """ --> 355 bbox = self.get_window_extent(renderer) 356 if self.get_clip_on(): 357 clip_box = self.get_clip_box() File ~\anaconda3\lib\site-packages\matplotlib\image.py:943, in AxesImage.get_window_extent(self, renderer) 942 def get_window_extent(self, renderer=None): --> 943 x0, x1, y0, y1 = self._extent 944 bbox = Bbox.from_extents([x0, y0, x1, y1]) 945 return bbox.transformed(self.axes.transData) TypeError: cannot unpack non-iterable NoneType object <Figure size 504x216 with 3 Axes> The error occurs deep in the append call, and appears to involve trying to get information about the plot window. If I comment out the append line, and it continues on to the plt.show(), and resulting image looks like the example, except the third image is blank. I tested this in a Windows QtConsole; I don't know if that context posses problems for this append or not. I don't think it's a problem with your code copy.
NonUniformImage: numpy example gives 'cannot unpack non-iterable NoneType object' error 2D-Histogram
I'm trying to run this very simple example from numpy page regarding histogram2d: https://numpy.org/doc/stable/reference/generated/numpy.histogram2d.html. from matplotlib.image import NonUniformImage import matplotlib.pyplot as plt xedges = [0, 1, 3, 5] yedges = [0, 2, 3, 4, 6] x = np.random.normal(2, 1, 100) y = np.random.normal(1, 1, 100) H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges)) H = H.T fig = plt.figure(figsize=(7, 3)) ax = fig.add_subplot(131, title='imshow: square bins') plt.imshow(H, interpolation='nearest', origin='lower',extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]]) ax = fig.add_subplot(132, title='pcolormesh: actual edges',aspect='equal') X, Y = np.meshgrid(xedges, yedges) ax.pcolormesh(X, Y, H) ax = fig.add_subplot(133, title='NonUniformImage: interpolated',aspect='equal', xlim=xedges[[0, -1]], ylim=yedges[[0, -1]]) im = NonUniformImage(ax, interpolation='bilinear') xcenters = (xedges[:-1] + xedges[1:]) / 2 ycenters = (yedges[:-1] + yedges[1:]) / 2 im.set_data(xcenters,ycenters,H) ax.images.append(im) plt.show() By running this code as in the example, I receive the error cannot unpack non-iterable NoneType object This happens as soon as I run the line ax.images.append(im). Does anyone know why this happens? Tried to run an example from numpy website and doesn't work as expected.
[ "The full error message is:\nTypeError Traceback (most recent call last)\nFile ~\\anaconda3\\lib\\site-packages\\IPython\\core\\formatters.py:339, in BaseFormatter.__call__(self, obj)\n 337 pass\n 338 else:\n--> 339 return printer(obj)\n 340 # Finally look for special method names\n 341 method = get_real_method(obj, self.print_method)\n\nFile ~\\anaconda3\\lib\\site-packages\\IPython\\core\\pylabtools.py:151, in print_figure(fig, fmt, bbox_inches, base64, **kwargs)\n 148 from matplotlib.backend_bases import FigureCanvasBase\n 149 FigureCanvasBase(fig)\n--> 151 fig.canvas.print_figure(bytes_io, **kw)\n 152 data = bytes_io.getvalue()\n 153 if fmt == 'svg':\n\nFile ~\\anaconda3\\lib\\site-packages\\matplotlib\\backend_bases.py:2299, in FigureCanvasBase.print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs)\n 2297 if bbox_inches:\n 2298 if bbox_inches == \"tight\":\n-> 2299 bbox_inches = self.figure.get_tightbbox(\n 2300 renderer, bbox_extra_artists=bbox_extra_artists)\n 2301 if pad_inches is None:\n 2302 pad_inches = rcParams['savefig.pad_inches']\n\nFile ~\\anaconda3\\lib\\site-packages\\matplotlib\\figure.py:1632, in FigureBase.get_tightbbox(self, renderer, bbox_extra_artists)\n 1629 artists = bbox_extra_artists\n 1631 for a in artists:\n-> 1632 bbox = a.get_tightbbox(renderer)\n 1633 if bbox is not None and (bbox.width != 0 or bbox.height != 0):\n 1634 bb.append(bbox)\n\nFile ~\\anaconda3\\lib\\site-packages\\matplotlib\\axes\\_base.py:4666, in _AxesBase.get_tightbbox(self, renderer, call_axes_locator, bbox_extra_artists, for_layout_only)\n 4662 if np.all(clip_extent.extents == axbbox.extents):\n 4663 # clip extent is inside the Axes bbox so don't check\n 4664 # this artist\n 4665 continue\n-> 4666 bbox = a.get_tightbbox(renderer)\n 4667 if (bbox is not None\n 4668 and 0 < bbox.width < np.inf\n 4669 and 0 < bbox.height < np.inf):\n 4670 bb.append(bbox)\n\nFile ~\\anaconda3\\lib\\site-packages\\matplotlib\\artist.py:355, in Artist.get_tightbbox(self, renderer)\n 340 def get_tightbbox(self, renderer):\n 341 \"\"\"\n 342 Like `.Artist.get_window_extent`, but includes any clipping.\n 343 \n (...)\n 353 The enclosing bounding box (in figure pixel coordinates).\n 354 \"\"\"\n--> 355 bbox = self.get_window_extent(renderer)\n 356 if self.get_clip_on():\n 357 clip_box = self.get_clip_box()\n\nFile ~\\anaconda3\\lib\\site-packages\\matplotlib\\image.py:943, in AxesImage.get_window_extent(self, renderer)\n 942 def get_window_extent(self, renderer=None):\n--> 943 x0, x1, y0, y1 = self._extent\n 944 bbox = Bbox.from_extents([x0, y0, x1, y1])\n 945 return bbox.transformed(self.axes.transData)\n\nTypeError: cannot unpack non-iterable NoneType object\n<Figure size 504x216 with 3 Axes>\n\nThe error occurs deep in the append call, and appears to involve trying to get information about the plot window. If I comment out the append line, and it continues on to the plt.show(), and resulting image looks like the example, except the third image is blank.\n\nI tested this in a Windows QtConsole; I don't know if that context posses problems for this append or not. I don't think it's a problem with your code copy.\n" ]
[ 0 ]
[]
[]
[ "histogram2d", "numpy", "python" ]
stackoverflow_0074677859_histogram2d_numpy_python.txt
Q: K8s Nodeport is faster than service name? I have 2 k8s application running in a single cluster. When it communicate with service name, it takes 12 seconds to transfer 1 GB data. When communicate with nodeport time is 8sec. Why the service name is slow? Why the nodeport give faster? Actually the service name should be faster right? A: It is expected to be faster when using the NodePort since the request does not rely on the kube-proxy to forward the traffic to the target. It also depends on the way the kube-proxy is configured. User space: This mode gets its name because the service routing takes place in kube-proxy in the user process space instead of in the kernel network stack. It is not commonly used as it is slow and outdated. iptables: This mode uses Linux kernel-level Netfilter rules to configure all routing for Kubernetes Services. This mode is the default for kube-proxy on most platforms. When load balancing for multiple backend pods, it uses unweighted round-robin scheduling. IPVS (IP Virtual Server): Built on the Netfilter framework, IPVS implements Layer-4 load balancing in the Linux kernel, supporting multiple load-balancing algorithms, including least connections and shortest expected delay. This kube-proxy mode became generally available in Kubernetes 1.11, but it requires the Linux kernel to have the IPVS modules loaded. It is also not as widely supported by various Kubernetes networking projects as the iptables mode. ref: https://www.stackrox.io/blog/kubernetes-networking-demystified/#kube-proxy On a side note, recently a new feature gate was introduced local service-traffic-policy. While it's still going through the kube-proxy, it will also reduce roundtrips since it routes traffic only to the same node. Maybe you want to test this as an experiment.
K8s Nodeport is faster than service name?
I have 2 k8s application running in a single cluster. When it communicate with service name, it takes 12 seconds to transfer 1 GB data. When communicate with nodeport time is 8sec. Why the service name is slow? Why the nodeport give faster? Actually the service name should be faster right?
[ "It is expected to be faster when using the NodePort since the request does not rely on the kube-proxy to forward the traffic to the target.\nIt also depends on the way the kube-proxy is configured.\n\nUser space: This mode gets its name because the service routing takes place in kube-proxy in the user process space instead of in the kernel network stack. It is not commonly used as it is slow and outdated.\niptables: This mode uses Linux kernel-level Netfilter rules to configure all routing for Kubernetes Services. This mode is the default for kube-proxy on most platforms. When load balancing for multiple backend pods, it uses unweighted round-robin scheduling.\nIPVS (IP Virtual Server): Built on the Netfilter framework, IPVS implements Layer-4 load balancing in the Linux kernel, supporting multiple load-balancing algorithms, including least connections and shortest expected delay. This kube-proxy mode became generally available in Kubernetes 1.11, but it requires the Linux kernel to have the IPVS modules loaded. It is also not as widely supported by various Kubernetes networking projects as the iptables mode.\n\nref: https://www.stackrox.io/blog/kubernetes-networking-demystified/#kube-proxy\nOn a side note, recently a new feature gate was introduced local service-traffic-policy. While it's still going through the kube-proxy, it will also reduce roundtrips since it routes traffic only to the same node. Maybe you want to test this as an experiment.\n" ]
[ 0 ]
[]
[]
[ "kubernetes", "kubernetes_nodeport", "service_name" ]
stackoverflow_0074678663_kubernetes_kubernetes_nodeport_service_name.txt
Q: How to escape characters in dynamic fields with KQL One of the inner values of my dynamic field contains "@". How can I escape the @? (need to escape the "fields.@version") let Source = datatable (fields: dynamic) [ dynamic({"seq":17300,"@version":"1"}) ]; Source | project fields, fields.seq //, fields.@version A: Dynamic object accessors A qualified string (single quote / double quote / triple back-tick) within brackets. let Source = datatable (fields: dynamic) [ dynamic({"seq":17300,"@version":"1"}) ]; Source | project fields['@version'], fields["@version"], fields[```@version```] fields_@version fields_@version1 fields_@version2 1 1 1 Fiddle A: This seems to work: let Source = datatable (fields: dynamic) [ dynamic({"seq":17300,"@version":"1"}) ]; Source | project fields, fields.seq , fields.['@version'] Are there any other options?
How to escape characters in dynamic fields with KQL
One of the inner values of my dynamic field contains "@". How can I escape the @? (need to escape the "fields.@version") let Source = datatable (fields: dynamic) [ dynamic({"seq":17300,"@version":"1"}) ]; Source | project fields, fields.seq //, fields.@version
[ "Dynamic object accessors\nA qualified string (single quote / double quote / triple back-tick) within brackets.\nlet Source = datatable (fields: dynamic) [\n dynamic({\"seq\":17300,\"@version\":\"1\"})\n];\nSource \n| project fields['@version'], fields[\"@version\"], fields[```@version```]\n\n\n\n\n\nfields_@version\nfields_@version1\nfields_@version2\n\n\n\n\n1\n1\n1\n\n\n\n\nFiddle\n", "This seems to work:\nlet Source = datatable (fields: dynamic) [\n dynamic({\"seq\":17300,\"@version\":\"1\"})\n];\nSource | project fields, fields.seq , fields.['@version']\n\nAre there any other options?\n" ]
[ 1, 0 ]
[]
[]
[ "azure_data_explorer", "kql" ]
stackoverflow_0074678197_azure_data_explorer_kql.txt
Q: How to fix "Object reference not set to an instance of an object" in Dynamics 365 im getting troubles with an element from Application Suite Package. When Im adding it in table fields and try to drag it im getting this error: Check Screenshot of error (My model its an empty project that include ApplicationSuite) Upd: I have already sync the whole Database. And also I have tried to use this element(ItemId) in other model and after build I didnt get any errors at build, but the element still dont work in any of my models. A: Select the project your Table2 is in (If it is not in a project, first create a project and add the table in that project.), right click ItemId in the AOT, select "Add to project" and select Yes when asked something-or-the-other about copying it over models. Then try adding the ItemId from your project by drag-and-drop to Table2? A: I already find the problem. ItemId extend ItemIdBase which is in other Model and 2 more items that is included in ItemdId. I had to add 3 models Directory,Ledger and SourceDocumentationTypes.
How to fix "Object reference not set to an instance of an object" in Dynamics 365
im getting troubles with an element from Application Suite Package. When Im adding it in table fields and try to drag it im getting this error: Check Screenshot of error (My model its an empty project that include ApplicationSuite) Upd: I have already sync the whole Database. And also I have tried to use this element(ItemId) in other model and after build I didnt get any errors at build, but the element still dont work in any of my models.
[ "Select the project your Table2 is in (If it is not in a project, first create a project and add the table in that project.), right click ItemId in the AOT, select \"Add to project\" and select Yes when asked something-or-the-other about copying it over models. Then try adding the ItemId from your project by drag-and-drop to Table2?\n", "I already find the problem. ItemId extend ItemIdBase which is in other Model and 2 more items that is included in ItemdId. I had to add 3 models Directory,Ledger and SourceDocumentationTypes.\n" ]
[ 0, 0 ]
[]
[]
[ "dynamics_365", "dynamics_365_operations" ]
stackoverflow_0070079187_dynamics_365_dynamics_365_operations.txt
Q: Pyinstaller - Error loading Python DLL - FormatMessageW failed I compiled my .py file running following commands: pyinstaller myfile.py --onefile. When i run it on my pc(Windows 10) everything works just fine. When i try to run it on my `virtual machine(Windows 8). I get the following error: Error loading Python DLL 'C:\Users\MyUsername\Appdata\Local\Temp\NUMBERS\python36.dll' LoadLibrary: PyInstaller: FormatMessageW failed. I already googled the error and i found many solutions but none of them worked.. //UPDATE: If i compile it with my virtual machine, everything runs fine on the virtual machine, main pc and even on my windows server.. strange.. so it must be a problem with my main pc. Kind Regards A: I had a similar problem trying to run a python-based program (aws cli) and getting the "Error loading Python DLL ... LoadLibrary: The specified module could not be found." on Windows Server 2008 R2. I solved this issue by installing the Visual C++ Redistributable for Visual Studio 2015 run-time components. https://www.microsoft.com/en-us/download/confirmation.aspx?id=48145 Hope it helps! A: This also happens when you read the .exe file located in build. You need to run the exe located in dist folder. If the error persists even on dist folder .exe , check the exact version of python, download python dll from internet for that exact version, in keep in the folder suggested by the error message (path where this dll is missing). A: Try to download a 32 bit version of python36.dll (or 64 if you tried 32) That fixed the problem for me
Pyinstaller - Error loading Python DLL - FormatMessageW failed
I compiled my .py file running following commands: pyinstaller myfile.py --onefile. When i run it on my pc(Windows 10) everything works just fine. When i try to run it on my `virtual machine(Windows 8). I get the following error: Error loading Python DLL 'C:\Users\MyUsername\Appdata\Local\Temp\NUMBERS\python36.dll' LoadLibrary: PyInstaller: FormatMessageW failed. I already googled the error and i found many solutions but none of them worked.. //UPDATE: If i compile it with my virtual machine, everything runs fine on the virtual machine, main pc and even on my windows server.. strange.. so it must be a problem with my main pc. Kind Regards
[ "I had a similar problem trying to run a python-based program (aws cli) and getting the \"Error loading Python DLL ... LoadLibrary: The specified module could not be found.\" on Windows Server 2008 R2. \nI solved this issue by installing the Visual C++ Redistributable for Visual Studio 2015 run-time components. https://www.microsoft.com/en-us/download/confirmation.aspx?id=48145\nHope it helps!\n", "This also happens when you read the .exe file located in build.\nYou need to run the exe located in dist folder.\nIf the error persists even on dist folder .exe , check the exact version of python, download python dll from internet for that exact version, in keep in the folder suggested by the error message (path where this dll is missing).\n", "Try to download a 32 bit version of python36.dll (or 64 if you tried 32)\nThat fixed the problem for me\n" ]
[ 3, 0, 0 ]
[ "You can use auto-py-to-exe instead:\npython -m pip install auto-py-to-exe\nAnd then wait for it to download and then write in then cmd (or terminal):\nauto-py-to-exe\nA screen will appear:\n\nAnd just make as I made in the screenshot, then press \"convert .py to .exe\" and then press \"show output folder\".\n" ]
[ -1 ]
[ "pyinstaller", "python" ]
stackoverflow_0054214600_pyinstaller_python.txt
Q: Problem with json_encode() it removes the "0" key from JSON string number in PHP I need to call this value registered in a MySQL column: {"0":[{"Type":3,"Seconds":-185}],"1":[{"Type":4,"Seconds":-144}]} With this form I get the JSON from the MySQL database: $boosterResultant = $mysqli->query('SELECT boosters FROM player_equipment WHERE userId = '.$player['userId'].'')->fetch_assoc()['boosters']; //response: "{\"0\":[{\"Type\":3,\"Seconds\":-185}],\"1\":[{\"Type\":4,\"Seconds\":-144}]}" I want to access what is in 'Seconds' to modify its value, so I use this form to modify it: $boosterFinal = json_decode($boosterResultant,true); $boosterFinal[0][0]['Seconds'] += 36000; //the value is changed successfully echo "Output:", json_encode($boosterFinal); //out: [[{"Type":3,"Seconds":35815}],[{"Type":4,"Seconds":-144}]] Since I run $boosterFinal = json_decode($boosterResultant,true); I get this: [[{"Type":3,"Seconds":-185}],[{"Type":4,"Seconds":-144}]] but I need to stay like this for update later in the DB: {"0":[{"Type":3,"Seconds":35815}],"1":[{"Type":4,"Seconds":-144}]} //good //bad: [[{"Type":3,"Seconds":35815}],[{"Type":4,"Seconds":-144}]] Edit: Thanks to @A. Cedano (link of answer in Spanish forum: here), I found the answer: //This is the data that comes from the sample DB $str='{"0":[{"Type":3,"Seconds":-185}],"1":[{"Type":4,"Seconds":-144}]}'; //Don't pass TRUE to json_decode to work as JSON as is $mJson=json_decode($str); $mJson->{0}[0]->Seconds+=36000; //Object Test echo $mJson; //Output: {"0":[{"Type":3,"Seconds":35815}],"1":[{"Type":4,"Seconds":-144}]} A: If PHP sees that your array keys are ascending ints, it automatically converts them into an array (php.net/manual/en/function.json-encode.php) You can disable this by passing the JSON_FORCE_OBJECT flag as a second param into json_encode: json_encode($boosterFinal, JSON_FORCE_OBJECT) A: I had a similar problem, where JSON_FORCE_OBJECT didn't work. I had an array that looked like this: <?php $array = [ "someKey" => [ 0 => "Some text....", 1 => "Some other text....." ] ]; Using json_encode with no flags I got a JSON object that looked like this: { "someKey": [ ["Some text...."], {"1": "Some other text....."} ] } This is clearly not what I had as the PHP object, and not what I want as the JSON object. with the JSON_FORCE_OBJECT I got a JSON object that looked like this: { "someKey": [ {"0": "Some text...."}, {"1": "Some other text....."} ] } Which does fix the issuse I had, but causes another issue. It would add unnecessary keys to arrays that don't have keys. Like this: $array = ["Sometext..."]; echo json_encode($array, JSON_PRETTY_PRINT|JSON_FORCE_OBJECT); // {0: "Sometext..."} We once again have the same issue, that the JSON object is not the same as the original PHP array. Solution: I used stdClass for the array that had numeric keys. and It encoded it to JSON correctly. code: $array = []; $stdClass = new stdClass(); $stdClass->{0} = "Some text..."; $stdClass->{1} = "Some other text...."; array_push($array, ["someKey" => $stdClass]); $json = json_encode($array, JSON_PRETTY_PRINT); echo $json; //Output: /* { "someKey": [ {"0": "Some text...."}, {"1": "Some other text....."} ] } */ This is because PHP does not touch the indexes when encoding an stdClass.
Problem with json_encode() it removes the "0" key from JSON string number in PHP
I need to call this value registered in a MySQL column: {"0":[{"Type":3,"Seconds":-185}],"1":[{"Type":4,"Seconds":-144}]} With this form I get the JSON from the MySQL database: $boosterResultant = $mysqli->query('SELECT boosters FROM player_equipment WHERE userId = '.$player['userId'].'')->fetch_assoc()['boosters']; //response: "{\"0\":[{\"Type\":3,\"Seconds\":-185}],\"1\":[{\"Type\":4,\"Seconds\":-144}]}" I want to access what is in 'Seconds' to modify its value, so I use this form to modify it: $boosterFinal = json_decode($boosterResultant,true); $boosterFinal[0][0]['Seconds'] += 36000; //the value is changed successfully echo "Output:", json_encode($boosterFinal); //out: [[{"Type":3,"Seconds":35815}],[{"Type":4,"Seconds":-144}]] Since I run $boosterFinal = json_decode($boosterResultant,true); I get this: [[{"Type":3,"Seconds":-185}],[{"Type":4,"Seconds":-144}]] but I need to stay like this for update later in the DB: {"0":[{"Type":3,"Seconds":35815}],"1":[{"Type":4,"Seconds":-144}]} //good //bad: [[{"Type":3,"Seconds":35815}],[{"Type":4,"Seconds":-144}]] Edit: Thanks to @A. Cedano (link of answer in Spanish forum: here), I found the answer: //This is the data that comes from the sample DB $str='{"0":[{"Type":3,"Seconds":-185}],"1":[{"Type":4,"Seconds":-144}]}'; //Don't pass TRUE to json_decode to work as JSON as is $mJson=json_decode($str); $mJson->{0}[0]->Seconds+=36000; //Object Test echo $mJson; //Output: {"0":[{"Type":3,"Seconds":35815}],"1":[{"Type":4,"Seconds":-144}]}
[ "If PHP sees that your array keys are ascending ints, it automatically converts them into an array (php.net/manual/en/function.json-encode.php)\nYou can disable this by passing the JSON_FORCE_OBJECT flag as a second param into json_encode: json_encode($boosterFinal, JSON_FORCE_OBJECT)\n", "I had a similar problem, where JSON_FORCE_OBJECT didn't work. I had an array that looked like this:\n<?php\n$array = [\n \"someKey\" => [\n 0 => \"Some text....\",\n 1 => \"Some other text.....\"\n ]\n];\n\nUsing json_encode with no flags I got a JSON object that looked like this:\n{\n \"someKey\": [\n [\"Some text....\"],\n {\"1\": \"Some other text.....\"}\n ]\n}\n\nThis is clearly not what I had as the PHP object, and not what I want as the JSON object.\nwith the JSON_FORCE_OBJECT I got a JSON object that looked like this:\n{\n \"someKey\": [\n {\"0\": \"Some text....\"},\n {\"1\": \"Some other text.....\"}\n ]\n}\n\nWhich does fix the issuse I had, but causes another issue. It would add unnecessary keys to arrays that don't have keys. Like this:\n$array = [\"Sometext...\"];\necho json_encode($array, JSON_PRETTY_PRINT|JSON_FORCE_OBJECT);\n// {0: \"Sometext...\"}\n\nWe once again have the same issue, that the JSON object is not the same as the original PHP array.\nSolution:\nI used stdClass for the array that had numeric keys. and It encoded it to JSON correctly. code:\n$array = [];\n\n$stdClass = new stdClass();\n\n$stdClass->{0} = \"Some text...\";\n$stdClass->{1} = \"Some other text....\";\n\narray_push($array, [\"someKey\" => $stdClass]);\n\n$json = json_encode($array, JSON_PRETTY_PRINT);\n\necho $json;\n\n//Output:\n/*\n{\n \"someKey\": [\n {\"0\": \"Some text....\"},\n {\"1\": \"Some other text.....\"}\n ]\n}\n*/\n\n\nThis is because PHP does not touch the indexes when encoding an stdClass.\n" ]
[ 2, 0 ]
[]
[]
[ "database", "json", "mysql", "php" ]
stackoverflow_0061536684_database_json_mysql_php.txt
Q: Beautiful Soup get nested span by class within another span Within a very large HTML page i want to get a span by class which is unique. The child span of this one, can be queried also by class but which is not unique. ... <span class="uniqueParent"> <span class="notUniqueChildClassName"> I am the child </span> </span> ... Output should be "I am the child". I have tried: s = soup.select('span[class="uniqueParent"] > span[class="notUniqueChildClassName"]') s.text and s = soup.find('span[class="uniqueParent"] > span[class="notUniqueChildClassName"]') s.text But both did not work. A: Try changing the first attempt to soup.select_one('span[class="uniqueParent"] > span[class="notUniqueChildClassName"]').text.strip() on your actual html. The output should be what you're looking for. A: You can use CSS selector with dot (e.g .uniqueParent, instead of class="uniqueParent"): from bs4 import BeautifulSoup html_doc = """\ <span class="uniqueParent"> <span class="notUniqueChildClassName"> I am the child </span> </span> """ soup = BeautifulSoup(html_doc, "html.parser") print(soup.select_one(".uniqueParent .notUniqueChildClassName").text) Prints: I am the child
Beautiful Soup get nested span by class within another span
Within a very large HTML page i want to get a span by class which is unique. The child span of this one, can be queried also by class but which is not unique. ... <span class="uniqueParent"> <span class="notUniqueChildClassName"> I am the child </span> </span> ... Output should be "I am the child". I have tried: s = soup.select('span[class="uniqueParent"] > span[class="notUniqueChildClassName"]') s.text and s = soup.find('span[class="uniqueParent"] > span[class="notUniqueChildClassName"]') s.text But both did not work.
[ "Try changing the first attempt to\nsoup.select_one('span[class=\"uniqueParent\"] > span[class=\"notUniqueChildClassName\"]').text.strip()\n\non your actual html.\nThe output should be what you're looking for.\n", "You can use CSS selector with dot (e.g .uniqueParent, instead of class=\"uniqueParent\"):\nfrom bs4 import BeautifulSoup\n\n\nhtml_doc = \"\"\"\\\n<span class=\"uniqueParent\">\n <span class=\"notUniqueChildClassName\">\n I am the child\n </span>\n</span> \"\"\"\n\n\nsoup = BeautifulSoup(html_doc, \"html.parser\")\n\nprint(soup.select_one(\".uniqueParent .notUniqueChildClassName\").text)\n\nPrints:\n\n I am the child\n \n\n" ]
[ 1, 1 ]
[]
[]
[ "beautifulsoup" ]
stackoverflow_0074678625_beautifulsoup.txt
Q: How Do I Check RegEx In Integer Form I am trying to do the Advent Of Code 2022, 1st problem. (DONT TELL THE ANSWER). What i am doing is reading the file and taking each number and adding it to a sum value. What happens is, when I come across the "\n", it doesn't understand it and I am having trouble trying to create the array of sums. Can anyone help? ` with open("input.txt") as f: list_array = f.read().split("\n") print(list_array) new_array = [] sum = 0 for i in list_array: print(i) if i == "\n": new_array.append(sum) sum = 0 sum += int(str(i)) print(sum) ` I was trying to convert to back to a str then an int, but it doesn't work A: Instead of checking for i == "\n", you should check i == ''. As the split based on \n will remove all the \n but left empty strings '' And for the line sum += int(str(i)), it should be applied when i != '' only. So the modified code should be: with open("input.txt") as f: list_array = f.read().split("\n") print(list_array) new_array = [] sum = 0 for i in list_array: print(i) if i == '': new_array.append(sum) sum = 0 else: sum += int(str(i)) print(sum)
How Do I Check RegEx In Integer Form
I am trying to do the Advent Of Code 2022, 1st problem. (DONT TELL THE ANSWER). What i am doing is reading the file and taking each number and adding it to a sum value. What happens is, when I come across the "\n", it doesn't understand it and I am having trouble trying to create the array of sums. Can anyone help? ` with open("input.txt") as f: list_array = f.read().split("\n") print(list_array) new_array = [] sum = 0 for i in list_array: print(i) if i == "\n": new_array.append(sum) sum = 0 sum += int(str(i)) print(sum) ` I was trying to convert to back to a str then an int, but it doesn't work
[ "Instead of checking for i == \"\\n\", you should check i == ''. As the split based on \\n will remove all the \\n but left empty strings ''\nAnd for the line sum += int(str(i)), it should be applied when i != '' only.\nSo the modified code should be:\nwith open(\"input.txt\") as f:\n list_array = f.read().split(\"\\n\")\n print(list_array)\n new_array = []\n sum = 0\n for i in list_array:\n print(i)\n if i == '':\n new_array.append(sum)\n sum = 0\n else: \n sum += int(str(i))\n print(sum)\n\n" ]
[ 0 ]
[]
[]
[ "integer", "python", "validation" ]
stackoverflow_0074678597_integer_python_validation.txt
Q: Create and get array in a Firebase Realtime Database I have just linked and started storing values in my realtime database and it all works smoothly. I have noticed however that when attempting to set another string to the list its overwrite it instead of having multiple values. My goal is to store multiple numbers (stored as strings) to the branch so I can calculate an average value to display in my app. Here is current code: val myRef = database.getReference("/general/$position") //sets location to save data, (In the section general, subcategory being the number of the list item being used //set up button that is in the dialogue val button = dialog.findViewById<View>(R.id.menu_rate) as Button button.setOnClickListener { val simpleRatingBar = dialog.findViewById<View>(R.id.ratingBar) as RatingBar // initiates the rating bar val ratingNumber = simpleRatingBar.rating // get rating number from a rating bar Toast.makeText(this, "You rated this $ratingNumber stars!", Toast.LENGTH_SHORT).show() val rating = ratingNumber.toString() //converts the float to string for storage myRef.setValue(rating) //saves value to server .addOnSuccessListener { Toast.makeText(this, "success", Toast.LENGTH_SHORT).show() } } It stores the values correctly for each category, it just only allows for 1 value to be stored per position. So how could I get multiple values to be stored so that I can then get the values and utilize them in my app? A: To store multiple values in a list in a Realtime Database, you can use the push() method to add a new value to the list. This method will automatically generate a unique key for the new value and append it to the list. For example, if you want to store multiple ratings for each item in your list, you can modify your code as follows: val myRef = database.getReference("/general/$position") // sets location to save data, (In the section general, subcategory being the number of the list item being used // set up button that is in the dialogue val button = dialog.findViewById<View>(R.id.menu_rate) as Button button.setOnClickListener { Copy code val simpleRatingBar = dialog.findViewById<View>(R.id.ratingBar) as RatingBar // initiates the rating bar val ratingNumber = simpleRatingBar.rating // get rating number from a rating bar Toast.makeText(this, "You rated this $ratingNumber stars!", Toast.LENGTH_SHORT).show() val rating = ratingNumber.toString() // converts the float to string for storage // use the push() method to add the new rating to the list myRef.push().setValue(rating) .addOnSuccessListener { Toast.makeText(this, "success", Toast.LENGTH_SHORT).show() } } With this code, each time the button is clicked, a new rating will be added to the list under the specified position. You can then retrieve the list of ratings using the value event listener, and calculate the average rating using the values in the list. For more information about using lists in the Realtime Database, see the Realtime Database documentation.
Create and get array in a Firebase Realtime Database
I have just linked and started storing values in my realtime database and it all works smoothly. I have noticed however that when attempting to set another string to the list its overwrite it instead of having multiple values. My goal is to store multiple numbers (stored as strings) to the branch so I can calculate an average value to display in my app. Here is current code: val myRef = database.getReference("/general/$position") //sets location to save data, (In the section general, subcategory being the number of the list item being used //set up button that is in the dialogue val button = dialog.findViewById<View>(R.id.menu_rate) as Button button.setOnClickListener { val simpleRatingBar = dialog.findViewById<View>(R.id.ratingBar) as RatingBar // initiates the rating bar val ratingNumber = simpleRatingBar.rating // get rating number from a rating bar Toast.makeText(this, "You rated this $ratingNumber stars!", Toast.LENGTH_SHORT).show() val rating = ratingNumber.toString() //converts the float to string for storage myRef.setValue(rating) //saves value to server .addOnSuccessListener { Toast.makeText(this, "success", Toast.LENGTH_SHORT).show() } } It stores the values correctly for each category, it just only allows for 1 value to be stored per position. So how could I get multiple values to be stored so that I can then get the values and utilize them in my app?
[ "To store multiple values in a list in a Realtime Database, you can use the push() method to add a new value to the list. This method will automatically generate a unique key for the new value and append it to the list.\nFor example, if you want to store multiple ratings for each item in your list, you can modify your code as follows:\nval myRef = database.getReference(\"/general/$position\") // sets location to save data, (In the section general, subcategory being the number of the list item being used\n\n// set up button that is in the dialogue\nval button = dialog.findViewById<View>(R.id.menu_rate) as Button\nbutton.setOnClickListener {\n\nCopy code\nval simpleRatingBar = dialog.findViewById<View>(R.id.ratingBar) as RatingBar // initiates the rating bar\n\nval ratingNumber = simpleRatingBar.rating // get rating number from a rating bar\n\nToast.makeText(this, \"You rated this $ratingNumber stars!\", Toast.LENGTH_SHORT).show()\n\nval rating = ratingNumber.toString() // converts the float to string for storage\n\n// use the push() method to add the new rating to the list\nmyRef.push().setValue(rating)\n .addOnSuccessListener {\n Toast.makeText(this, \"success\", Toast.LENGTH_SHORT).show()\n }\n}\n\nWith this code, each time the button is clicked, a new rating will be added to the list under the specified position. You can then retrieve the list of ratings using the value event listener, and calculate the average rating using the values in the list.\nFor more information about using lists in the Realtime Database, see the Realtime Database documentation.\n" ]
[ 1 ]
[]
[]
[ "android", "firebase", "firebase_realtime_database", "kotlin" ]
stackoverflow_0074678758_android_firebase_firebase_realtime_database_kotlin.txt
Q: Creating second sequence based on argument; Oracle I have the following question. I have generated the following RowNumber column by usage of the rownumber() function and the over(paritation by clause. The counting starts with '1' every time a new part_no is listed: SEQ_NO PART_NO RowNumber LEVEL 110 PRD101 1 1 120 PRD101 2 2 130 PRD101 3 3 140 PRD101 4 4 150 PRD101 5 1 160 PRD101 6 2 110 PRD102 1 1 120 PRD102 2 2 130 PRD102 3 2 140 PRD102 4 1 110 PRD103 1 1 120 PRD103 2 1 The query is kind of like this: select seq_no, part_no, row_number() over(partition by part_no order by seq_no) as RowNumber, level from table1 The point is that I would like to create a second sequence which does not fill any value in for rows where levels > 2 The second sequence is also paritated by the part_no The table would result like: SEQ_NO PART_NO RowNumber SecondRowNumber LEVEL 110 PRD101 1 1 1 120 PRD101 2 2 2 130 PRD101 3 3 140 PRD101 4 4 150 PRD101 5 3 1 160 PRD101 6 4 2 110 PRD102 1 1 1 120 PRD102 2 2 2 130 PRD102 3 3 2 140 PRD102 4 4 1 110 PRD103 1 1 1 120 PRD103 2 2 1 Does anyone have an idea how to solve this? A: use a case statement in the select clause of your query to create the second sequence. select seq_no, part_no, row_number() over(partition by part_no order by seq_no) as RowNumber, case when level > 2 then null else RowNumber end as SecondRowNumber, level from table1 A: You can create a CTE with the wnated secnd row numbers and join it WITH CTE as ( select "SEQ_NO", "PART_NO" , row_number() over(partition by "PART_NO" order by "SEQ_NO") as RowNumber, "LEVEL" from table1 WHERE "LEVEL" <= 2 ) select table1."SEQ_NO", table1."PART_NO" , row_number() over(partition by table1."PART_NO" order by table1."SEQ_NO") as RowNumber_ , CTE.RowNumber as secondRowNumber , table1."LEVEL" from table1 LEFT JOIN CTE ON table1."SEQ_NO" = CTE."SEQ_NO" AND table1."PART_NO" = CTE."PART_NO" SEQ_NO PART_NO ROWNUMBER_ SECONDROWNUMBER LEVEL 110 PRD101 1 1 1 120 PRD101 2 2 2 130 PRD101 3 null 3 140 PRD101 4 null 4 150 PRD101 5 3 1 160 PRD101 6 4 2 110 PRD102 1 1 1 120 PRD102 2 2 2 130 PRD102 3 3 2 140 PRD102 4 4 1 110 PRD103 1 1 1 120 PRD103 2 2 1 fiddle
Creating second sequence based on argument; Oracle
I have the following question. I have generated the following RowNumber column by usage of the rownumber() function and the over(paritation by clause. The counting starts with '1' every time a new part_no is listed: SEQ_NO PART_NO RowNumber LEVEL 110 PRD101 1 1 120 PRD101 2 2 130 PRD101 3 3 140 PRD101 4 4 150 PRD101 5 1 160 PRD101 6 2 110 PRD102 1 1 120 PRD102 2 2 130 PRD102 3 2 140 PRD102 4 1 110 PRD103 1 1 120 PRD103 2 1 The query is kind of like this: select seq_no, part_no, row_number() over(partition by part_no order by seq_no) as RowNumber, level from table1 The point is that I would like to create a second sequence which does not fill any value in for rows where levels > 2 The second sequence is also paritated by the part_no The table would result like: SEQ_NO PART_NO RowNumber SecondRowNumber LEVEL 110 PRD101 1 1 1 120 PRD101 2 2 2 130 PRD101 3 3 140 PRD101 4 4 150 PRD101 5 3 1 160 PRD101 6 4 2 110 PRD102 1 1 1 120 PRD102 2 2 2 130 PRD102 3 3 2 140 PRD102 4 4 1 110 PRD103 1 1 1 120 PRD103 2 2 1 Does anyone have an idea how to solve this?
[ "use a case statement in the select clause of your query to create the second sequence.\nselect seq_no,\n part_no,\n row_number() over(partition by part_no order by seq_no) as RowNumber,\n case when level > 2 then null else RowNumber end as SecondRowNumber,\n level\nfrom table1\n\n", "You can create a CTE with the wnated secnd row numbers and join it\nWITH CTE as (\n select \"SEQ_NO\", \"PART_NO\"\n , row_number() over(partition by \"PART_NO\" order by \"SEQ_NO\") as RowNumber, \"LEVEL\" \nfrom table1\n WHERE \"LEVEL\" <= 2\n )\nselect table1.\"SEQ_NO\", table1.\"PART_NO\"\n , row_number() over(partition by table1.\"PART_NO\" order by table1.\"SEQ_NO\") as RowNumber_\n , CTE.RowNumber as secondRowNumber\n , table1.\"LEVEL\" \nfrom table1 LEFT JOIN CTE ON table1.\"SEQ_NO\" = CTE.\"SEQ_NO\" AND table1.\"PART_NO\" = CTE.\"PART_NO\"\n\n\n\n\n\nSEQ_NO\nPART_NO\nROWNUMBER_\nSECONDROWNUMBER\nLEVEL\n\n\n\n\n110\nPRD101\n1\n1\n1\n\n\n120\nPRD101\n2\n2\n2\n\n\n130\nPRD101\n3\nnull\n3\n\n\n140\nPRD101\n4\nnull\n4\n\n\n150\nPRD101\n5\n3\n1\n\n\n160\nPRD101\n6\n4\n2\n\n\n110\nPRD102\n1\n1\n1\n\n\n120\nPRD102\n2\n2\n2\n\n\n130\nPRD102\n3\n3\n2\n\n\n140\nPRD102\n4\n4\n1\n\n\n110\nPRD103\n1\n1\n1\n\n\n120\nPRD103\n2\n2\n1\n\n\n\n\nfiddle\n" ]
[ 0, 0 ]
[]
[]
[ "oracle", "row_number", "sql" ]
stackoverflow_0074678499_oracle_row_number_sql.txt
Q: NodeJS HTTPS server serving over HTTP instead of HTTPS when running inside Docker container I'm creating a website using NextJS and Docker so that I can easily deploy it. I used npx-create-next-app to initialize it and used this Dockerfile (slightly modified) to containerize it. Since I wanted to use SSL with my server without going through the hassle of setting up a proxy, I followed this article, and setup the custom server. This worked fine when I ran it outside of a docker container, and performed as expected, serving over HTTPS. However when I containerized it, and tried to open the webpage over HTTPS, I came up with SSL_ERROR_RX_RECORD_TOO_LONG, but I could open the page using just HTTP (which I could not do when running outside of a container). Some googling led me to this question, from which I concluded that when running outside of a docker container, the custom server runs the server over HTTPS, as expected, however when I containerize it, it starts running HTTP, even though no code has been changed. I'd expect the behavior to be the same when running locally or containerized. At first I assumed this was due to invalid key and cert values in httpsOptions however I wasn't able to find anything that would make them invalid, and I don't see how that would cause this strange behavior. I tried changing the Docker run environment from node:alpine-16 to just node:latest to see if it had something to do with the parent image, but that was fruitless. One other minor issue I had is that console.log does not seem to output to the container's log for some reason, I tried googling this but didn't find much of anything pertaining to it. This has made debugging much harder as I can't really output any debug data. The only log I get when running inside of a container is Listening on port 3000 url: http://localhost:3000, which I assume is output by some library/package as it isn't anywhere in my code. Here is my custom server code in case it would be helpful: const https = require('https'); const fs = require('fs'); const { parse } = require('url'); const next = require('next'); const dev = process.env.NODE_ENV !== 'production'; const hostname = "127.0.0.1"; const port = process.env.PORT || 3000 const app = next({ dev, hostname, port }) const handle = app.getRequestHandler() const httpsOptions = { key: fs.readFileSync('./cert/privkey.pem'), cert: fs.readFileSync('./cert/fullchain.pem') }; app.prepare().then(() => { https.createServer(httpsOptions, async (req, res) => { // When running on docker this creates an HTTP server instead of HTTPS const parsedUrl = parse(req.url, true) const { pathname, query } = parsedUrl await handle(req, res, parsedUrl) }).listen(port, (err) => { if(err) throw err console.log(`Ready on https://localhost:${port}`) }) }) Link to a reproducible example here. A: It sounds like you have successfully set up a NextJS server that serves over HTTPS when running outside of a Docker container. You have also containerized the server using Docker, but when you try to access the server over HTTPS from inside the container, you receive the error SSL_ERROR_RX_RECORD_TOO_LONG. This error typically indicates that the server is not configured to use HTTPS. In your code, you create a server using the https module and pass in your httpsOptions object, which contains the key and cert files. However, when running inside the Docker container, it appears that the server is being created using the http module instead of https. One potential cause of this issue could be that the https module is not installed in the Docker container. This could happen if the https module is not listed in the dependencies section of your package.json file. If that is the case, you can fix the issue by adding the https module to your dependencies and rebuilding the Docker container. Alternatively, it could be that the https module is installed in the Docker container, but the code is not executing the https.createServer() line. This could be due to a syntax error or some other issue in the code. In that case, you can try adding some logging statements to your code to help diagnose the problem. For example, you could try adding a log statement before the https.createServer() line to print the value of the https module. This can help you determine whether the https module is being loaded correctly. As for your second issue, the fact that console.log() statements are not appearing in the container logs, this could be due to the way that Docker is configured. By default, Docker will only show logs for a container if it is running in the foreground. If the container is running in the background, you will need to use the docker logs command to view the logs. You can also use the -f flag with docker logs to follow the logs in real-time. In summary, it sounds like your NextJS server is not serving over HTTPS when running inside the Docker container because the https module is not installed or is not being used correctly. To fix this issue, you can try the following steps: Check that the https module is listed in the dependencies section of your package.json file. If it is not, add it and rebuild the Docker container. Add some logging statements to your code to help diagnose the problem. For example, you can try logging the value of the https module before the https.createServer() line. Make sure that the container is running in the foreground, or use the docker logs command to view the logs. You can use the -f flag with docker logs to follow the logs in real-time. A: The thing is, based on your sample repo, that your server.js file that is in the root of your repo gets overwritten in the image because of this line in the Dockerfile: COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ So the actual server.js that is running in the container is the server.js that is created by the yarn build command and it looks like this (you can exec into the container and see it for yourself): const NextServer = require('next/dist/server/next-server').default const http = require('http') const path = require('path') process.env.NODE_ENV = 'production' process.chdir(__dirname) // Make sure commands gracefully respect termination signals (e.g. from Docker) // Allow the graceful termination to be manually configurable if (!process.env.NEXT_MANUAL_SIG_HANDLE) { process.on('SIGTERM', () => process.exit(0)) process.on('SIGINT', () => process.exit(0)) } let handler const server = http.createServer(async (req, res) => { try { await handler(req, res) } catch (err) { console.error(err); res.statusCode = 500 res.end('internal server error') } }) const currentPort = parseInt(process.env.PORT, 10) || 3000 server.listen(currentPort, (err) => { if (err) { console.error("Failed to start server", err) process.exit(1) } const nextServer = new NextServer({ hostname: 'localhost', port: currentPort, dir: path.join(__dirname), dev: false, customServer: false, conf: {"env":{},"webpack":null,"webpackDevMiddleware":null,"eslint":{"ignoreDuringBuilds":false},"typescript":{"ignoreBuildErrors":false,"tsconfigPath":"tsconfig.json"},"distDir":"./.next","cleanDistDir":true,"assetPrefix":"","configOrigin":"next.config.js","useFileSystemPublicRoutes":true,"generateEtags":true,"pageExtensions":["tsx","ts","jsx","js"],"target":"server","poweredByHeader":true,"compress":true,"analyticsId":"","images":{"deviceSizes":[640,750,828,1080,1200,1920,2048,3840],"imageSizes":[16,32,48,64,96,128,256,384],"path":"/_next/image","loader":"default","loaderFile":"","domains":[],"disableStaticImages":false,"minimumCacheTTL":60,"formats":["image/webp"],"dangerouslyAllowSVG":false,"contentSecurityPolicy":"script-src 'none'; frame-src 'none'; sandbox;","remotePatterns":[],"unoptimized":false},"devIndicators":{"buildActivity":true,"buildActivityPosition":"bottom-right"},"onDemandEntries":{"maxInactiveAge":15000,"pagesBufferLength":2},"amp":{"canonicalBase":""},"basePath":"","sassOptions":{},"trailingSlash":false,"i18n":{"locales":["en"],"defaultLocale":"en"},"productionBrowserSourceMaps":false,"optimizeFonts":true,"excludeDefaultMomentLocales":true,"serverRuntimeConfig":{},"publicRuntimeConfig":{},"reactStrictMode":true,"httpAgentOptions":{"keepAlive":true},"outputFileTracing":true,"staticPageGenerationTimeout":60,"swcMinify":true,"output":"standalone","experimental":{"middlewarePrefetch":"flexible","optimisticClientCache":true,"manualClientBasePath":false,"legacyBrowsers":false,"newNextLinkBehavior":true,"cpus":7,"sharedPool":true,"profiling":false,"isrFlushToDisk":true,"workerThreads":false,"pageEnv":false,"optimizeCss":false,"nextScriptWorkers":false,"scrollRestoration":false,"externalDir":false,"disableOptimizedLoading":false,"gzipSize":true,"swcFileReading":true,"craCompat":false,"esmExternals":true,"appDir":false,"isrMemoryCacheSize":52428800,"fullySpecified":false,"outputFileTracingRoot":"","swcTraceProfiling":false,"forceSwcTransforms":false,"largePageDataBytes":128000,"enableUndici":false,"adjustFontFallbacks":false,"adjustFontFallbacksWithSizeAdjust":false,"trustHostHeader":false},"configFileName":"next.config.js"}, }) handler = nextServer.getRequestHandler() console.log( 'Listening on port', currentPort, 'url: http://localhost:' + currentPort ) }) And as you see it starts a http server not a https. Also this is why the console.log("lksdfjls"); in your own server.js will not get executed. What I would suggest is to leave node as it is, running on http://localhost:3000 and set up a reverse proxy that would forward incoming requests to this node backend that is accessible only from the reverse proxy. And of course reverse proxy would handle TLS termination. A docker compose setup would be more convenient for this so you could put the reverse proxy container (nginx for example) in the compose project too and map a directory from the docker host where your cert files are stored into the reverse proxy container at runtime - DO NOT BAKE CERTS OR ANY OTHER SECRETS INTO ANY IMAGE, not even if it is an internally used image only because it could leak out accidentally any time. Also you could just manually run the two container with docker run but compose would make life easier it has a lot of capabilities for example you could scale compose services up and down so your backend service would run not in one but many containers. But if this would be a high load and/or business critical production stuff then you are better off with a better (real) container orchestrator like kubernetes, docker swarm, nomad etc but today as I see it the de facto container orchestrator is kubernetes.
NodeJS HTTPS server serving over HTTP instead of HTTPS when running inside Docker container
I'm creating a website using NextJS and Docker so that I can easily deploy it. I used npx-create-next-app to initialize it and used this Dockerfile (slightly modified) to containerize it. Since I wanted to use SSL with my server without going through the hassle of setting up a proxy, I followed this article, and setup the custom server. This worked fine when I ran it outside of a docker container, and performed as expected, serving over HTTPS. However when I containerized it, and tried to open the webpage over HTTPS, I came up with SSL_ERROR_RX_RECORD_TOO_LONG, but I could open the page using just HTTP (which I could not do when running outside of a container). Some googling led me to this question, from which I concluded that when running outside of a docker container, the custom server runs the server over HTTPS, as expected, however when I containerize it, it starts running HTTP, even though no code has been changed. I'd expect the behavior to be the same when running locally or containerized. At first I assumed this was due to invalid key and cert values in httpsOptions however I wasn't able to find anything that would make them invalid, and I don't see how that would cause this strange behavior. I tried changing the Docker run environment from node:alpine-16 to just node:latest to see if it had something to do with the parent image, but that was fruitless. One other minor issue I had is that console.log does not seem to output to the container's log for some reason, I tried googling this but didn't find much of anything pertaining to it. This has made debugging much harder as I can't really output any debug data. The only log I get when running inside of a container is Listening on port 3000 url: http://localhost:3000, which I assume is output by some library/package as it isn't anywhere in my code. Here is my custom server code in case it would be helpful: const https = require('https'); const fs = require('fs'); const { parse } = require('url'); const next = require('next'); const dev = process.env.NODE_ENV !== 'production'; const hostname = "127.0.0.1"; const port = process.env.PORT || 3000 const app = next({ dev, hostname, port }) const handle = app.getRequestHandler() const httpsOptions = { key: fs.readFileSync('./cert/privkey.pem'), cert: fs.readFileSync('./cert/fullchain.pem') }; app.prepare().then(() => { https.createServer(httpsOptions, async (req, res) => { // When running on docker this creates an HTTP server instead of HTTPS const parsedUrl = parse(req.url, true) const { pathname, query } = parsedUrl await handle(req, res, parsedUrl) }).listen(port, (err) => { if(err) throw err console.log(`Ready on https://localhost:${port}`) }) }) Link to a reproducible example here.
[ "It sounds like you have successfully set up a NextJS server that serves over HTTPS when running outside of a Docker container. You have also containerized the server using Docker, but when you try to access the server over HTTPS from inside the container, you receive the error SSL_ERROR_RX_RECORD_TOO_LONG.\nThis error typically indicates that the server is not configured to use HTTPS. In your code, you create a server using the https module and pass in your httpsOptions object, which contains the key and cert files. However, when running inside the Docker container, it appears that the server is being created using the http module instead of https.\nOne potential cause of this issue could be that the https module is not installed in the Docker container. This could happen if the https module is not listed in the dependencies section of your package.json file. If that is the case, you can fix the issue by adding the https module to your dependencies and rebuilding the Docker container.\nAlternatively, it could be that the https module is installed in the Docker container, but the code is not executing the https.createServer() line. This could be due to a syntax error or some other issue in the code. In that case, you can try adding some logging statements to your code to help diagnose the problem. For example, you could try adding a log statement before the https.createServer() line to print the value of the https module. This can help you determine whether the https module is being loaded correctly.\nAs for your second issue, the fact that console.log() statements are not appearing in the container logs, this could be due to the way that Docker is configured. By default, Docker will only show logs for a container if it is running in the foreground. If the container is running in the background, you will need to use the docker logs command to view the logs. You can also use the -f flag with docker logs to follow the logs in real-time.\nIn summary, it sounds like your NextJS server is not serving over HTTPS when running inside the Docker container because the https module is not installed or is not being used correctly. To fix this issue, you can try the following steps:\n\nCheck that the https module is listed in the dependencies section of your package.json file. If it is not, add it and rebuild the Docker container.\nAdd some logging statements to your code to help diagnose the problem. For example, you can try logging the value of the https module before the https.createServer() line.\nMake sure that the container is running in the foreground, or use the docker logs command to view the logs. You can use the -f flag with docker logs to follow the logs in real-time.\n\n", "The thing is, based on your sample repo, that your server.js file that is in the root of your repo gets overwritten in the image because of this line in the Dockerfile:\nCOPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./\nSo the actual server.js that is running in the container is the server.js that is created by the yarn build command and it looks like this (you can exec into the container and see it for yourself):\nconst NextServer = require('next/dist/server/next-server').default\nconst http = require('http')\nconst path = require('path')\nprocess.env.NODE_ENV = 'production'\nprocess.chdir(__dirname)\n\n// Make sure commands gracefully respect termination signals (e.g. from Docker)\n// Allow the graceful termination to be manually configurable\nif (!process.env.NEXT_MANUAL_SIG_HANDLE) {\n process.on('SIGTERM', () => process.exit(0))\n process.on('SIGINT', () => process.exit(0))\n}\n\nlet handler\n\nconst server = http.createServer(async (req, res) => {\n try {\n await handler(req, res)\n } catch (err) {\n console.error(err);\n res.statusCode = 500\n res.end('internal server error')\n }\n})\nconst currentPort = parseInt(process.env.PORT, 10) || 3000\n\nserver.listen(currentPort, (err) => {\n if (err) {\n console.error(\"Failed to start server\", err)\n process.exit(1)\n }\n const nextServer = new NextServer({\n hostname: 'localhost',\n port: currentPort,\n dir: path.join(__dirname),\n dev: false,\n customServer: false,\n conf: {\"env\":{},\"webpack\":null,\"webpackDevMiddleware\":null,\"eslint\":{\"ignoreDuringBuilds\":false},\"typescript\":{\"ignoreBuildErrors\":false,\"tsconfigPath\":\"tsconfig.json\"},\"distDir\":\"./.next\",\"cleanDistDir\":true,\"assetPrefix\":\"\",\"configOrigin\":\"next.config.js\",\"useFileSystemPublicRoutes\":true,\"generateEtags\":true,\"pageExtensions\":[\"tsx\",\"ts\",\"jsx\",\"js\"],\"target\":\"server\",\"poweredByHeader\":true,\"compress\":true,\"analyticsId\":\"\",\"images\":{\"deviceSizes\":[640,750,828,1080,1200,1920,2048,3840],\"imageSizes\":[16,32,48,64,96,128,256,384],\"path\":\"/_next/image\",\"loader\":\"default\",\"loaderFile\":\"\",\"domains\":[],\"disableStaticImages\":false,\"minimumCacheTTL\":60,\"formats\":[\"image/webp\"],\"dangerouslyAllowSVG\":false,\"contentSecurityPolicy\":\"script-src 'none'; frame-src 'none'; sandbox;\",\"remotePatterns\":[],\"unoptimized\":false},\"devIndicators\":{\"buildActivity\":true,\"buildActivityPosition\":\"bottom-right\"},\"onDemandEntries\":{\"maxInactiveAge\":15000,\"pagesBufferLength\":2},\"amp\":{\"canonicalBase\":\"\"},\"basePath\":\"\",\"sassOptions\":{},\"trailingSlash\":false,\"i18n\":{\"locales\":[\"en\"],\"defaultLocale\":\"en\"},\"productionBrowserSourceMaps\":false,\"optimizeFonts\":true,\"excludeDefaultMomentLocales\":true,\"serverRuntimeConfig\":{},\"publicRuntimeConfig\":{},\"reactStrictMode\":true,\"httpAgentOptions\":{\"keepAlive\":true},\"outputFileTracing\":true,\"staticPageGenerationTimeout\":60,\"swcMinify\":true,\"output\":\"standalone\",\"experimental\":{\"middlewarePrefetch\":\"flexible\",\"optimisticClientCache\":true,\"manualClientBasePath\":false,\"legacyBrowsers\":false,\"newNextLinkBehavior\":true,\"cpus\":7,\"sharedPool\":true,\"profiling\":false,\"isrFlushToDisk\":true,\"workerThreads\":false,\"pageEnv\":false,\"optimizeCss\":false,\"nextScriptWorkers\":false,\"scrollRestoration\":false,\"externalDir\":false,\"disableOptimizedLoading\":false,\"gzipSize\":true,\"swcFileReading\":true,\"craCompat\":false,\"esmExternals\":true,\"appDir\":false,\"isrMemoryCacheSize\":52428800,\"fullySpecified\":false,\"outputFileTracingRoot\":\"\",\"swcTraceProfiling\":false,\"forceSwcTransforms\":false,\"largePageDataBytes\":128000,\"enableUndici\":false,\"adjustFontFallbacks\":false,\"adjustFontFallbacksWithSizeAdjust\":false,\"trustHostHeader\":false},\"configFileName\":\"next.config.js\"},\n })\n handler = nextServer.getRequestHandler()\n\n console.log(\n 'Listening on port',\n currentPort,\n 'url: http://localhost:' + currentPort\n )\n})\n\nAnd as you see it starts a http server not a https. Also this is why the console.log(\"lksdfjls\"); in your own server.js will not get executed.\nWhat I would suggest is to leave node as it is, running on http://localhost:3000 and set up a reverse proxy that would forward incoming requests to this node backend that is accessible only from the reverse proxy. And of course reverse proxy would handle TLS termination. A docker compose setup would be more convenient for this so you could put the reverse proxy container (nginx for example) in the compose project too and map a directory from the docker host where your cert files are stored into the reverse proxy container at runtime - DO NOT BAKE CERTS OR ANY OTHER SECRETS INTO ANY IMAGE, not even if it is an internally used image only because it could leak out accidentally any time.\nAlso you could just manually run the two container with docker run but compose would make life easier it has a lot of capabilities for example you could scale compose services up and down so your backend service would run not in one but many containers. But if this would be a high load and/or business critical production stuff then you are better off with a better (real) container orchestrator like kubernetes, docker swarm, nomad etc but today as I see it the de facto container orchestrator is kubernetes.\n" ]
[ 0, 0 ]
[]
[]
[ "docker", "https", "javascript", "next.js", "node.js" ]
stackoverflow_0074622461_docker_https_javascript_next.js_node.js.txt
Q: JWT token expiration check I've a following utility class but whenever I check for an expired Token via verify method, it's not throwing the JWtVerificationException. public class Token { private static String SECRET = "c3bff416-993f-4760-9275-132b00256944"; public static String get(String name, String value) throws UnsupportedEncodingException { return JWT.create() .withIssuer("auth0") .withClaim(name, value) .withClaim("random", String.valueOf(UUID.randomUUID())) .withExpiresAt(new Date(System.currentTimeMillis() + (4 * 60 * 60 * 1000))) .sign(Algorithm.HMAC256(Token.SECRET)); } public static DecodedJWT verify(String token) throws JWTVerificationException, UnsupportedEncodingException { JWTVerifier verifier = JWT.require(Algorithm.HMAC256(Token.SECRET)) .withIssuer("auth0") .acceptExpiresAt(4) .build(); return verifier.verify(token); } } As per the website https://github.com/auth0/java-jwt When verifying a token the time validation occurs automatically, resulting in a JWTVerificationException being throw when the values are invalid. Edit: A case when client renewing token every 5 minutes, will following work or should I add few extra seconds to accommodate any network lag? creates .withExpiresAt(new Date(System.currentTimeMillis() + (5 * 60 * 1000))) // 5 minutes verify .acceptExpiresAt(5 * 60) // accept expiry of 5 minutes A: JWT.create().withExpiresAt(new Date(System.currentTimeMillis() + (5 * 60 * 1000))) means you will create a token, which will expire after 5 minutes. It seems good. JWT.require(xxx).acceptExpiresAt(5 * 60) means you will accept a token which has already expired 5 minutes before.Even considering the network lag, 5 minutes of leeway is still too long. It should in seconds. A: Just add separate catch block when verifying token try { DecodedJWT decodedJWT = Token.verify(); Map claims = decodedJWT.getClaims(); } catch (TokenExpiredException e) { // Token expired } catch (JWTVerificationException e) { // Token validation error } A: If the token has an invalid signature or the Claim requirement is not met, a JWTVerificationException will raise. When verifying a token the time validation occurs automatically, resulting in a JWTVerificationException being throw when the values are invalid. If any of the previous fields are missing they will not be considered in this validation. A: We can get expire time of a JWT with .expiresAt like this(in Unix Timestamp) : val jwtExample = JWT("your string token") jwtExample.expiresAt Then we can define a fun for evaluating JWT like this : private fun isJwtExpired(jwt: JWT): Boolean { val todayTime = (floor(Date(TimeUtil.getCurrentMillis()).time / 1000.0) * 1000).toLong() val pastToday = Date(todayTime) val expValid = jwt.expiresAt == null || !pastToday.after(jwt.expiresAt) return !expValid }
JWT token expiration check
I've a following utility class but whenever I check for an expired Token via verify method, it's not throwing the JWtVerificationException. public class Token { private static String SECRET = "c3bff416-993f-4760-9275-132b00256944"; public static String get(String name, String value) throws UnsupportedEncodingException { return JWT.create() .withIssuer("auth0") .withClaim(name, value) .withClaim("random", String.valueOf(UUID.randomUUID())) .withExpiresAt(new Date(System.currentTimeMillis() + (4 * 60 * 60 * 1000))) .sign(Algorithm.HMAC256(Token.SECRET)); } public static DecodedJWT verify(String token) throws JWTVerificationException, UnsupportedEncodingException { JWTVerifier verifier = JWT.require(Algorithm.HMAC256(Token.SECRET)) .withIssuer("auth0") .acceptExpiresAt(4) .build(); return verifier.verify(token); } } As per the website https://github.com/auth0/java-jwt When verifying a token the time validation occurs automatically, resulting in a JWTVerificationException being throw when the values are invalid. Edit: A case when client renewing token every 5 minutes, will following work or should I add few extra seconds to accommodate any network lag? creates .withExpiresAt(new Date(System.currentTimeMillis() + (5 * 60 * 1000))) // 5 minutes verify .acceptExpiresAt(5 * 60) // accept expiry of 5 minutes
[ "JWT.create().withExpiresAt(new Date(System.currentTimeMillis() + (5 * 60 * 1000)))\nmeans you will create a token, which will expire after 5 minutes. It seems good.\nJWT.require(xxx).acceptExpiresAt(5 * 60)\nmeans you will accept a token which has already expired 5 minutes before.Even considering the network lag, 5 minutes of leeway is still too long. It should in seconds.\n", "Just add separate catch block when verifying token\ntry {\n DecodedJWT decodedJWT = Token.verify();\n Map claims = decodedJWT.getClaims();\n\n} catch (TokenExpiredException e) {\n // Token expired \n} catch (JWTVerificationException e) {\n // Token validation error\n}\n\n", "If the token has an invalid signature or the Claim requirement is not met, a JWTVerificationException will raise.\nWhen verifying a token the time validation occurs automatically, resulting in a JWTVerificationException being throw when the values are invalid. If any of the previous fields are missing they will not be considered in this validation.\n", "We can get expire time of a JWT with .expiresAt like this(in Unix Timestamp) :\nval jwtExample = JWT(\"your string token\")\njwtExample.expiresAt\n\nThen we can define a fun for evaluating JWT like this :\nprivate fun isJwtExpired(jwt: JWT): Boolean {\n val todayTime =\n (floor(Date(TimeUtil.getCurrentMillis()).time / 1000.0) * 1000).toLong()\n val pastToday = Date(todayTime)\n val expValid = jwt.expiresAt == null || !pastToday.after(jwt.expiresAt)\n\n return !expValid\n}\n\n" ]
[ 5, 1, 0, 0 ]
[]
[]
[ "java", "jwt" ]
stackoverflow_0048177766_java_jwt.txt
Q: Create string with action name and all user inputs We are reviewing our logs to make it more effective for audit analysis, therefore we are trying to include the action name and all inputs applied each time by the user. Consider this sample code: public JsonResult SampleActionCode(int inputA, Guid inputB, bool inputC) { ... } So our code would be something similar to this added at that action: string actionName = this.ControllerContext.RouteData.Values["action"].ToString(); string userInputs = inputA.ToString() + " , " + inputB.ToString() + " , " + inputC.ToString(); string userExecuted = actionName + " , " + userInputs; //save to database How could we make a general code that would cycle all inputs available and concatenate those into a string, similar to userInputs shown? A: The query is stored in Request.QueryString, so you can iterate over its parts: var parts = new List<string>(); // using System.Collections.Generic foreach (var key in Request.QueryString.AllKeys) { parts.Add(Request.QueryString[key]); } string result = string.Join(", ", parts);
Create string with action name and all user inputs
We are reviewing our logs to make it more effective for audit analysis, therefore we are trying to include the action name and all inputs applied each time by the user. Consider this sample code: public JsonResult SampleActionCode(int inputA, Guid inputB, bool inputC) { ... } So our code would be something similar to this added at that action: string actionName = this.ControllerContext.RouteData.Values["action"].ToString(); string userInputs = inputA.ToString() + " , " + inputB.ToString() + " , " + inputC.ToString(); string userExecuted = actionName + " , " + userInputs; //save to database How could we make a general code that would cycle all inputs available and concatenate those into a string, similar to userInputs shown?
[ "The query is stored in Request.QueryString, so you can iterate over its parts:\nvar parts = new List<string>(); // using System.Collections.Generic\n\nforeach (var key in Request.QueryString.AllKeys) {\n parts.Add(Request.QueryString[key]);\n}\n\nstring result = string.Join(\", \", parts);\n\n" ]
[ 0 ]
[]
[]
[ "action", "asp.net_mvc", "c#", "controller" ]
stackoverflow_0074678271_action_asp.net_mvc_c#_controller.txt
Q: User Defined function problem (Language:Python) Write the definition of a user defined function PushA(N) which accepts a list of names in N and pushes all those names which have letter 'A' present in it ,into a list named OnlyA. Write a program in python to input 5 names and push them one by one into a list named AllNames. The program should then use the function PushA() to create a stack of names in the list OnlyA so that it stores only those names which have the letter 'A' from the list AllNames. Pop each name from the list OnlyA and display the popped Name and when the stack is empty display the message "EMPTY". For example: If the names input and pushed into the list AllNames are ['AARON','PENNY','TALON,'JOY'] Then stack OnlyA should store ['AARON','TALON'] And the output should be displayed as AARON PENNY TALON JOY I was unable to come up with a code for the above problem
User Defined function problem (Language:Python)
Write the definition of a user defined function PushA(N) which accepts a list of names in N and pushes all those names which have letter 'A' present in it ,into a list named OnlyA. Write a program in python to input 5 names and push them one by one into a list named AllNames. The program should then use the function PushA() to create a stack of names in the list OnlyA so that it stores only those names which have the letter 'A' from the list AllNames. Pop each name from the list OnlyA and display the popped Name and when the stack is empty display the message "EMPTY". For example: If the names input and pushed into the list AllNames are ['AARON','PENNY','TALON,'JOY'] Then stack OnlyA should store ['AARON','TALON'] And the output should be displayed as AARON PENNY TALON JOY I was unable to come up with a code for the above problem
[]
[]
[ "# Function to push names with 'A' into a list named OnlyA\n\ndef PushA(N):\n\n OnlyA = []\n\n for name in N:\n\n if 'A' in name.upper():\n\n OnlyA.append(name)\n\n return OnlyA\n\n# Main program\n\nAllNames = []\n\n" ]
[ -2 ]
[ "list", "python", "stack", "user_defined_functions" ]
stackoverflow_0074678774_list_python_stack_user_defined_functions.txt
Q: Enabling temporal variable for Image Mosaic in Geoserver I am working on creating a Image Mosaic to serve a set of geotiffs as a WMS. The data has temporal dimension as well. But unfortunately however I try, I cannot succed in enabling the time variable in the dimensions tab. I followed the following tutorials. https://geoserver.geo-solutions.it/multidim/multidim/get_started/index.html#geoserver-get-started http://www.orbital.co.ke:8080/opengeo-docs/geoserver/tutorials/imagemosaic_timeseries/imagemosaic_timeseries.html In both of these resources, it is clearly mentioned that "you should add the following switch when launching the Java process for GeoServer." The switches include "-Duser.timezone=GMT" "-Dorg.geotools.shapefile.datetime=true" But I can't find where to put these lines of code. I tried adding these lines on the catalina.bat file like the folowing, but it did not work anyways. set "JAVA_OPTS=%JAVA_OPTS% -Duser.timezone=GMT" set "JAVA_OPTS=%JAVA_OPTS% -Dorg.geotools.shapefile.datetime=true" Can someone help me to find the correct place to add these java switches? Thanks in advance!! EDIT1: File names are: 20200115T000000_geotiff_file_time 20200115T010000_geotiff_file_time 20200115T020000_geotiff_file_time 20200115T030000_geotiff_file_time Contents of the mosaic_data.properties which was automatically created. #-Automagically created from GeoTools- #Fri Feb 11 11:29:42 CET 2022 ExpandToRGB=false TypeName=snowLZWdataset Name=snowLZWdataset SuggestedSPI=it.geosolutions.imageioimpl.plugins.tiff.TIFFImageReaderSpi LevelsNum=1 PathType=RELATIVE Heterogeneous=false Caching=false HeterogeneousCRS=false LocationAttribute=location Levels=100.0,100.0 CheckAuxiliaryMetadata=false MosaicCRS=EPSG\:32632 A: You can try the tutorial below, worked for me with geotiff files. https://www.earder.com/tutorials/timeseries-with-geoserver-and-openlayers/
Enabling temporal variable for Image Mosaic in Geoserver
I am working on creating a Image Mosaic to serve a set of geotiffs as a WMS. The data has temporal dimension as well. But unfortunately however I try, I cannot succed in enabling the time variable in the dimensions tab. I followed the following tutorials. https://geoserver.geo-solutions.it/multidim/multidim/get_started/index.html#geoserver-get-started http://www.orbital.co.ke:8080/opengeo-docs/geoserver/tutorials/imagemosaic_timeseries/imagemosaic_timeseries.html In both of these resources, it is clearly mentioned that "you should add the following switch when launching the Java process for GeoServer." The switches include "-Duser.timezone=GMT" "-Dorg.geotools.shapefile.datetime=true" But I can't find where to put these lines of code. I tried adding these lines on the catalina.bat file like the folowing, but it did not work anyways. set "JAVA_OPTS=%JAVA_OPTS% -Duser.timezone=GMT" set "JAVA_OPTS=%JAVA_OPTS% -Dorg.geotools.shapefile.datetime=true" Can someone help me to find the correct place to add these java switches? Thanks in advance!! EDIT1: File names are: 20200115T000000_geotiff_file_time 20200115T010000_geotiff_file_time 20200115T020000_geotiff_file_time 20200115T030000_geotiff_file_time Contents of the mosaic_data.properties which was automatically created. #-Automagically created from GeoTools- #Fri Feb 11 11:29:42 CET 2022 ExpandToRGB=false TypeName=snowLZWdataset Name=snowLZWdataset SuggestedSPI=it.geosolutions.imageioimpl.plugins.tiff.TIFFImageReaderSpi LevelsNum=1 PathType=RELATIVE Heterogeneous=false Caching=false HeterogeneousCRS=false LocationAttribute=location Levels=100.0,100.0 CheckAuxiliaryMetadata=false MosaicCRS=EPSG\:32632
[ "You can try the tutorial below, worked for me with geotiff files.\nhttps://www.earder.com/tutorials/timeseries-with-geoserver-and-openlayers/\n" ]
[ 0 ]
[]
[]
[ "geoserver", "wms" ]
stackoverflow_0071078385_geoserver_wms.txt
Q: Is HTML Turing Complete? After reading this question Is CSS Turing complete? -- which received a few thoughtful, succinct answers -- it made me wonder: Is HTML Turing Complete? Although the short answer is a definitive Yes or No, please also provide a short description or counter-example to prove whether HTML is or is not Turing Complete (obviously it cannot be both). Information on other versions of HTML may be interesting, but the correct answer should answer this for HTML5. A: By itself (without CSS or JS), HTML (5 or otherwise) cannot possibly be Turing-complete because it is not a machine. Asking whether it is or not is essentially equivalent to asking whether an apple or an orange is Turing complete, or to take a more relevant example, a book. HTML is not something that "runs". It is a representation. It is a format. It is an information encoding. Not being a machine, it cannot compute anything on its own, at the level of Turing completeness or any other level. A: It seems clear to me that states and transitions can be represented in HTML with pages and hyperlinks, respectively. With this, one can implement deterministic finite automata where clicking links transitions between states. For example, I implemented a few simple DFA which are accessible here. DFA are much simpler that the Turing Machine though. To implement something closer to a TM, an additional mechanism involving reading and writing to memory would be necessary, besides the basic states/transitions functionality. However, HTML does not seem to have this kind of feature. So I would say HTML is not Turing-complete, but is able to simulate DFA. Edit1: I was reminded of the video On The Turing Completeness of PowerPoint when writing this answer. Edit2: complementing this answer with the DFA definition and clarification. Edit3: it might be worth mentioning that any machine in the real world is a finite-state machine due to reality's constraint of finite memory. So in a way, DFA can actually do anything that any real machine can do, as far as I know. See: https://en.wikipedia.org/wiki/Turing_machine#Comparison_with_real_machines Definition From https://en.wikipedia.org/wiki/Deterministic_finite_automaton#Formal_definition In the theory of computation, a branch of theoretical computer science, a deterministic finite automaton (DFA)—also known as deterministic finite acceptor (DFA), deterministic finite-state machine (DFSM), or deterministic finite-state automaton (DFSA)—is a finite-state machine that accepts or rejects a given string of symbols, by running through a state sequence uniquely determined by the string. A deterministic finite automaton M is a 5-tuple, (Q, Σ, δ, q0, F), consisting of a finite set of states Q a finite set of input symbols called the alphabet Σ a transition function δ : Q × Σ → Q an initial or start state q0 a set of accept states F The following example is of a DFA M, with a binary alphabet, which requires that the input contains an even number of 0s. M = (Q, Σ, δ, q0, F) where Q = {S1, S2} Σ = {0, 1} q0 = S1 F = {S1} and δ is defined by the following state transition table: 0 0 s1 s2 s1 s2 s1 s2 State diagram for M: The state S1 represents that there has been an even number of 0s in the input so far, while S2 signifies an odd number. A 1 in the input does not change the state of the automaton. When the input ends, the state will show whether the input contained an even number of 0s or not. If the input did contain an even number of 0s, M will finish in state S1, an accepting state, so the input string will be accepted. HTML implementation The DFA M exemplified above plus a few of the most basic DFA were implemented in Markdown and converted/hosted as HTML pages by Github, accessible here. Following the definition of M, its HTML implementation is detailed as follows. The set of states Q contains the pages s1.html and s2.html, and also the acceptance page acc.html and the rejection page rej.html. These two additional states are a "user-friendly" way to communicate the acceptance of a word and don't affect the semantics of the DFA. The set of symbols Σ is defined as the symbols 0 and 1. The empty string symbol ε was also included to denote the end of the input, leading to either acc.html or rej.html state. The initial state q0 is s1.html. The set of accept states is {acc.html}. The set of transitions is defined by hyperlinks such that page s1.html contains a link with text "0" leading to s2.html, a link with text "1" leading to s1.html, and a link with text "ε" leading to acc.html. Each page is analogous according to the following transition table. Obs: acc.html and rej.html don't contain links. 0 1 ε s1.html s2.html s1.html acc.html s2.html s1.html s2.html rej.html Questions In what ways are those HTML pages "machines"? Don't these machines include the browser and the person who clicks the links? In what way does a link perform computation? DFA is an abstract machine, i.e. a mathematical object. By the definition shown above, it is a tuple that defines transition rules between states according to a set of symbols. A real-world implementation of these rules (i.e. who keeps track of the current state, looks up the transition table and updates the current state accordingly) is then outside the scope of the definition. And for that matter, a Turing machine is a similar tuple with a few more elements to it. As described above, the HTML implementation represents the DFA M in full: every state and every transition is represented by a page and a link respectively. Browsers, clicks and CPUs are then irrelevant in the context of the DFA. In other words, as written by @Not_Here in the comments: Rules don't innately implement themselves, they're just rules an implementation should follow. Consider it this way: Turing machines aren't actual machines, Turing didn't build machines. They're purely mathematical objects, they're tuples of sets (state, symbols) and a transition function between states. Turing machines are purely mathematical objects, they're sets of instructions for how to implement a computation, and so is this example in HTML. The Wikipedia article on abstract machines: An abstract machine, also called an abstract computer, is a theoretical computer used for defining a model of computation. Abstraction of computing processes is used in both the computer science and computer engineering disciplines and usually assumes a discrete time paradigm. In the theory of computation, abstract machines are often used in thought experiments regarding computability or to analyze the complexity of algorithms (see computational complexity theory). A typical abstract machine consists of a definition in terms of input, output, and the set of allowable operations used to turn the former into the latter. The best-known example is the Turing machine. A: Some have claimed to implement Rule 110, a cellular automaton, using pure HTML and CSS (no JavaScript). You can see a video here, or browse the source of one implementation. Why is this relevant? It has been proven that Rule 110 is itself Turing complete, meaning that it can simulate any Turing machine. If we then implement Rule 110 using pure HTML, it follows that HTML can simulate any Turing machine via its simulation of that particular cellular automaton. The critiques of this HTML "proof" focus on the fact that human input is required to drive the operation of the HTML machine. As seen in the video above, the human's input is constrained to a repeating pattern of Tab + Space (because the HTML machine consists of a series of checkboxes). Much as a Turing machine would require a clock signal and motive force to move its read/write head if it were to be implemented as a physical machine, the HTML machine needs energy input from the human -- but no information input, and crucially, no decision making. In summary: HTML is probably Turing-complete, as proven by construction.
Is HTML Turing Complete?
After reading this question Is CSS Turing complete? -- which received a few thoughtful, succinct answers -- it made me wonder: Is HTML Turing Complete? Although the short answer is a definitive Yes or No, please also provide a short description or counter-example to prove whether HTML is or is not Turing Complete (obviously it cannot be both). Information on other versions of HTML may be interesting, but the correct answer should answer this for HTML5.
[ "By itself (without CSS or JS), HTML (5 or otherwise) cannot possibly be Turing-complete because it is not a machine. Asking whether it is or not is essentially equivalent to asking whether an apple or an orange is Turing complete, or to take a more relevant example, a book.\nHTML is not something that \"runs\". It is a representation. It is a format. It is an information encoding. Not being a machine, it cannot compute anything on its own, at the level of Turing completeness or any other level. \n", "It seems clear to me that states and transitions can be represented in HTML with pages and hyperlinks, respectively. With this, one can implement deterministic finite automata where clicking links transitions between states. For example, I implemented a few simple DFA which are accessible here.\nDFA are much simpler that the Turing Machine though. To implement something closer to a TM, an additional mechanism involving reading and writing to memory would be necessary, besides the basic states/transitions functionality. However, HTML does not seem to have this kind of feature. So I would say HTML is not Turing-complete, but is able to simulate DFA.\nEdit1: I was reminded of the video On The Turing Completeness of PowerPoint when writing this answer.\nEdit2: complementing this answer with the DFA definition and clarification.\nEdit3: it might be worth mentioning that any machine in the real world is a finite-state machine due to reality's constraint of finite memory. So in a way, DFA can actually do anything that any real machine can do, as far as I know. See: https://en.wikipedia.org/wiki/Turing_machine#Comparison_with_real_machines\nDefinition\nFrom https://en.wikipedia.org/wiki/Deterministic_finite_automaton#Formal_definition\n\nIn the theory of computation, a branch of theoretical computer\nscience, a deterministic finite automaton (DFA)—also known as\ndeterministic finite acceptor (DFA), deterministic finite-state\nmachine (DFSM), or deterministic finite-state automaton (DFSA)—is a\nfinite-state machine that accepts or rejects a given string of\nsymbols, by running through a state sequence uniquely determined by\nthe string.\nA deterministic finite automaton M is a 5-tuple, (Q, Σ, δ, q0, F),\nconsisting of\n\na finite set of states Q\na finite set of input symbols called the alphabet Σ\na transition function δ : Q × Σ → Q\nan initial or start state q0\na set of accept states F\n\nThe following example is of a DFA M, with a binary alphabet, which\nrequires that the input contains an even number of 0s.\nM = (Q, Σ, δ, q0, F) where\n\nQ = {S1, S2}\nΣ = {0, 1}\nq0 = S1\nF = {S1} and\nδ is defined by the following state transition table:\n\n\n\n\n\n\n0\n0\n\n\n\n\ns1\ns2\ns1\n\n\ns2\ns1\ns2\n\n\n\n\nState diagram for M:\n\nThe state S1 represents that there has been an even number of 0s in\nthe input so far, while S2 signifies an odd number. A 1 in the input\ndoes not change the state of the automaton. When the input ends, the\nstate will show whether the input contained an even number of 0s or\nnot. If the input did contain an even number of 0s, M will finish in\nstate S1, an accepting state, so the input string will be accepted.\n\nHTML implementation\nThe DFA M exemplified above plus a few of the most basic DFA were implemented in Markdown and converted/hosted as HTML pages by Github, accessible here.\nFollowing the definition of M, its HTML implementation is detailed as follows.\n\nThe set of states Q contains the pages s1.html and s2.html, and also the acceptance page acc.html and the rejection page rej.html. These two additional states are a \"user-friendly\" way to communicate the acceptance of a word and don't affect the semantics of the DFA.\nThe set of symbols Σ is defined as the symbols 0 and 1. The empty string symbol ε was also included to denote the end of the input, leading to either acc.html or rej.html state.\nThe initial state q0 is s1.html.\nThe set of accept states is {acc.html}.\nThe set of transitions is defined by hyperlinks such that page s1.html contains a link with text \"0\" leading to s2.html, a link with text \"1\" leading to s1.html, and a link with text \"ε\" leading to acc.html. Each page is analogous according to the following transition table. Obs: acc.html and rej.html don't contain links.\n\n\n\n\n\n\n0\n1\nε\n\n\n\n\ns1.html\ns2.html\ns1.html\nacc.html\n\n\ns2.html\ns1.html\ns2.html\nrej.html\n\n\n\nQuestions\n\nIn what ways are those HTML pages \"machines\"? Don't these machines include the browser and the person who clicks the links? In what way does a link perform computation?\n\nDFA is an abstract machine, i.e. a mathematical object. By the definition shown above, it is a tuple that defines transition rules between states according to a set of symbols. A real-world implementation of these rules (i.e. who keeps track of the current state, looks up the transition table and updates the current state accordingly) is then outside the scope of the definition. And for that matter, a Turing machine is a similar tuple with a few more elements to it.\nAs described above, the HTML implementation represents the DFA M in full: every state and every transition is represented by a page and a link respectively. Browsers, clicks and CPUs are then irrelevant in the context of the DFA.\nIn other words, as written by @Not_Here in the comments:\n\nRules don't innately implement themselves, they're just rules an\nimplementation should follow. Consider it this way: Turing machines\naren't actual machines, Turing didn't build machines. They're purely\nmathematical objects, they're tuples of sets (state, symbols) and a\ntransition function between states. Turing machines are purely\nmathematical objects, they're sets of instructions for how to\nimplement a computation, and so is this example in HTML.\n\nThe Wikipedia article on abstract machines:\n\nAn abstract machine, also called an abstract computer, is a\ntheoretical computer used for defining a model of computation.\nAbstraction of computing processes is used in both the computer\nscience and computer engineering disciplines and usually assumes a\ndiscrete time paradigm.\nIn the theory of computation, abstract machines are often used in\nthought experiments regarding computability or to analyze the\ncomplexity of algorithms (see computational complexity theory). A\ntypical abstract machine consists of a definition in terms of input,\noutput, and the set of allowable operations used to turn the former\ninto the latter. The best-known example is the Turing machine.\n\n", "Some have claimed to implement Rule 110, a cellular automaton, using pure HTML and CSS (no JavaScript). You can see a video here, or browse the source of one implementation.\nWhy is this relevant? It has been proven that Rule 110 is itself Turing complete, meaning that it can simulate any Turing machine. If we then implement Rule 110 using pure HTML, it follows that HTML can simulate any Turing machine via its simulation of that particular cellular automaton.\nThe critiques of this HTML \"proof\" focus on the fact that human input is required to drive the operation of the HTML machine. As seen in the video above, the human's input is constrained to a repeating pattern of Tab + Space (because the HTML machine consists of a series of checkboxes). Much as a Turing machine would require a clock signal and motive force to move its read/write head if it were to be implemented as a physical machine, the HTML machine needs energy input from the human -- but no information input, and crucially, no decision making.\nIn summary: HTML is probably Turing-complete, as proven by construction.\n" ]
[ 38, 23, 0 ]
[]
[]
[ "html", "turing_complete" ]
stackoverflow_0030719221_html_turing_complete.txt
Q: how to validate inputs in a child component (formik) I generated Field in CustomField and call it in the CustomForm component. I want to validate each Customefield in itself with validateAsync but validateAsync is not working and meta. the error object is always empty. this is my CustomForm component: import { Field, Form, Formik, yupToFormErrors } from "formik"; import React, { Component } from "react"; import CustomField from "./customeField"; import * as Yup from "yup"; class CustomForm extends Component { state = {}; render() { return ( <Formik initialValues={{ name1: "", name2: "" }} onSubmit={(values) => { console.log(values); }} > <Form> <CustomField name="name1" lable="name1"></CustomField> <CustomField name="name2" lable="name2"></CustomField> <button type="submit">send</button> </Form> </Formik> ); } } export default CustomForm; and this is my CustomField component import React, { Component } from "react"; import { Field, Form, Formik, useField, ErrorMessage } from "formik"; import * as Yup from "yup"; const CustomField = ({ lable, ...props }) => { const [field, meta] = useField(props); const validateAsync = () => Yup.object({ name1: Yup.string().required("error"), }); return ( <div> <label htmlFor={props.id || props.name}>{lable}</label> <Field validate={validateAsync} {...field} {...props} /> {meta.touched && meta.error ? ( <div className="error">{meta.error}</div> ) : ( <div className="error"></div> )} </div> ); }; export default CustomField; A: there are two problems in your code, the first one is how you use the Yup for validation and the second problem is about that validateAsync function, as Formik doc mentions you have to get input value from the first argument and as result, you can return undefined (which means there is no error) or a string (error message), BTW it's also possible to return a promise that indicates is input value valid or not. here is how you can go with this case: const CustomField = ({ label, name }: CustomFieldProps) => { const [field, meta] = useField({ name }); const validate = (x: string) => { const error_msg = "Error!!!"; try { Yup.string().required(error_msg).validateSync(x).toString(); } catch (error) { return error_msg; } }; return ( <div> <Field validate={validate} {...field} /> {meta.touched && meta.error && <div className="error">{meta.error}</div>} </div> ); }; p.s: here is the link of a working sample sandbox if you need a playground: https://codesandbox.io/s/formik-field-validate-rx3snh?file=/src/App.tsx:173-650
how to validate inputs in a child component (formik)
I generated Field in CustomField and call it in the CustomForm component. I want to validate each Customefield in itself with validateAsync but validateAsync is not working and meta. the error object is always empty. this is my CustomForm component: import { Field, Form, Formik, yupToFormErrors } from "formik"; import React, { Component } from "react"; import CustomField from "./customeField"; import * as Yup from "yup"; class CustomForm extends Component { state = {}; render() { return ( <Formik initialValues={{ name1: "", name2: "" }} onSubmit={(values) => { console.log(values); }} > <Form> <CustomField name="name1" lable="name1"></CustomField> <CustomField name="name2" lable="name2"></CustomField> <button type="submit">send</button> </Form> </Formik> ); } } export default CustomForm; and this is my CustomField component import React, { Component } from "react"; import { Field, Form, Formik, useField, ErrorMessage } from "formik"; import * as Yup from "yup"; const CustomField = ({ lable, ...props }) => { const [field, meta] = useField(props); const validateAsync = () => Yup.object({ name1: Yup.string().required("error"), }); return ( <div> <label htmlFor={props.id || props.name}>{lable}</label> <Field validate={validateAsync} {...field} {...props} /> {meta.touched && meta.error ? ( <div className="error">{meta.error}</div> ) : ( <div className="error"></div> )} </div> ); }; export default CustomField;
[ "there are two problems in your code, the first one is how you use the Yup for validation and the second problem is about that validateAsync function, as Formik doc mentions you have to get input value from the first argument and as result, you can return undefined (which means there is no error) or a string (error message), BTW it's also possible to return a promise that indicates is input value valid or not.\nhere is how you can go with this case:\nconst CustomField = ({ label, name }: CustomFieldProps) => {\n const [field, meta] = useField({ name });\n\n const validate = (x: string) => {\n const error_msg = \"Error!!!\";\n try {\n Yup.string().required(error_msg).validateSync(x).toString();\n } catch (error) {\n return error_msg;\n }\n };\n\n return (\n <div>\n <Field validate={validate} {...field} />\n {meta.touched && meta.error && <div className=\"error\">{meta.error}</div>}\n </div>\n );\n};\n\np.s: here is the link of a working sample sandbox if you need a playground:\nhttps://codesandbox.io/s/formik-field-validate-rx3snh?file=/src/App.tsx:173-650\n" ]
[ 0 ]
[]
[]
[ "formik", "reactjs" ]
stackoverflow_0074677015_formik_reactjs.txt
Q: Delete parent if no children in EF Core 7 Using EF Core 7 and .NET 7 (but also in previous versions), it is possible to delete all children of a one-to-many relationship in a SQL server database by configuring the delete behavior of the parent entity in the OnModelCreating-method in the class deriving from the DbContext-class, like this: protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder .Entity<Department>() .HasMany(d => d.Employees) .WithOne(e => e.Department) .OnDelete(DeleteBehavior.Cascade) } } But what if I want to delete the parent if all child entities are deleted? I've tried mapping a reversed delete pattern from the one above (see below), but to no success. modelBuilder.Entity<Employee>() .HasOne(e => e.Department) .WithMany(d => d.Employees) .OnDelete(DeleteBehavior.Cascade); A: ORM engines are inspired from the relational database management systems. Removing a parent when last child is removed is not a standard operation on a relation change in the DB engines. So EFCore does not support it to. At the database level you can use triggers to achieve what you want.
Delete parent if no children in EF Core 7
Using EF Core 7 and .NET 7 (but also in previous versions), it is possible to delete all children of a one-to-many relationship in a SQL server database by configuring the delete behavior of the parent entity in the OnModelCreating-method in the class deriving from the DbContext-class, like this: protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder .Entity<Department>() .HasMany(d => d.Employees) .WithOne(e => e.Department) .OnDelete(DeleteBehavior.Cascade) } } But what if I want to delete the parent if all child entities are deleted? I've tried mapping a reversed delete pattern from the one above (see below), but to no success. modelBuilder.Entity<Employee>() .HasOne(e => e.Department) .WithMany(d => d.Employees) .OnDelete(DeleteBehavior.Cascade);
[ "ORM engines are inspired from the relational database management systems. Removing a parent when last child is removed is not a standard operation on a relation change in the DB engines. So EFCore does not support it to. At the database level you can use triggers to achieve what you want.\n" ]
[ 2 ]
[]
[]
[ "c#", "entity_framework", "entity_framework_core" ]
stackoverflow_0074678813_c#_entity_framework_entity_framework_core.txt
Q: Why history listen is not updating my component's state? TLDR: I am building a React router app, I trying to update the state of my component through a history listener, this listener works fine I put a console.log and I can see it, but the state of my component is not changing, I can see this with the React chrome extension and my component is not updating. ` import React from "react"; import { withRouter } from "react-router-dom"; import { styles } from './Styles'; import { url } from './App'; class Searchresults extends React.Component { constructor(props) { super(props); this.state = { searchResults : [] } } async fetchResults(endpoint) { try { const response = await fetch(endpoint); if (response.ok) { const rJson = await response.json(); return rJson; } } catch (err) { console.log(err); } } componentDidMount() { this.searchUpdate(); this.unlisten = this.props.history.listen((location, action) => { console.log("it works!"); this.searchUpdate(); }) } searchUpdate = () => { const { location } = this.props; const params = new URLSearchParams(location); const query = params.get("search"); const name = query.replace("?name", "s"); const endpoint = url + "&" + name; this.fetchResults(endpoint).then(response => { return response['Search'].map(item => { return { title: item['Title'], poster: item['Poster'], id: item['imdbID'] } }) }).then(response => { this.setState({ searchResults : response }) }); } render() { return ( <div style={styles.movieList}> <ul> { !this.state.searchResults? 'Loading' : this.state.searchResults.map((item, index) => { return (<li key={index}> <a href={'/moviepage?id=' + item.id}>{item.title}</a><br /> <img src={item.poster} alt="Movie poster" style={{ width: "6rem", height: "auto" }} /> </li>) }) } </ul> </div> ); } } export default withRouter(Searchresults); ` I am trying to update the state with a method searchUpdate, then this method is called in componentDidMount, here works fine, then when the URL changes, the history.listen triggers and searchUpdate is fired again, and everything seems to work except the change of the state of my component. A: The first .then function in your searchResult function doesn't return a promise, so there is no need to use another .then. Just put the setState call in the same block: this.fetchResults(endpoint).then(response => { const searchResults = response['Search'].map(item => { return { title: item['Title'], poster: item['Poster'], id: item['imdbID'] } }); this.setState({searchResults}) });
Why history listen is not updating my component's state?
TLDR: I am building a React router app, I trying to update the state of my component through a history listener, this listener works fine I put a console.log and I can see it, but the state of my component is not changing, I can see this with the React chrome extension and my component is not updating. ` import React from "react"; import { withRouter } from "react-router-dom"; import { styles } from './Styles'; import { url } from './App'; class Searchresults extends React.Component { constructor(props) { super(props); this.state = { searchResults : [] } } async fetchResults(endpoint) { try { const response = await fetch(endpoint); if (response.ok) { const rJson = await response.json(); return rJson; } } catch (err) { console.log(err); } } componentDidMount() { this.searchUpdate(); this.unlisten = this.props.history.listen((location, action) => { console.log("it works!"); this.searchUpdate(); }) } searchUpdate = () => { const { location } = this.props; const params = new URLSearchParams(location); const query = params.get("search"); const name = query.replace("?name", "s"); const endpoint = url + "&" + name; this.fetchResults(endpoint).then(response => { return response['Search'].map(item => { return { title: item['Title'], poster: item['Poster'], id: item['imdbID'] } }) }).then(response => { this.setState({ searchResults : response }) }); } render() { return ( <div style={styles.movieList}> <ul> { !this.state.searchResults? 'Loading' : this.state.searchResults.map((item, index) => { return (<li key={index}> <a href={'/moviepage?id=' + item.id}>{item.title}</a><br /> <img src={item.poster} alt="Movie poster" style={{ width: "6rem", height: "auto" }} /> </li>) }) } </ul> </div> ); } } export default withRouter(Searchresults); ` I am trying to update the state with a method searchUpdate, then this method is called in componentDidMount, here works fine, then when the URL changes, the history.listen triggers and searchUpdate is fired again, and everything seems to work except the change of the state of my component.
[ "The first .then function in your searchResult function doesn't return a promise, so there is no need to use another .then. Just put the setState call in the same block:\nthis.fetchResults(endpoint).then(response => {\n const searchResults = response['Search'].map(item => {\n return { title: item['Title'], poster: item['Poster'], id: item['imdbID'] }\n });\n this.setState({searchResults})\n});\n\n" ]
[ 0 ]
[]
[]
[ "javascript", "react_router", "reactjs" ]
stackoverflow_0074678757_javascript_react_router_reactjs.txt
Q: How to Enable protected content in a webview? In chrome browser, there is an option to play protected content. How do I enable the same in webview in android? I have tried a method called allowContentAccess() but that does not work. Please help A: To allow a webview to play a DRM content you have to grant RESOURCE_PROTECTED_MEDIA_ID permission to the webview. You can do it by override of WebChromeClient#onPermissionRequest As a sample: @Override public void onPermissionRequest(PermissionRequest request) { String[] resources = request.getResources(); for (int i = 0; i < resources.length; i++) { if (PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID.equals(resources[i])) { request.grant(resources); return; } } super.onPermissionRequest(request); } A: setAllowContentAccess() (I couldn't find the allowContentAccess() you mentioned) is used for accessing local content files on the device, not for protected content. Protected content viewing enabling is usually controlled by the user, not the developer unfortunately. For example, for the default browser Chrome according to this help article: Chrome will play protected content by default. If you don't want Chrome to play protected content by default, you can change your settings: On your Android phone or tablet, open the Chrome app Chrome. To the right of the address bar, tap More More and then Settings. Tap Site settings and then Media and then Protected Content. Select Ask first. Since accessing protected content requires the site viewing information about your device, I expect this isn't available through a WebView. There is a full built-in framework available (since API level 11) for managing DRM content that should be used instead. A: Following Viacheslav's answer which works perfectly, here's the same snippet in Kotlin, to allow the WebView to play DRM content: override fun onPermissionRequest(request: PermissionRequest?) { request?.let { request -> if (request.resources.contains(PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID)) { request.grant(request.resources) return } } super.onPermissionRequest(request) }
How to Enable protected content in a webview?
In chrome browser, there is an option to play protected content. How do I enable the same in webview in android? I have tried a method called allowContentAccess() but that does not work. Please help
[ "To allow a webview to play a DRM content you have to grant RESOURCE_PROTECTED_MEDIA_ID permission to the webview.\nYou can do it by override of WebChromeClient#onPermissionRequest\nAs a sample:\n @Override\n public void onPermissionRequest(PermissionRequest request) {\n String[] resources = request.getResources();\n for (int i = 0; i < resources.length; i++) {\n if (PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID.equals(resources[i])) {\n request.grant(resources);\n return;\n }\n }\n\n super.onPermissionRequest(request);\n }\n\n", "setAllowContentAccess() (I couldn't find the allowContentAccess() you mentioned) is used for accessing local content files on the device, not for protected content.\nProtected content viewing enabling is usually controlled by the user, not the developer unfortunately. For example, for the default browser Chrome according to this help article:\n\nChrome will play protected content by default.\nIf you don't want Chrome to play protected content by default, you can\n change your settings:\n\nOn your Android phone or tablet, open the Chrome app Chrome.\nTo the right of the address bar, tap More More and then Settings.\nTap Site settings and then Media and then Protected Content.\nSelect Ask first.\n\n\nSince accessing protected content requires the site viewing information about your device, I expect this isn't available through a WebView.\nThere is a full built-in framework available (since API level 11) for managing DRM content that should be used instead.\n", "Following Viacheslav's answer which works perfectly, here's the same snippet in Kotlin, to allow the WebView to play DRM content:\n override fun onPermissionRequest(request: PermissionRequest?) {\n request?.let { request ->\n if (request.resources.contains(PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID)) {\n request.grant(request.resources)\n return\n }\n }\n\n super.onPermissionRequest(request)\n }\n\n" ]
[ 6, 0, 0 ]
[]
[]
[ "android", "webview" ]
stackoverflow_0053143363_android_webview.txt
Q: Python Flask Apache wsgi Not Wrking EDIT-1 - I was having import issues running the app with mod_wsgi and the command line, but I have resolved those. I still can't get the mod_wsgi part to work, as detailed below. EDIT-2 Now the mod_wsgi is loading the login page, but the sqlite db is complaining. And one import either works for mod_wsgi, or the command line invocation, depending on how it is written. EDIT-3 Fixed the sqlite error. Needed to have the full path to the db file in the factory. I still have the import issue as described below. I have a flask application (my first) in a rocket_launcher_flask/rocket_launcher and I can't seem to get the both the command line invocation and the wsgi connection to work with the same code base. The errors occur in two places. In the factory function in __init__.py I have this import: #from . import rocket_launcher # works for command line launch import rocket_launcher # works for wsgi app.register_blueprint(rocket_launcher.bp) If I just use the import rocket_launcher and run from the command line, I get this error: File "/home/mark/python-projects/rocket_launcher_flask/rocket_launcher/__init__.py", line 67, in create_app app.register_blueprint(rocket_launcher.bp) AttributeError: module 'rocket_launcher' has no attribute 'bp' But, if you look at the rocket_launcher.py file, bp is defined at the top of the file (complete file shown below): from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for, make_response ) bp = Blueprint('rocket_launcher', __name__) If I run the app using wsgi, the app works as expected. However, if I change the import to from . import rocket_launcher # works for command line launch #import rocket_launcher # works for wsgi app.register_blueprint(rocket_launcher.bp) and run from the command line, there are no errors and the app works as designed with no other code changes. However, running the app using this import and using wsgi yields this error: Sat Dec 03 16:11:59.368196 2022] [wsgi:error] [pid 1297960:tid 140355496306432] [client 192.168.25.15:57682] File "/home/mark/python-projects/rocket_launcher_flask/rocket_launcher/__init__.py", line 65, in create_app, referer: http://192.168.25.15/ [Sat Dec 03 16:11:59.368201 2022] [wsgi:error] [pid 1297960:tid 140355496306432] [client 192.168.25.15:57682] from . import rocket_launcher, referer: http://192.168.25.15/ [Sat Dec 03 16:11:59.368218 2022] [wsgi:error] [pid 1297960:tid 140355496306432] [client 192.168.25.15:57682] ImportError: attempted relative import with no known parent package, referer: http://192.168.25.15/ The app uses this invocation for the command line: #!/bin/bash export FLASK_APP=rocket_launcher export FLASK_ENV=development python -m flask run --host=0.0.0.0 My application has the following structure: ├── rocket_launcher_flask ├── instance ├── run.sh -- script (above) to run app from CLI ├── rocket_launcher.sqlite ├── rocket_launcher ├── auth.py ├── db.py ├── fsm.py ├── hardware.py ├── __init__.py ├── model.py ├── rocket_launcher_flask.wsgi ├── rocket_launcher.py ├── schema.sql ├── static ├── templates │   ├── <lots of templates> My new and improved rocket_launcher_flask.wsgi file: #! /home/mark/.virtualenvs/rocket_launcher_flask/bin/python import logging import sys logging.basicConfig(stream=sys.stderr) sys.path.insert(0, '/home/mark/python-projects/rocket_launcher_flask/rocket_launcher') #sys.path.insert(0, '/home/mark/.virtualenvs/rocket_launcher_flask/lib/python3.8/site-packages/') #sys.path.insert(0, '/home/mark/.virtualenvs/rocket_launcher_flask/bin/python') activate_this = '/home/mark/.virtualenvs/rocket_launcher_flask/bin/activate_this.py' with open(activate_this) as file_: exec(file_.read(), dict(__file__=activate_this)) logging.error("path=%s" % sys.path) from __init__ import create_app application = create_app() My __init__.py: import os from datetime import datetime from flask import Flask, redirect, url_for from flask_wtf.csrf import CSRFProtect global launcher import sys sys.path.insert(0, '/home/mark/python-projects/rocket_launcher_flask/rocket_launcher') sys.path.insert(0, '/home/mark/.virtualenvs/rocket_launcher_flask/lib/python3.8/site-packages/') sys.path.insert(0, '/home/mark/.virtualenvs/rocket_launcher_flask/bin/python') print("sys.path=%s" % sys.path) def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=False) app.config.from_mapping( DEBUG=False, SECRET_KEY=os.urandom(42), #b'\xc29\xe7\x98@\xc3\x12~\xde3\xed\nP\x1e\x8f\xcd', #created from python -c 'import os; print(os.urandom(16))' DATABASE=os.path.join(app.instance_path, '/full/path/to/rocket_launcher.sqlite'), ) if 'WINGDB_ACTIVE' in os.environ: app.debug = False csrf = CSRFProtect() csrf.init_app(app) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass @app.context_processor def get_copyright_years(): start = '2021' now = datetime.utcnow() end = str(now.year) return {'copyright_years': "%s - %s" % (start, end)} # a simple page that says hello @app.route('/hello') def hello(): return 'Hello, World!' from . import db db.init_app(app) from . import auth app.register_blueprint(auth.bp) app.add_url_rule('/', endpoint='auth.login') #import rocket_launcher # works for wsgi from . import rocket_launcher # works for command line app.register_blueprint(rocket_launcher.bp) from . import model app.register_blueprint(model.bp) from . import fsm app.register_blueprint(fsm.bp) return app My rocket_launcher.py - I removed most of the function bodies to keep things easier to read. import functools from fsm import launcher import hardware import logging from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for, make_response ) from werkzeug.exceptions import abort from auth import login_required, logout from db import get_db logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) bp = Blueprint('rocket_launcher', __name__) def create_safe_response(endpoint=None, template=None, **data): @bp.route('/connected', methods=('GET', 'POST')) @login_required def connected(): @bp.route('/armed', methods=('GET', 'POST')) @login_required #@valid_key_required def armed(): @bp.route('/ignition', methods=('GET', 'POST')) @login_required #@valid_key_required #@launch_initiated def ignition(): @bp.route('/ignition_timer_done', methods=('GET', 'POST')) @login_required def ignition_timer_done(): @bp.route('/admin', methods=('GET', 'POST')) @login_required def admin(): def get_continuity(test=False): Thanks for any suggestions you may have to fix my import problems! A: I am not sure this is the answer, but it is a workable solution. I changed the name of the the file rocket_launcher.py to controller.py and changed the appropriate references to rocket_launcher in the code to controller. I then changed the import in __init__.py to `import controller'. And voila, it works for both wsgi and command line invocations! I guess there were too many rocket_launcher references that pointed to different things, and python got confused?? A much more knowledgeable Pythonista will have to answer that question.
Python Flask Apache wsgi Not Wrking
EDIT-1 - I was having import issues running the app with mod_wsgi and the command line, but I have resolved those. I still can't get the mod_wsgi part to work, as detailed below. EDIT-2 Now the mod_wsgi is loading the login page, but the sqlite db is complaining. And one import either works for mod_wsgi, or the command line invocation, depending on how it is written. EDIT-3 Fixed the sqlite error. Needed to have the full path to the db file in the factory. I still have the import issue as described below. I have a flask application (my first) in a rocket_launcher_flask/rocket_launcher and I can't seem to get the both the command line invocation and the wsgi connection to work with the same code base. The errors occur in two places. In the factory function in __init__.py I have this import: #from . import rocket_launcher # works for command line launch import rocket_launcher # works for wsgi app.register_blueprint(rocket_launcher.bp) If I just use the import rocket_launcher and run from the command line, I get this error: File "/home/mark/python-projects/rocket_launcher_flask/rocket_launcher/__init__.py", line 67, in create_app app.register_blueprint(rocket_launcher.bp) AttributeError: module 'rocket_launcher' has no attribute 'bp' But, if you look at the rocket_launcher.py file, bp is defined at the top of the file (complete file shown below): from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for, make_response ) bp = Blueprint('rocket_launcher', __name__) If I run the app using wsgi, the app works as expected. However, if I change the import to from . import rocket_launcher # works for command line launch #import rocket_launcher # works for wsgi app.register_blueprint(rocket_launcher.bp) and run from the command line, there are no errors and the app works as designed with no other code changes. However, running the app using this import and using wsgi yields this error: Sat Dec 03 16:11:59.368196 2022] [wsgi:error] [pid 1297960:tid 140355496306432] [client 192.168.25.15:57682] File "/home/mark/python-projects/rocket_launcher_flask/rocket_launcher/__init__.py", line 65, in create_app, referer: http://192.168.25.15/ [Sat Dec 03 16:11:59.368201 2022] [wsgi:error] [pid 1297960:tid 140355496306432] [client 192.168.25.15:57682] from . import rocket_launcher, referer: http://192.168.25.15/ [Sat Dec 03 16:11:59.368218 2022] [wsgi:error] [pid 1297960:tid 140355496306432] [client 192.168.25.15:57682] ImportError: attempted relative import with no known parent package, referer: http://192.168.25.15/ The app uses this invocation for the command line: #!/bin/bash export FLASK_APP=rocket_launcher export FLASK_ENV=development python -m flask run --host=0.0.0.0 My application has the following structure: ├── rocket_launcher_flask ├── instance ├── run.sh -- script (above) to run app from CLI ├── rocket_launcher.sqlite ├── rocket_launcher ├── auth.py ├── db.py ├── fsm.py ├── hardware.py ├── __init__.py ├── model.py ├── rocket_launcher_flask.wsgi ├── rocket_launcher.py ├── schema.sql ├── static ├── templates │   ├── <lots of templates> My new and improved rocket_launcher_flask.wsgi file: #! /home/mark/.virtualenvs/rocket_launcher_flask/bin/python import logging import sys logging.basicConfig(stream=sys.stderr) sys.path.insert(0, '/home/mark/python-projects/rocket_launcher_flask/rocket_launcher') #sys.path.insert(0, '/home/mark/.virtualenvs/rocket_launcher_flask/lib/python3.8/site-packages/') #sys.path.insert(0, '/home/mark/.virtualenvs/rocket_launcher_flask/bin/python') activate_this = '/home/mark/.virtualenvs/rocket_launcher_flask/bin/activate_this.py' with open(activate_this) as file_: exec(file_.read(), dict(__file__=activate_this)) logging.error("path=%s" % sys.path) from __init__ import create_app application = create_app() My __init__.py: import os from datetime import datetime from flask import Flask, redirect, url_for from flask_wtf.csrf import CSRFProtect global launcher import sys sys.path.insert(0, '/home/mark/python-projects/rocket_launcher_flask/rocket_launcher') sys.path.insert(0, '/home/mark/.virtualenvs/rocket_launcher_flask/lib/python3.8/site-packages/') sys.path.insert(0, '/home/mark/.virtualenvs/rocket_launcher_flask/bin/python') print("sys.path=%s" % sys.path) def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=False) app.config.from_mapping( DEBUG=False, SECRET_KEY=os.urandom(42), #b'\xc29\xe7\x98@\xc3\x12~\xde3\xed\nP\x1e\x8f\xcd', #created from python -c 'import os; print(os.urandom(16))' DATABASE=os.path.join(app.instance_path, '/full/path/to/rocket_launcher.sqlite'), ) if 'WINGDB_ACTIVE' in os.environ: app.debug = False csrf = CSRFProtect() csrf.init_app(app) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass @app.context_processor def get_copyright_years(): start = '2021' now = datetime.utcnow() end = str(now.year) return {'copyright_years': "%s - %s" % (start, end)} # a simple page that says hello @app.route('/hello') def hello(): return 'Hello, World!' from . import db db.init_app(app) from . import auth app.register_blueprint(auth.bp) app.add_url_rule('/', endpoint='auth.login') #import rocket_launcher # works for wsgi from . import rocket_launcher # works for command line app.register_blueprint(rocket_launcher.bp) from . import model app.register_blueprint(model.bp) from . import fsm app.register_blueprint(fsm.bp) return app My rocket_launcher.py - I removed most of the function bodies to keep things easier to read. import functools from fsm import launcher import hardware import logging from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for, make_response ) from werkzeug.exceptions import abort from auth import login_required, logout from db import get_db logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) bp = Blueprint('rocket_launcher', __name__) def create_safe_response(endpoint=None, template=None, **data): @bp.route('/connected', methods=('GET', 'POST')) @login_required def connected(): @bp.route('/armed', methods=('GET', 'POST')) @login_required #@valid_key_required def armed(): @bp.route('/ignition', methods=('GET', 'POST')) @login_required #@valid_key_required #@launch_initiated def ignition(): @bp.route('/ignition_timer_done', methods=('GET', 'POST')) @login_required def ignition_timer_done(): @bp.route('/admin', methods=('GET', 'POST')) @login_required def admin(): def get_continuity(test=False): Thanks for any suggestions you may have to fix my import problems!
[ "I am not sure this is the answer, but it is a workable solution.\nI changed the name of the the file rocket_launcher.py to controller.py and changed the appropriate references to rocket_launcher in the code to controller.\nI then changed the import in __init__.py to `import controller'.\nAnd voila, it works for both wsgi and command line invocations!\nI guess there were too many rocket_launcher references that pointed to different things, and python got confused?? A much more knowledgeable Pythonista will have to answer that question.\n" ]
[ 0 ]
[]
[]
[ "flask", "mod_wsgi", "python" ]
stackoverflow_0074668973_flask_mod_wsgi_python.txt
Q: How to find the intersection of two or more strings on the commandline I frequently find myself renaming .flac-files in order to remove abundant information. I write a loop where I edit filenames by manually writing out the part that I want removed. E.g. I have a folder full of files like this: $ ls -l -rw-r--r-- 1 me me 315416376 Jan 6 2021 'Föllakzoid - 01 - I.flac' -rw-r--r-- 1 me me 250380814 Jan 6 2021 'Föllakzoid - 02 - II.flac' -rw-r--r-- 1 me me 336071410 Jan 6 2021 'Föllakzoid - 03 - III.flac' -rw-r--r-- 1 me me 258787367 Jan 6 2021 'Föllakzoid - 04 - IIII.flac' With the desired output being: $ ls -l -rw-r--r-- 1 me me 315416376 Jan 6 2021 '01 - I.flac' -rw-r--r-- 1 me me 250380814 Jan 6 2021 '02 - II.flac' -rw-r--r-- 1 me me 336071410 Jan 6 2021 '03 - III.flac' -rw-r--r-- 1 me me 258787367 Jan 6 2021 '04 - IIII.flac' Here I want to remove the "Föllakzoid - "-part from all of the files (as I that information is conveyed through a folder structure further up). Instead of manually typing $ for file in *.flac; do a=`echo "$file" | sed 's/Föllakzoid - //'`; mv "$file" "$a"; done I'd rather find the "Föllakzoid -"-part automatically and remove it from all files. Than I could abstract it into a script and re-use all the time (Thereby improving my bash-skills along the way). I found some similar questions here (on stackoverflow) but they deal with lists of items where order is not important. In my case I want to search for equal substrings in multiple longer strings: I am looking for a function that returns the intersection of multiple strings. So the order of letters is important (as opposed to other questions about list-intersections. Is there a simple tool in the riches of the depths of /usr/bin ? A: You might want to have a look at rename. It's not a standard utility but it's widely available on Linux. That said, you can also write your own function/script that works with literal globs (you'll loose the speed of remane though): The code was made in a jiffy so there're border cases that need to be addressed (it's not so easy to write something generic, flexible and robust at the same time) #!/bin/bash ren() { (( $# > 2 )) || return 1 local fpath for fpath in "${@:3}" do [[ $fpath =~ ^(.*/)?(.+)$ ]] || continue mv "$fpath" "${BASH_REMATCH[1]}${BASH_REMATCH[2]/$1/$2}" done } note: Here I used the bash parameter expansion ${var/glob/repl} that replaces the first occurrence of glob with repl, but there exists a few others that might prove useful; for example there's a ${var#glob} that strips the shortest left-side match of glob from $var (i.e. if $var expands to Föllakzoid - 01 - I.flac then ${var#* - } will expand to 01 - I.flac). Then you can use the function like this: ren 'w*d' 'guys' /path/file_hello_world.txt /passwd/www_domains.txt And that'll execute the commands: mv /path/file_hello_world.txt /path/file_hello_guys.txt mv /passwd/www_domains.txt /passwd/guysomains.txt A: The renameutils package's qmv command with a file glob will drop you into an editor to make the pattern change you want and will make the change you requested on exit. Good for the case where the use cases aren't 100% consistent and require a lot of special casing. May not be the best option, but still a good tool to have in one's grasp.
How to find the intersection of two or more strings on the commandline
I frequently find myself renaming .flac-files in order to remove abundant information. I write a loop where I edit filenames by manually writing out the part that I want removed. E.g. I have a folder full of files like this: $ ls -l -rw-r--r-- 1 me me 315416376 Jan 6 2021 'Föllakzoid - 01 - I.flac' -rw-r--r-- 1 me me 250380814 Jan 6 2021 'Föllakzoid - 02 - II.flac' -rw-r--r-- 1 me me 336071410 Jan 6 2021 'Föllakzoid - 03 - III.flac' -rw-r--r-- 1 me me 258787367 Jan 6 2021 'Föllakzoid - 04 - IIII.flac' With the desired output being: $ ls -l -rw-r--r-- 1 me me 315416376 Jan 6 2021 '01 - I.flac' -rw-r--r-- 1 me me 250380814 Jan 6 2021 '02 - II.flac' -rw-r--r-- 1 me me 336071410 Jan 6 2021 '03 - III.flac' -rw-r--r-- 1 me me 258787367 Jan 6 2021 '04 - IIII.flac' Here I want to remove the "Föllakzoid - "-part from all of the files (as I that information is conveyed through a folder structure further up). Instead of manually typing $ for file in *.flac; do a=`echo "$file" | sed 's/Föllakzoid - //'`; mv "$file" "$a"; done I'd rather find the "Föllakzoid -"-part automatically and remove it from all files. Than I could abstract it into a script and re-use all the time (Thereby improving my bash-skills along the way). I found some similar questions here (on stackoverflow) but they deal with lists of items where order is not important. In my case I want to search for equal substrings in multiple longer strings: I am looking for a function that returns the intersection of multiple strings. So the order of letters is important (as opposed to other questions about list-intersections. Is there a simple tool in the riches of the depths of /usr/bin ?
[ "You might want to have a look at rename. It's not a standard utility but it's widely available on Linux.\nThat said, you can also write your own function/script that works with literal globs (you'll loose the speed of remane though):\nThe code was made in a jiffy so there're border cases that need to be addressed (it's not so easy to write something generic, flexible and robust at the same time)\n#!/bin/bash\n\nren() {\n (( $# > 2 )) || return 1\n local fpath\n for fpath in \"${@:3}\"\n do\n [[ $fpath =~ ^(.*/)?(.+)$ ]] || continue\n mv \"$fpath\" \"${BASH_REMATCH[1]}${BASH_REMATCH[2]/$1/$2}\"\n done\n}\n\nnote: Here I used the bash parameter expansion ${var/glob/repl} that replaces the first occurrence of glob with repl, but there exists a few others that might prove useful; for example there's a ${var#glob} that strips the shortest left-side match of glob from $var (i.e. if $var expands to Föllakzoid - 01 - I.flac then ${var#* - } will expand to 01 - I.flac).\nThen you can use the function like this:\nren 'w*d' 'guys' /path/file_hello_world.txt /passwd/www_domains.txt\n\nAnd that'll execute the commands:\nmv /path/file_hello_world.txt /path/file_hello_guys.txt\nmv /passwd/www_domains.txt /passwd/guysomains.txt\n\n", "The renameutils package's qmv command with a file glob will drop you into an editor to make the pattern change you want and will make the change you requested on exit.\nGood for the case where the use cases aren't 100% consistent and require a lot of special casing.\nMay not be the best option, but still a good tool to have in one's grasp.\n" ]
[ 1, 0 ]
[]
[]
[ "bash", "comparison", "intersection", "string" ]
stackoverflow_0072736358_bash_comparison_intersection_string.txt
Q: I want to access information from another script but I get this error " Int does not contain a definition for TakeDamage" Unity This is the entire error 'int' does not contain a definition for 'TakeDamage' and no accessible extension method 'TakeDamage' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?) Here is the scrip from where I should take the information I wrote a text where I receive the error using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerStatus : MonoBehaviour { //health public int health; public int maxHealth = 10; //Damage int dmg = 4; //XP public int xp; public int LevelUp = 10; // Start is called before the first frame update void Start() { health = maxHealth; } // Update is called once per frame public void TakeDamage(int amount) { health -= amount; if(health <=0) { Destroy(gameObject); } } } Here is the script that should receive the information using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnmStatus : MonoBehaviour { public PlayerStatus playerHealth; public int damage = 2; //health public int health; public int maxHeath = 10; // Start is called before the first frame update void Start() { health = maxHeath; } // Update is called once per frame void Update() { } *//Down here I receive the error* private void OnMouseDown() { health.TakeDamage(damage); // if(health \>= 1) // { // playerHealth.TakeDamage(damage); // } } void TakeDamage(int amount) { health -= amount; if (health <= 0) { Destroy(gameObject); } } } It is suppose to decrease ENM health when I click on him, afterwards I want to decrease player health if ENM is still alive (Health >= 1) A: You are attempting to call .TakeDamage(damage) on an integer type instead of the PlayerStatus class referenced via the playerHealth variable. I assume that's the function you're attempting to call in this scenario. I'm assuming you have assigned a reference to PlayerStatus using the playerHealth variable, but just in case I've added a null check. You're welcome to omit it and shorten the below code to just: playerHealth.TakeDamage(damage); Alternatively, the full code would include the following: private void OnMouseDown() { /* * This could also be written in one line using a null conditional operator * playerHealth?.TakeDamage(damage); */ if(playerHealth != null) { playerHealth.TakeDamage(damage); } } If you're looking to call the TakeDamage function defined within your EnmStatus then you don't need to write health.TakeDamage(damage); TakeDamage(damage) would suffice since its locally scoped. But I'm not sure why you'd have the two duplicate functions. I would recommend brushing up on the basics of C# programming, perhaps through the Beginner Scripting Tutorials provided for free on Unity Learn
I want to access information from another script but I get this error " Int does not contain a definition for TakeDamage" Unity
This is the entire error 'int' does not contain a definition for 'TakeDamage' and no accessible extension method 'TakeDamage' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?) Here is the scrip from where I should take the information I wrote a text where I receive the error using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerStatus : MonoBehaviour { //health public int health; public int maxHealth = 10; //Damage int dmg = 4; //XP public int xp; public int LevelUp = 10; // Start is called before the first frame update void Start() { health = maxHealth; } // Update is called once per frame public void TakeDamage(int amount) { health -= amount; if(health <=0) { Destroy(gameObject); } } } Here is the script that should receive the information using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnmStatus : MonoBehaviour { public PlayerStatus playerHealth; public int damage = 2; //health public int health; public int maxHeath = 10; // Start is called before the first frame update void Start() { health = maxHeath; } // Update is called once per frame void Update() { } *//Down here I receive the error* private void OnMouseDown() { health.TakeDamage(damage); // if(health \>= 1) // { // playerHealth.TakeDamage(damage); // } } void TakeDamage(int amount) { health -= amount; if (health <= 0) { Destroy(gameObject); } } } It is suppose to decrease ENM health when I click on him, afterwards I want to decrease player health if ENM is still alive (Health >= 1)
[ "You are attempting to call .TakeDamage(damage) on an integer type instead of the PlayerStatus class referenced via the playerHealth variable. I assume that's the function you're attempting to call in this scenario.\nI'm assuming you have assigned a reference to PlayerStatus using the playerHealth variable, but just in case I've added a null check. You're welcome to omit it and shorten the below code to just:\nplayerHealth.TakeDamage(damage);\n\nAlternatively, the full code would include the following:\nprivate void OnMouseDown()\n{\n /*\n * This could also be written in one line using a null conditional operator\n * playerHealth?.TakeDamage(damage);\n */\n if(playerHealth != null)\n {\n playerHealth.TakeDamage(damage);\n }\n}\n\nIf you're looking to call the TakeDamage function defined within your EnmStatus then you don't need to write health.TakeDamage(damage); TakeDamage(damage) would suffice since its locally scoped. But I'm not sure why you'd have the two duplicate functions.\nI would recommend brushing up on the basics of C# programming, perhaps through the Beginner Scripting Tutorials provided for free on Unity Learn\n" ]
[ 0 ]
[]
[]
[ "c#", "unity3d", "visual_studio" ]
stackoverflow_0074678219_c#_unity3d_visual_studio.txt
Q: Android: How do you check if a particular AccessibilityService is enabled I've written an Android app that requires the use of the AccessibilityService. I know how to check to see if Accessibility is enabled or disabled on the phone, but I cannot work out a way to determine if my app has been specifically enabled within the accessibility menu. I'm wanting to prompt the user if the AccessibilityService is not running, but can't find a good way of doing this. Is there any API methods that I might be missing that would let me know which accessibility services are enabled on the device? A: Since API Level 14, it is also possible to obtain the enabled accessibility services through the AccessibilityManager: public static boolean isAccessibilityServiceEnabled(Context context, Class<? extends AccessibilityService> service) { AccessibilityManager am = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE); List<AccessibilityServiceInfo> enabledServices = am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK); for (AccessibilityServiceInfo enabledService : enabledServices) { ServiceInfo enabledServiceInfo = enabledService.getResolveInfo().serviceInfo; if (enabledServiceInfo.packageName.equals(context.getPackageName()) && enabledServiceInfo.name.equals(service.getName())) return true; } return false; } Usage: boolean enabled = isAccessibilityServiceEnabled(context, MyAccessibilityService.class); A: I worked this one out myself in the end: public boolean isAccessibilityEnabled() { int accessibilityEnabled = 0; final String LIGHTFLOW_ACCESSIBILITY_SERVICE = "com.example.test/com.example.text.ccessibilityService"; boolean accessibilityFound = false; try { accessibilityEnabled = Settings.Secure.getInt(this.getContentResolver(),android.provider.Settings.Secure.ACCESSIBILITY_ENABLED); Log.d(LOGTAG, "ACCESSIBILITY: " + accessibilityEnabled); } catch (SettingNotFoundException e) { Log.d(LOGTAG, "Error finding setting, default accessibility to not found: " + e.getMessage()); } TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':'); if (accessibilityEnabled==1) { Log.d(LOGTAG, "***ACCESSIBILIY IS ENABLED***: "); String settingValue = Settings.Secure.getString(getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES); Log.d(LOGTAG, "Setting: " + settingValue); if (settingValue != null) { TextUtils.SimpleStringSplitter splitter = mStringColonSplitter; splitter.setString(settingValue); while (splitter.hasNext()) { String accessabilityService = splitter.next(); Log.d(LOGTAG, "Setting: " + accessabilityService); if (accessabilityService.equalsIgnoreCase(ACCESSIBILITY_SERVICE_NAME)){ Log.d(LOGTAG, "We've found the correct setting - accessibility is switched on!"); return true; } } } Log.d(LOGTAG, "***END***"); } else { Log.d(LOGTAG, "***ACCESSIBILIY IS DISABLED***"); } return accessibilityFound; } A: Checking if the service is enabled /** * Based on {@link com.android.settingslib.accessibility.AccessibilityUtils#getEnabledServicesFromSettings(Context,int)} * @see <a href="https://github.com/android/platform_frameworks_base/blob/d48e0d44f6676de6fd54fd8a017332edd6a9f096/packages/SettingsLib/src/com/android/settingslib/accessibility/AccessibilityUtils.java#L55">AccessibilityUtils</a> */ public static boolean isAccessibilityServiceEnabled(Context context, Class<?> accessibilityService) { ComponentName expectedComponentName = new ComponentName(context, accessibilityService); String enabledServicesSetting = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES); if (enabledServicesSetting == null) return false; TextUtils.SimpleStringSplitter colonSplitter = new TextUtils.SimpleStringSplitter(':'); colonSplitter.setString(enabledServicesSetting); while (colonSplitter.hasNext()) { String componentNameString = colonSplitter.next(); ComponentName enabledService = ComponentName.unflattenFromString(componentNameString); if (enabledService != null && enabledService.equals(expectedComponentName)) return true; } return false; } Usage: boolean enabled = isAccessibilityServiceEnabled(context, MyAccessibilityService.class); Detecting when the service is enabled or disabled Make a callback: ContentObserver observer = new ContentObserver() { @Override public void onChange(boolean selfChange) { super.onChange(selfChange); boolean accessibilityServiceEnabled = isAccessibilityServiceEnabled(context, MyAccessibilityService.class); //Do something here } }; Subscribe: Uri uri = Settings.Secure.getUriFor(Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES); context.getContentResolver().registerContentObserver(uri, false, observer); Unsubscribe when you're done: context.getContentResolver().unregisterContentObserver(observer); Note that this doesn't work with the getEnabledAccessibilityServiceList() approach since its values are out-of-sync with the Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES values. That's why I think using Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES is a better one-size-fits-all approach. A: Get the ID when your activity service just started. In your Activity service OnSeriviceCeonnected after all the initialize calls. Use this... AccessibilityServiceInfo serviceInfo = this.getServiceInfo(); String accessibilityId = serviceInfo.getId(); Requires Jelly Bean API Then you can use Martin's code (isAccessibilityEnabled) to check running services. A: Maybe's too late but here's how I check the Accessibility Service's status: $ adb shell dumpsys accessibility Result: ACCESSIBILITY MANAGER (dumpsys accessibility) User state[attributes:{id=0, currentUser=true, accessibilityEnabled=false, touchExplorationEnabled=false, displayMagnificationEnabled=false} services:{}] A: I was looking for the same solution and decided to do this check in my AccessabilityService. It works for me and maybe will be helpful for somebody else. class AppConnectorService : AccessibilityService() { companion object { val connected = MutableStateFlow(false) } override fun onAccessibilityEvent(event: AccessibilityEvent?) { Timber.d("!!! $event") } override fun onInterrupt() { TODO("Not yet implemented") } override fun onServiceConnected() { super.onServiceConnected() connected.tryEmit(true) Timber.d("!!! AccessibilityService is connected!!!!!") } override fun onDestroy() { super.onDestroy() connected.tryEmit(false) Timber.d("!!! AccessibilityService is destroyed!!!!") } } And to check and listen for changes just use. In Compose: val isConnected by AppConnectorService.connected.collectAsState() or coroutine: coroutineScope.launch { AppConnectorService.connected.collect { } } A: A good solution I've come up with is to run your AccessibilityService in a separate process. You can add an android:process attribute in the manifest, e.g. <service android:name=".ExampleService" android:process="com.example.service" ... Now your service will be running in a separate process with the given name. From your app you can call val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager activityManager.runningAppProcesses.any { it.processName == "com.example.service" } Which will return true if the service is running and false otherwise. IMPORTANT: note that it will show you when your service was started, but when you disable it (meaning, after system unbinds from it) the process can still be alive. So you can simply force it's removal: override fun onUnbind(intent: Intent?): Boolean { stopSelf() return super.onUnbind(intent) } override fun onDestroy() { super.onDestroy() killProcess(Process.myPid()) } Then it works perfectly. I see this method more robust than reading values from settings, because it shows the exact thing needed: whether the service is running or not.
Android: How do you check if a particular AccessibilityService is enabled
I've written an Android app that requires the use of the AccessibilityService. I know how to check to see if Accessibility is enabled or disabled on the phone, but I cannot work out a way to determine if my app has been specifically enabled within the accessibility menu. I'm wanting to prompt the user if the AccessibilityService is not running, but can't find a good way of doing this. Is there any API methods that I might be missing that would let me know which accessibility services are enabled on the device?
[ "Since API Level 14, it is also possible to obtain the enabled accessibility services through the AccessibilityManager:\npublic static boolean isAccessibilityServiceEnabled(Context context, Class<? extends AccessibilityService> service) {\n AccessibilityManager am = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);\n List<AccessibilityServiceInfo> enabledServices = am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK);\n\n for (AccessibilityServiceInfo enabledService : enabledServices) {\n ServiceInfo enabledServiceInfo = enabledService.getResolveInfo().serviceInfo;\n if (enabledServiceInfo.packageName.equals(context.getPackageName()) && enabledServiceInfo.name.equals(service.getName()))\n return true;\n }\n\n return false;\n}\n\nUsage:\nboolean enabled = isAccessibilityServiceEnabled(context, MyAccessibilityService.class);\n\n", "I worked this one out myself in the end:\npublic boolean isAccessibilityEnabled() {\n int accessibilityEnabled = 0;\n final String LIGHTFLOW_ACCESSIBILITY_SERVICE = \"com.example.test/com.example.text.ccessibilityService\";\n boolean accessibilityFound = false;\n try {\n accessibilityEnabled = Settings.Secure.getInt(this.getContentResolver(),android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);\n Log.d(LOGTAG, \"ACCESSIBILITY: \" + accessibilityEnabled);\n } catch (SettingNotFoundException e) {\n Log.d(LOGTAG, \"Error finding setting, default accessibility to not found: \" + e.getMessage());\n }\n\n TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');\n\n if (accessibilityEnabled==1) {\n Log.d(LOGTAG, \"***ACCESSIBILIY IS ENABLED***: \");\n\n String settingValue = Settings.Secure.getString(getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);\n Log.d(LOGTAG, \"Setting: \" + settingValue);\n if (settingValue != null) {\n TextUtils.SimpleStringSplitter splitter = mStringColonSplitter;\n splitter.setString(settingValue);\n while (splitter.hasNext()) {\n String accessabilityService = splitter.next();\n Log.d(LOGTAG, \"Setting: \" + accessabilityService);\n if (accessabilityService.equalsIgnoreCase(ACCESSIBILITY_SERVICE_NAME)){\n Log.d(LOGTAG, \"We've found the correct setting - accessibility is switched on!\");\n return true;\n }\n }\n }\n\n Log.d(LOGTAG, \"***END***\");\n }\n else {\n Log.d(LOGTAG, \"***ACCESSIBILIY IS DISABLED***\");\n }\n return accessibilityFound;\n}\n\n", "Checking if the service is enabled\n/**\n * Based on {@link com.android.settingslib.accessibility.AccessibilityUtils#getEnabledServicesFromSettings(Context,int)}\n * @see <a href=\"https://github.com/android/platform_frameworks_base/blob/d48e0d44f6676de6fd54fd8a017332edd6a9f096/packages/SettingsLib/src/com/android/settingslib/accessibility/AccessibilityUtils.java#L55\">AccessibilityUtils</a>\n */\npublic static boolean isAccessibilityServiceEnabled(Context context, Class<?> accessibilityService) {\n ComponentName expectedComponentName = new ComponentName(context, accessibilityService);\n\n String enabledServicesSetting = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);\n if (enabledServicesSetting == null)\n return false;\n\n TextUtils.SimpleStringSplitter colonSplitter = new TextUtils.SimpleStringSplitter(':');\n colonSplitter.setString(enabledServicesSetting);\n\n while (colonSplitter.hasNext()) {\n String componentNameString = colonSplitter.next();\n ComponentName enabledService = ComponentName.unflattenFromString(componentNameString);\n\n if (enabledService != null && enabledService.equals(expectedComponentName))\n return true;\n }\n\n return false;\n}\n\nUsage:\nboolean enabled = isAccessibilityServiceEnabled(context, MyAccessibilityService.class);\n\nDetecting when the service is enabled or disabled\nMake a callback:\nContentObserver observer = new ContentObserver() {\n @Override\n public void onChange(boolean selfChange) {\n super.onChange(selfChange);\n boolean accessibilityServiceEnabled = isAccessibilityServiceEnabled(context, MyAccessibilityService.class);\n //Do something here\n }\n};\n\nSubscribe:\nUri uri = Settings.Secure.getUriFor(Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);\ncontext.getContentResolver().registerContentObserver(uri, false, observer);\n\nUnsubscribe when you're done:\ncontext.getContentResolver().unregisterContentObserver(observer);\n\nNote that this doesn't work with the getEnabledAccessibilityServiceList() approach since its values are out-of-sync with the Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES values. That's why I think using Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES is a better one-size-fits-all approach.\n", "Get the ID when your activity service just started.\nIn your Activity service OnSeriviceCeonnected after all the initialize calls. Use this...\nAccessibilityServiceInfo serviceInfo = this.getServiceInfo();\n String accessibilityId = serviceInfo.getId();\n\nRequires Jelly Bean API\nThen you can use Martin's code (isAccessibilityEnabled) to check running services.\n", "Maybe's too late but here's how I check the Accessibility Service's status:\n$ adb shell dumpsys accessibility\n\nResult:\nACCESSIBILITY MANAGER (dumpsys accessibility)\nUser state[attributes:{id=0, currentUser=true, accessibilityEnabled=false, touchExplorationEnabled=false, displayMagnificationEnabled=false}\n services:{}]\n\n", "I was looking for the same solution and decided to do this check in my AccessabilityService. It works for me and maybe will be helpful for somebody else.\nclass AppConnectorService : AccessibilityService() {\n\n companion object {\n val connected = MutableStateFlow(false)\n }\n\n override fun onAccessibilityEvent(event: AccessibilityEvent?) {\n Timber.d(\"!!! $event\")\n }\n\n override fun onInterrupt() {\n TODO(\"Not yet implemented\")\n }\n\n override fun onServiceConnected() {\n super.onServiceConnected()\n connected.tryEmit(true)\n Timber.d(\"!!! AccessibilityService is connected!!!!!\")\n }\n\n override fun onDestroy() {\n super.onDestroy()\n connected.tryEmit(false)\n Timber.d(\"!!! AccessibilityService is destroyed!!!!\")\n }\n}\n\nAnd to check and listen for changes just use. In Compose:\nval isConnected by AppConnectorService.connected.collectAsState()\n\nor coroutine:\ncoroutineScope.launch {\n AppConnectorService.connected.collect {\n \n }\n}\n\n", "A good solution I've come up with is to run your AccessibilityService in a separate process. You can add an android:process attribute in the manifest, e.g.\n<service\n android:name=\".ExampleService\"\n android:process=\"com.example.service\"\n ...\n\nNow your service will be running in a separate process with the given name. From your app you can call\nval activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager\nactivityManager.runningAppProcesses.any { it.processName == \"com.example.service\" }\n\nWhich will return true if the service is running and false otherwise.\nIMPORTANT: note that it will show you when your service was started, but when you disable it (meaning, after system unbinds from it) the process can still be alive. So you can simply force it's removal:\noverride fun onUnbind(intent: Intent?): Boolean {\n stopSelf()\n return super.onUnbind(intent)\n}\n\noverride fun onDestroy() {\n super.onDestroy()\n killProcess(Process.myPid())\n}\n\nThen it works perfectly. I see this method more robust than reading values from settings, because it shows the exact thing needed: whether the service is running or not.\n" ]
[ 68, 67, 35, 2, 1, 0, 0 ]
[ " AccessibilityManager accessibilityManager = (AccessibilityManager)context.getSystemService(Context.ACCESSIBILITY_SERVICE);\n List<AccessibilityServiceInfo> runningservice = accessibilityManager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK);\n\n accessibilityManager.addAccessibilityStateChangeListener(new AccessibilityManager.AccessibilityStateChangeListener() {\n @Override\n public void onAccessibilityStateChanged(boolean b) {\n Toast.makeText(MainActivity.this, \"permission \"+b, Toast.LENGTH_SHORT).show();\n }\n });\n\n\nListner will be called whenever state is changed \nyou can keep track of the boolean to check the permission\nthis is by far the simplest and lightest solution to check permission\n", "this need more times\nAccessibilityManager am = (AccessibilityManager) context\n .getSystemService(Context.ACCESSIBILITY_SERVICE);\n\n" ]
[ -1, -5 ]
[ "accessibility_api", "android" ]
stackoverflow_0005081145_accessibility_api_android.txt
Q: MariaDB table with UUID primary key as BINARY(16) NOT NULL I want to use BINARY UUIDs as my primary key in my tables, but using my own custom functions that generates optimised UUIDs loosely based on this article: https://mariadb.com/kb/en/guiduuid-performance/ The table structure and two main functions of interest here are: CREATE TABLE `Test` ( `Id` BINARY(16), `Data` VARCHAR(100) ) ENGINE=InnoDB ROW_FORMAT=DYNAMIC CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'; CREATE DEFINER = 'user'@'%' FUNCTION `OPTIMISE_UUID_STR`(`_uuid` VARCHAR(36)) RETURNS VARCHAR(32) CHARACTER SET utf8mb4 DETERMINISTIC NO SQL SQL SECURITY INVOKER COMMENT '' BEGIN /* FROM 00 10 20 30 123456789012345678901234567890123456 ==================================== AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE TO 00 10 20 30 12345678901234567890123456789012 ================================ CCCCBBBBAAAAAAAADDDDEEEEEEEEEEEE */ RETURN UCASE(CONCAT( SUBSTR(_uuid, 15, 4), /* Time nodes reversed */ SUBSTR(_uuid, 10, 4), SUBSTR(_uuid, 1, 8), SUBSTR(_uuid, 20, 4), /* MAC nodes last */ SUBSTR(_uuid, 25, 12))); END; CREATE DEFINER = 'user'@'%' FUNCTION `CONVERT_OPTIMISED_UUID_STR_TO_BIN`(`_hexstr` BINARY(32)) RETURNS BINARY(16) DETERMINISTIC NO SQL SQL SECURITY INVOKER COMMENT '' BEGIN /* Convert optimised UUID from string hex representation to binary. If the UUID is not optimised, it makes no sense to convert */ RETURN UNHEX(_hexstr); END; I cannot use my custom functions in column definition as shown below CREATE TABLE `Test` ( `Id` BINARY(16) NOT NULL DEFAULT CONVERT_OPTIMISED_UUID_STR_TO_BIN(OPTIMISE_UUID_STR(UUID())), I get the error "Function or expression 'OPTIMISE_UUID_STR()' cannot be used in the DEFAULT clause of Id" So I tried using the same in Triggers: CREATE DEFINER = 'user'@'%' TRIGGER `Test_before_ins_tr1` BEFORE INSERT ON `Test` FOR EACH ROW BEGIN IF (new.Id IS NULL) OR (new.Id = X'0000000000000000') OR (new.Id = X'FFFFFFFFFFFFFFFF') THEN SET new.Id = CONVERT_OPTIMISED_UUID_STR_TO_BIN(OPTIMISE_UUID_STR(UUID())); END IF; END; The above works pretty good, but the issue is that I cannot define the Id column as PRIMARY KEY, which I want to because PRIMARY KEYs have to be NOT NULL, and setting this means I have to pre-generate optimised UUIDs. I do not want to do this as I would like the DB to take care of generating the optimised UUIDs. As you might have inferred looking at the above Trigger definition, I tried setting a default value on the Id column, such as: Id` BINARY(16) NOT NULL DEFAULT X'0000000000000000' and Id` BINARY(16) NOT NULL DEFAULT X'FFFFFFFFFFFFFFFF' and Id` BINARY(16) NOT NULL DEFAULT '0' /* I tried setting 0, but always seem to revert to '0' */ and this default value would be picked up by the trigger and a correct optimised UUID assigned. But that also does not work as the DB complains "Column 'Id' cannot be null" even though a DEFAULT value has been set. So my actual question is: Can I generate a custom (optimised UUID) BINARY value for a PRIMARY KEY column? A: Short answer: Yes Long answer: The PRIMARY KEY can be almost any datatype with whatever values you can create. TEXT or BLOB are not allowed. Not even TINYTEXT. VARCHAR (etc) are not allowed beyond some size (depends on version and CHARACTER SET). VARCHAR(191) (or smaller) works in all combinations. The ubiquitous VARCHAR(255) works in many situations. MySQL 8.0 has builtin functions for converting between binary and string UUIDs. This also provides functions (like yours) for such: UUIDs A: Yes, it's doable even without triggers and/or stored functions: MariaDB from version 10.6: Use function SYS_GUID() which returns same result as UUID() but without - characters. The result of this function can be directly converted to a 16-byte value with UNHEX() function. Example: CREATE TABLE test (a BINARY(16) NOT NULL DEFAULT UNHEX(SYS_GUID()) PRIMARY KEY); INSERT INTO test VALUES (DEFAULT); INSERT INTO test VALUES (DEFAULT); SELECT HEX(a) FROM test; +----------------------------------+ | HEX(a) | +----------------------------------+ | 53EE84FB733911EDA238D83BBF89F2E2 | | 61AC0286733911EDA238D83BBF89F2E2 | +----------------------------------+ MariaDB from version 10.7 (as mentioned in danielblack's comment): Use UUID datatype which stores UUID() (and SYS_GUID()) values as 16 byte: CREATE TABLE test (a UUID not NULL default UUID() PRIMARY KEY); INSERT INTO test VALUES (DEFAULT); INSERT INTO test VALUES (DEFAULT); SELECT a FROM test; +--------------------------------------+ | a | +--------------------------------------+ | 6c42e367-733b-11ed-a238-d83bbf89f2e2 | | 6cbc0418-733b-11ed-a238-d83bbf89f2e2 | +--------------------------------------+ Addendum: If you are using a version < 10.6 and your requirements match the following limitations, you could also use UUID_SHORT() function, which generates a 64-bit identifier.
MariaDB table with UUID primary key as BINARY(16) NOT NULL
I want to use BINARY UUIDs as my primary key in my tables, but using my own custom functions that generates optimised UUIDs loosely based on this article: https://mariadb.com/kb/en/guiduuid-performance/ The table structure and two main functions of interest here are: CREATE TABLE `Test` ( `Id` BINARY(16), `Data` VARCHAR(100) ) ENGINE=InnoDB ROW_FORMAT=DYNAMIC CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'; CREATE DEFINER = 'user'@'%' FUNCTION `OPTIMISE_UUID_STR`(`_uuid` VARCHAR(36)) RETURNS VARCHAR(32) CHARACTER SET utf8mb4 DETERMINISTIC NO SQL SQL SECURITY INVOKER COMMENT '' BEGIN /* FROM 00 10 20 30 123456789012345678901234567890123456 ==================================== AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE TO 00 10 20 30 12345678901234567890123456789012 ================================ CCCCBBBBAAAAAAAADDDDEEEEEEEEEEEE */ RETURN UCASE(CONCAT( SUBSTR(_uuid, 15, 4), /* Time nodes reversed */ SUBSTR(_uuid, 10, 4), SUBSTR(_uuid, 1, 8), SUBSTR(_uuid, 20, 4), /* MAC nodes last */ SUBSTR(_uuid, 25, 12))); END; CREATE DEFINER = 'user'@'%' FUNCTION `CONVERT_OPTIMISED_UUID_STR_TO_BIN`(`_hexstr` BINARY(32)) RETURNS BINARY(16) DETERMINISTIC NO SQL SQL SECURITY INVOKER COMMENT '' BEGIN /* Convert optimised UUID from string hex representation to binary. If the UUID is not optimised, it makes no sense to convert */ RETURN UNHEX(_hexstr); END; I cannot use my custom functions in column definition as shown below CREATE TABLE `Test` ( `Id` BINARY(16) NOT NULL DEFAULT CONVERT_OPTIMISED_UUID_STR_TO_BIN(OPTIMISE_UUID_STR(UUID())), I get the error "Function or expression 'OPTIMISE_UUID_STR()' cannot be used in the DEFAULT clause of Id" So I tried using the same in Triggers: CREATE DEFINER = 'user'@'%' TRIGGER `Test_before_ins_tr1` BEFORE INSERT ON `Test` FOR EACH ROW BEGIN IF (new.Id IS NULL) OR (new.Id = X'0000000000000000') OR (new.Id = X'FFFFFFFFFFFFFFFF') THEN SET new.Id = CONVERT_OPTIMISED_UUID_STR_TO_BIN(OPTIMISE_UUID_STR(UUID())); END IF; END; The above works pretty good, but the issue is that I cannot define the Id column as PRIMARY KEY, which I want to because PRIMARY KEYs have to be NOT NULL, and setting this means I have to pre-generate optimised UUIDs. I do not want to do this as I would like the DB to take care of generating the optimised UUIDs. As you might have inferred looking at the above Trigger definition, I tried setting a default value on the Id column, such as: Id` BINARY(16) NOT NULL DEFAULT X'0000000000000000' and Id` BINARY(16) NOT NULL DEFAULT X'FFFFFFFFFFFFFFFF' and Id` BINARY(16) NOT NULL DEFAULT '0' /* I tried setting 0, but always seem to revert to '0' */ and this default value would be picked up by the trigger and a correct optimised UUID assigned. But that also does not work as the DB complains "Column 'Id' cannot be null" even though a DEFAULT value has been set. So my actual question is: Can I generate a custom (optimised UUID) BINARY value for a PRIMARY KEY column?
[ "Short answer: Yes\nLong answer:\nThe PRIMARY KEY can be almost any datatype with whatever values you can create.\n\nTEXT or BLOB are not allowed. Not even TINYTEXT.\nVARCHAR (etc) are not allowed beyond some size (depends on version and CHARACTER SET). VARCHAR(191) (or smaller) works in all combinations. The ubiquitous VARCHAR(255) works in many situations.\n\nMySQL 8.0 has builtin functions for converting between binary and string UUIDs. This also provides functions (like yours) for such: UUIDs\n", "Yes, it's doable even without triggers and/or stored functions:\nMariaDB from version 10.6:\nUse function SYS_GUID() which returns same result as UUID() but without - characters. The result of this function can be directly converted to a 16-byte value with UNHEX() function.\nExample:\nCREATE TABLE test (a BINARY(16) NOT NULL DEFAULT UNHEX(SYS_GUID()) PRIMARY KEY);\nINSERT INTO test VALUES (DEFAULT);\nINSERT INTO test VALUES (DEFAULT);\nSELECT HEX(a) FROM test;\n+----------------------------------+\n| HEX(a) |\n+----------------------------------+\n| 53EE84FB733911EDA238D83BBF89F2E2 |\n| 61AC0286733911EDA238D83BBF89F2E2 |\n+----------------------------------+\n\nMariaDB from version 10.7 (as mentioned in danielblack's comment):\nUse UUID datatype which stores UUID() (and SYS_GUID()) values as 16 byte:\nCREATE TABLE test (a UUID not NULL default UUID() PRIMARY KEY);\nINSERT INTO test VALUES (DEFAULT);\nINSERT INTO test VALUES (DEFAULT);\nSELECT a FROM test;\n+--------------------------------------+\n| a |\n+--------------------------------------+\n| 6c42e367-733b-11ed-a238-d83bbf89f2e2 |\n| 6cbc0418-733b-11ed-a238-d83bbf89f2e2 |\n+--------------------------------------+\n\nAddendum: If you are using a version < 10.6 and your requirements match the following limitations, you could also use UUID_SHORT() function, which generates a 64-bit identifier.\n" ]
[ 0, 0 ]
[]
[]
[ "binary", "mariadb", "mysql", "primary_key", "sql" ]
stackoverflow_0074665341_binary_mariadb_mysql_primary_key_sql.txt
Q: How to run a node app which launch a desktop notifications using systemd service Based on my previous searches, I think that the answer is that I can't do that, but anyway I would like to ask because I'm not a linux pro. I have a small app made with nodejs that launch a desktop notification every second: import notifier from 'node-notifier' import {CronJob} from 'cron'; /* Create a cron job that send a desktop notification every second */ const job = new CronJob('* * * * * *', () => { notifier.notify({ title: 'My notification', message: 'Hello, there!', }); }, null, true, 'America/Los_Angeles'); job.start() This works well when I run npm run start. I want to run this using a systemd service: [Unit] Description=should run node app which launch a desktop notification After=network.target [Service] Environment="DISPLAY=:0" "XAUTHORITY=/home/myuser/.Xauthority" Type=simple User=myuser ExecStart=/home/myuser/.nvm/versions/node/v16.13.1/bin/node /home/myuser/notify_send/notify_node/build/index.js Restart=on-failure [Install] WantedBy=multi-user.target Several seconds after start the service, the status command shows this: ● runjs.service - should run node app which launch a desktop notification Loaded: loaded (/etc/systemd/system/runjs.service; disabled; vendor preset: enabled) Active: active (running) since Sun 2022-12-04 17:47:40 CET; 22s ago Main PID: 5606 (node) Tasks: 20 (limit: 18651) Memory: 18.1M CGroup: /system.slice/runjs.service ├─5606 /home/myuser/.nvm/versions/node/v16.13.1/bin/node /home/myuser/notify_send/notify_node/build/index.js ├─5633 /bin/sh -c notify-send "My notification" "Hello, there!" --expire-time "10000" ├─5634 notify-send My notification Hello, there! --expire-time 10000 ├─5639 dbus-launch --autolaunch=017e96ffe51b466384d899f21cbecdc5 --binary-syntax --close-stderr ├─5640 /usr/bin/dbus-daemon --syslog-only --fork --print-pid 5 --print-address 7 --session ├─5642 /usr/bin/dbus-daemon --syslog-only --fork --print-pid 5 --print-address 7 --session └─5643 /usr/bin/plasma_waitforname org.freedesktop.Notifications dic 04 17:47:40 slimbook systemd[1]: Started should run node app which launch a desktop notification. dic 04 17:48:00 slimbook dbus-daemon[5640]: [session uid=1000 pid=5638] AppArmor D-Bus mediation is enabled dic 04 17:48:00 slimbook dbus-daemon[5640]: [session uid=1000 pid=5638] Activating service name='org.freedesktop.Notifications' requested by ':1.0> But no deskop notification is launched when service is running. Thanks in advance. A: try setting the DISPLAY and XAUTHORITY environment variables directly: [Service] Environment="DISPLAY=:0" "XAUTHORITY=/home/myuser/.Xauthority" Type=simple User=myuser ExecStart=/home/myuser/.nvm/versions/node/v16.13.1/bin/node /home/myuser/notify_send/notify_node/build/index.js Restart=on-failure You can also try setting these environment variables in the /etc/environment file, which is read by all processes at startup. add the following lines to the /etc/environment file: DISPLAY=:0 XAUTHORITY=/home/myuser/.Xauthority
How to run a node app which launch a desktop notifications using systemd service
Based on my previous searches, I think that the answer is that I can't do that, but anyway I would like to ask because I'm not a linux pro. I have a small app made with nodejs that launch a desktop notification every second: import notifier from 'node-notifier' import {CronJob} from 'cron'; /* Create a cron job that send a desktop notification every second */ const job = new CronJob('* * * * * *', () => { notifier.notify({ title: 'My notification', message: 'Hello, there!', }); }, null, true, 'America/Los_Angeles'); job.start() This works well when I run npm run start. I want to run this using a systemd service: [Unit] Description=should run node app which launch a desktop notification After=network.target [Service] Environment="DISPLAY=:0" "XAUTHORITY=/home/myuser/.Xauthority" Type=simple User=myuser ExecStart=/home/myuser/.nvm/versions/node/v16.13.1/bin/node /home/myuser/notify_send/notify_node/build/index.js Restart=on-failure [Install] WantedBy=multi-user.target Several seconds after start the service, the status command shows this: ● runjs.service - should run node app which launch a desktop notification Loaded: loaded (/etc/systemd/system/runjs.service; disabled; vendor preset: enabled) Active: active (running) since Sun 2022-12-04 17:47:40 CET; 22s ago Main PID: 5606 (node) Tasks: 20 (limit: 18651) Memory: 18.1M CGroup: /system.slice/runjs.service ├─5606 /home/myuser/.nvm/versions/node/v16.13.1/bin/node /home/myuser/notify_send/notify_node/build/index.js ├─5633 /bin/sh -c notify-send "My notification" "Hello, there!" --expire-time "10000" ├─5634 notify-send My notification Hello, there! --expire-time 10000 ├─5639 dbus-launch --autolaunch=017e96ffe51b466384d899f21cbecdc5 --binary-syntax --close-stderr ├─5640 /usr/bin/dbus-daemon --syslog-only --fork --print-pid 5 --print-address 7 --session ├─5642 /usr/bin/dbus-daemon --syslog-only --fork --print-pid 5 --print-address 7 --session └─5643 /usr/bin/plasma_waitforname org.freedesktop.Notifications dic 04 17:47:40 slimbook systemd[1]: Started should run node app which launch a desktop notification. dic 04 17:48:00 slimbook dbus-daemon[5640]: [session uid=1000 pid=5638] AppArmor D-Bus mediation is enabled dic 04 17:48:00 slimbook dbus-daemon[5640]: [session uid=1000 pid=5638] Activating service name='org.freedesktop.Notifications' requested by ':1.0> But no deskop notification is launched when service is running. Thanks in advance.
[ "try setting the DISPLAY and XAUTHORITY environment variables directly:\n[Service]\nEnvironment=\"DISPLAY=:0\" \"XAUTHORITY=/home/myuser/.Xauthority\"\nType=simple\nUser=myuser\nExecStart=/home/myuser/.nvm/versions/node/v16.13.1/bin/node /home/myuser/notify_send/notify_node/build/index.js\nRestart=on-failure\n\nYou can also try setting these environment variables in the /etc/environment file, which is read by all processes at startup. add the following lines to the /etc/environment file:\nDISPLAY=:0\nXAUTHORITY=/home/myuser/.Xauthority\n\n" ]
[ 0 ]
[]
[]
[ "linux", "node.js", "notifications", "systemd" ]
stackoverflow_0074678818_linux_node.js_notifications_systemd.txt