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: Gauss-Legendre Matlab: How to use Newton method to approximate k_1 and k_2? Recently as a project I have been working on a program in matlab designed to implement the Gauss-Legendre order 4 method of solving an IVP. Numerical analysis- and coding in particular- is somewhat of a weakness of mine, and thus it has been rather tough going. I used the explicit Euler method to initially seed the method, but I've been stuck for a very long time on how to use the Newton method to get closer values of k1 and k2. Thusfar, my code looks as follows: ` %Gauss-Butcher Order 4 function[y] = GBOF(f,fprime,y_0,maxit,ertol) A = [1/4,1/4-sqrt(3)/6;1/4+sqrt(3)/6,1/4]; h = [1,0,0,0,0,0,0,0,0,0,0,0,0]; t = [0,0,0,0,0,0,0,0,0,0,0,0,0]; for n = 1:12 h(n+1) = 1/(2^n); t(n+1) = t(n)+h(n); end y = zeros(size(t)); y(1) = y_0; niter = 1; %Declaration of Variables for i = 1:12 k = f(y(i)); y1approx = y(i) + ((1/2-sqrt(3))*h(i)*k); y2approx = y(i) + ((1/2+sqrt(3))*h(i)*k); k1 = f(y1approx); k2 = f(y2approx); %Initial guess for newton seeding errorFunc =@(k1,k2) [k1-f(y(i) +A(1,1)*k1+A(1,2)*k2*h(i)); k2-f(y(i)+A(2,1)*k1+A(2,2)*k2*h(i))]; error = errorFunc(k1,k2); %Function for error and creation of error variable while norm(error) > ertol && niter < maxit niter = niter + 1; ** k1 = k1-f(k1)/fprime(k1); k2 = k2-f(k2)/fprime(k2); ** error = errorFunc(k1,k2); %Newton Raphston for estimating K1 and K2 end y(i+1) = y(i) +(h(i)*(k1+k2)/2); %Creation of next end disp(t); ` The part of the code I believe is causing this to fail is highlighted. When I enter in a basic ivp (i.e. y' = y, y(0) =1), I get the output Any input on how I could go about fixing this would be much appreciated. Thank you. I have tried replacing the k1s and k2s in the problem with the values used in the formula extrapolated from the butcher tableau, but nothing changed. I can't think of any other ways to tackle this issue. A: The implicit system you have to solve is k1 = f(y + h*(a11*k1 + a12*k2) ) k2 = f(y + h*(a21*k1 + a22*k2) ) This is also correct in your residual function errorFunc. The naive way is just to iterate this system, like any other fixed-point iteration. This system has a linearization rel. h at the base point y k1 = f(y) + h*f'(y)*(a11*k1 + a12*k2) + O(h^2) k2 = f(y) + h*f'(y)*(a21*k1 + a22*k2) + O(h^2) Seen as simple iteration, the contraction factor is O(h), so if h is small enough, the factor is smaller than 1 and thus convergence is sure, increasing the order of h in the residual by 1 in each step. So with 6 iterations the error in the implicit system is O(h^6), which is one order smaller than the local truncation error. One can reduce the number of iterations if k1,k2 start with some higher-order estimates, not just with k1=k2=f(y). One can reduce the right side residual by removing the terms that are linear in h (on both sides of course). k1 - h*f'(y)*(a11*k1 + a12*k2) = f(y + h*(a11*k1 + a12*k2) ) - h*f'(y)*(a11*k1 + a12*k2) k2 - h*f'(y)*(a21*k1 + a22*k2) = f(y + h*(a21*k1 + a22*k2) ) - h*f'(y)*(a21*k1 + a22*k2) The right side is evaluated at the current values, the left side is a linear system for the new values. So K = K - solve(M, rhs) with K = [ k1; k2] M = [ 1 - h*f'(y)*a11, -h*f'(y)*a12 ; -h*f'(y)*a21, 1 - h*f'(y)*a22 ] = I - h*f'(y)*A rhs = [ k1 - f(y + h*(a11*k1 + a12*k2) ); k2 - f(y + h*(a12*k1 + a12*k2) ) = K - f(Y) where Y = y+h*A*K This should, probably, work for scalar equations, for systems this involves Kronecker products of matrices and vectors. As the linear part is taken out of the residual, the contraction factor in this new fixed-point iteration is O(h^2), possibly with smaller constants, so it converges faster and, it has been argued, for larger step sizes. What you have in the code regarding the implicit method step shows the steps of the algorithm in the right order, but with wrong arguments in the function calls. What you do with h is not recognizable. One could guess that the task is to explore the results of the method for a collection of step sizes. This means that the h for each integration run is constant, halving the step size and increasing the step number for the next integration run.
Gauss-Legendre Matlab: How to use Newton method to approximate k_1 and k_2?
Recently as a project I have been working on a program in matlab designed to implement the Gauss-Legendre order 4 method of solving an IVP. Numerical analysis- and coding in particular- is somewhat of a weakness of mine, and thus it has been rather tough going. I used the explicit Euler method to initially seed the method, but I've been stuck for a very long time on how to use the Newton method to get closer values of k1 and k2. Thusfar, my code looks as follows: ` %Gauss-Butcher Order 4 function[y] = GBOF(f,fprime,y_0,maxit,ertol) A = [1/4,1/4-sqrt(3)/6;1/4+sqrt(3)/6,1/4]; h = [1,0,0,0,0,0,0,0,0,0,0,0,0]; t = [0,0,0,0,0,0,0,0,0,0,0,0,0]; for n = 1:12 h(n+1) = 1/(2^n); t(n+1) = t(n)+h(n); end y = zeros(size(t)); y(1) = y_0; niter = 1; %Declaration of Variables for i = 1:12 k = f(y(i)); y1approx = y(i) + ((1/2-sqrt(3))*h(i)*k); y2approx = y(i) + ((1/2+sqrt(3))*h(i)*k); k1 = f(y1approx); k2 = f(y2approx); %Initial guess for newton seeding errorFunc =@(k1,k2) [k1-f(y(i) +A(1,1)*k1+A(1,2)*k2*h(i)); k2-f(y(i)+A(2,1)*k1+A(2,2)*k2*h(i))]; error = errorFunc(k1,k2); %Function for error and creation of error variable while norm(error) > ertol && niter < maxit niter = niter + 1; ** k1 = k1-f(k1)/fprime(k1); k2 = k2-f(k2)/fprime(k2); ** error = errorFunc(k1,k2); %Newton Raphston for estimating K1 and K2 end y(i+1) = y(i) +(h(i)*(k1+k2)/2); %Creation of next end disp(t); ` The part of the code I believe is causing this to fail is highlighted. When I enter in a basic ivp (i.e. y' = y, y(0) =1), I get the output Any input on how I could go about fixing this would be much appreciated. Thank you. I have tried replacing the k1s and k2s in the problem with the values used in the formula extrapolated from the butcher tableau, but nothing changed. I can't think of any other ways to tackle this issue.
[ "The implicit system you have to solve is\nk1 = f(y + h*(a11*k1 + a12*k2) )\nk2 = f(y + h*(a21*k1 + a22*k2) )\n\nThis is also correct in your residual function errorFunc.\nThe naive way is just to iterate this system, like any other fixed-point iteration.\nThis system has a linearization rel. h at the base point y\nk1 = f(y) + h*f'(y)*(a11*k1 + a12*k2) + O(h^2)\nk2 = f(y) + h*f'(y)*(a21*k1 + a22*k2) + O(h^2)\n\nSeen as simple iteration, the contraction factor is O(h), so if h is small enough, the factor is smaller than 1 and thus convergence is sure, increasing the order of h in the residual by 1 in each step. So with 6 iterations the error in the implicit system is O(h^6), which is one order smaller than the local truncation error.\nOne can reduce the number of iterations if k1,k2 start with some higher-order estimates, not just with k1=k2=f(y).\n\nOne can reduce the right side residual by removing the terms that are linear in h (on both sides of course).\nk1 - h*f'(y)*(a11*k1 + a12*k2) = f(y + h*(a11*k1 + a12*k2) ) - h*f'(y)*(a11*k1 + a12*k2)\nk2 - h*f'(y)*(a21*k1 + a22*k2) = f(y + h*(a21*k1 + a22*k2) ) - h*f'(y)*(a21*k1 + a22*k2)\n\nThe right side is evaluated at the current values, the left side is a linear system for the new values. So\nK = K - solve(M, rhs)\n\nwith\nK = [ k1; k2]\n\nM = [ 1 - h*f'(y)*a11, -h*f'(y)*a12 ; -h*f'(y)*a21, 1 - h*f'(y)*a22 ]\n = I - h*f'(y)*A\n\nrhs = [ k1 - f(y + h*(a11*k1 + a12*k2) ); k2 - f(y + h*(a12*k1 + a12*k2) )\n = K - f(Y)\n\nwhere \n\nY = y+h*A*K\n\nThis should, probably, work for scalar equations, for systems this involves Kronecker products of matrices and vectors.\nAs the linear part is taken out of the residual, the contraction factor in this new fixed-point iteration is O(h^2), possibly with smaller constants, so it converges faster and, it has been argued, for larger step sizes.\nWhat you have in the code regarding the implicit method step shows the steps of the algorithm in the right order, but with wrong arguments in the function calls.\nWhat you do with h is not recognizable. One could guess that the task is to explore the results of the method for a collection of step sizes. This means that the h for each integration run is constant, halving the step size and increasing the step number for the next integration run.\n" ]
[ 0 ]
[]
[]
[ "matlab", "numerical_methods" ]
stackoverflow_0074669048_matlab_numerical_methods.txt
Q: Nuxt 3 with TailwindCSS -> heroicons Can someone help with setting up Heroicons in combination with Nuxt 3? I ran the following command: yarn add @heroicons/vue I also added @heroicons/vue as following to my nuxt.config.js: build: { transpile: ["@headlessui/vue", "@heroicons/vue"], postcss: { plugins: { tailwindcss: {}, autoprefixer: {}, }, }, }, But I can't seem to make it work at all. Could you tell me what I have to do? A: Here is how you should set up a nuxt.config.js file together with tailwindcss and nuxt-icon library: export default defineNuxtConfig({ modules: ['nuxt-icon'], css: ['~/assets/css/main.css'], // css file with @tailwind base etc. postcss: { plugins: { tailwindcss: {}, autoprefixer: {} } } }) Like I wrote in comment, nuxt-icon contains all Heroicons together with 100k + more. Here is the way you can use this icon library: https://stackoverflow.com/a/73810640/6310260 A: Tailwindcss and Nuxt first you should ,install tailwind package: npm install -D tailwindcss postcss autoprefixer then generate tailwind cona fig file: npx tailwindcss init Add Tailwind to your PostCSS configuration // https://v3.nuxtjs.org/api/configuration/nuxt.config export default defineNuxtConfig({ postcss: { plugins: { tailwindcss: {}, autoprefixer: {}, }, }, }) then inside your tailwind.config.js Configure your template paths: /** @type {import('tailwindcss').Config} */ module.exports = { content: [ "./components/**/*.{js,vue,ts}", "./layouts/**/*.vue", "./pages/**/*.vue", "./pages/index.vue", "./plugins/**/*.{js,ts}", "./nuxt.config.{js,ts}", "./app.vue", ], theme: { extend: {}, }, plugins: [], } ! if you set srcDir correct the paths then add the Tailwind directives to your CSS: add main.css file to your assets with this content: Add main.css the CSS file globally main.css file: @tailwind base; @tailwind components; @tailwind utilities; nuxt.config.js css: ['~/assets/css/main.css'], finally you can use tailwind. final nuxt.config.js file : export default defineNuxtConfig({ css: ["@/assets/styles/main.scss"], postcss: { plugins: { "postcss-import": {}, "tailwindcss/nesting": {}, tailwindcss: {}, autoprefixer: {}, }, }, }) Heroicons and Nuxt First, you should install Heroicons package: npm install @heroicons/vue then you can use it like this: <template> <BeakerIcon class="h-6 w-6 text-blue-500" /> </template> <script lang="ts" setup> import { BeakerIcon } from "@heroicons/vue/24/solid"; </script> The 24x24 outline icons can be imported from @heroicons/vue/24/outline, the 24x24 solid icons can be imported from @heroicons/vue/24/solid, and the 20x20 solid icons can be imported from @heroicons/vue/20/solid. learn more here: https://github.com/tailwindlabs/heroicons#vue but try nuxt-icon library :)
Nuxt 3 with TailwindCSS -> heroicons
Can someone help with setting up Heroicons in combination with Nuxt 3? I ran the following command: yarn add @heroicons/vue I also added @heroicons/vue as following to my nuxt.config.js: build: { transpile: ["@headlessui/vue", "@heroicons/vue"], postcss: { plugins: { tailwindcss: {}, autoprefixer: {}, }, }, }, But I can't seem to make it work at all. Could you tell me what I have to do?
[ "Here is how you should set up a nuxt.config.js file together with tailwindcss and nuxt-icon library:\nexport default defineNuxtConfig({\n modules: ['nuxt-icon'],\n css: ['~/assets/css/main.css'], // css file with @tailwind base etc.\n postcss: {\n plugins: {\n tailwindcss: {},\n autoprefixer: {}\n }\n }\n})\n\nLike I wrote in comment, nuxt-icon contains all Heroicons together with 100k + more.\nHere is the way you can use this icon library: https://stackoverflow.com/a/73810640/6310260\n", "Tailwindcss and Nuxt\nfirst you should ,install tailwind package:\nnpm install -D tailwindcss postcss autoprefixer\n\nthen generate tailwind cona fig file:\nnpx tailwindcss init\n\nAdd Tailwind to your PostCSS configuration\n// https://v3.nuxtjs.org/api/configuration/nuxt.config\nexport default defineNuxtConfig({\n postcss: {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n },\n})\n\nthen inside your tailwind.config.js Configure your template paths:\n/** @type {import('tailwindcss').Config} */\nmodule.exports = {\n content: [\n \"./components/**/*.{js,vue,ts}\",\n \"./layouts/**/*.vue\",\n \"./pages/**/*.vue\",\n \"./pages/index.vue\",\n \"./plugins/**/*.{js,ts}\",\n \"./nuxt.config.{js,ts}\",\n \"./app.vue\",\n ],\n theme: {\n extend: {},\n },\n plugins: [],\n}\n\n! if you set srcDir correct the paths\nthen add the Tailwind directives to your CSS:\n\nadd main.css file to your assets with this content:\n\nAdd main.css the CSS file globally\n\n\nmain.css file:\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\nnuxt.config.js\ncss: ['~/assets/css/main.css'],\n\nfinally you can use tailwind.\nfinal nuxt.config.js file :\nexport default defineNuxtConfig({\ncss: [\"@/assets/styles/main.scss\"],\n postcss: {\n plugins: {\n \"postcss-import\": {},\n \"tailwindcss/nesting\": {},\n tailwindcss: {},\n autoprefixer: {},\n },\n },\n})\n\nHeroicons and Nuxt\nFirst, you should install Heroicons package:\nnpm install @heroicons/vue\n\nthen you can use it like this:\n<template>\n<BeakerIcon class=\"h-6 w-6 text-blue-500\" />\n</template>\n<script lang=\"ts\" setup>\nimport { BeakerIcon } from \"@heroicons/vue/24/solid\";\n</script>\n\n\nThe 24x24 outline icons can be imported from @heroicons/vue/24/outline, the 24x24 solid icons can be imported from @heroicons/vue/24/solid, and the 20x20 solid icons can be imported from @heroicons/vue/20/solid.\n\nlearn more here: https://github.com/tailwindlabs/heroicons#vue\nbut try nuxt-icon library :)\n" ]
[ 0, 0 ]
[]
[]
[ "heroicons", "nuxtjs3", "tailwind_css", "tailwind_ui", "vue.js" ]
stackoverflow_0074678254_heroicons_nuxtjs3_tailwind_css_tailwind_ui_vue.js.txt
Q: How do I use binaries from Conan packages? I'm trying build a project using Emscripten installed form the Conan center. I've been able to get it working, but I'm confused as to how I'm supposed to use the binaries for building my project. Here's my conanfile: [requires] libxml2/2.10.3 zlib/1.2.13 zstd/1.5.2 [generators] cmake And my host profile: [settings] os=Emscripten arch=wasm compiler=clang compiler.version=16 build_type=Release [build_requires] emsdk/3.1.23 [options] libxml2:ftp=False libxml2:shared=False libxml2:threads=False [env] I thought I could use imports, but that didn't seem to work. Binaries from libxml and zstd got imported, but not anything from emsdk. I eventually found a solution using conan info + awk: source $(conan info . --package-filter emsdk/3.1.23 --paths --only "package_folder" -pr:h emscripten -pr:b default 2>/dev/null | awk ' $2 != "" {print $2}')/bin/emsdk_env.sh export PATH=$PATH:$(conan info . --package-filter nodejs/16.3.0 --paths --only "package_folder" -pr:h emscripten -pr:b default 2>/dev/null | awk ' $2 != "" {print $2}')/bin But I feel like there's got to be a simpler way that I've just missed somehow. A: When you use Conan to install a package, the binaries are placed in a directory that Conan calls the "package cache". By default, this directory is located at ~/.conan/data/, but you can change its location by setting the CONAN_USER_HOME environment variable. To use the binaries from a package in your project, you'll need to tell your build system (e.g. CMake) where to find them. This is typically done by setting the CMAKE_PREFIX_PATH variable to the package cache directory. For example, if you're using CMake and the package cache is located at ~/.conan/data/, you can add the following line to your CMakeLists.txt file: set(CMAKE_PREFIX_PATH "$ENV{HOME}/.conan/data") This will tell CMake to look in the package cache for any dependencies that your project needs. If you're still having trouble getting your project to build with Conan, I'd recommend checking out the Conan documentation or asking for help on the Conan forums.
How do I use binaries from Conan packages?
I'm trying build a project using Emscripten installed form the Conan center. I've been able to get it working, but I'm confused as to how I'm supposed to use the binaries for building my project. Here's my conanfile: [requires] libxml2/2.10.3 zlib/1.2.13 zstd/1.5.2 [generators] cmake And my host profile: [settings] os=Emscripten arch=wasm compiler=clang compiler.version=16 build_type=Release [build_requires] emsdk/3.1.23 [options] libxml2:ftp=False libxml2:shared=False libxml2:threads=False [env] I thought I could use imports, but that didn't seem to work. Binaries from libxml and zstd got imported, but not anything from emsdk. I eventually found a solution using conan info + awk: source $(conan info . --package-filter emsdk/3.1.23 --paths --only "package_folder" -pr:h emscripten -pr:b default 2>/dev/null | awk ' $2 != "" {print $2}')/bin/emsdk_env.sh export PATH=$PATH:$(conan info . --package-filter nodejs/16.3.0 --paths --only "package_folder" -pr:h emscripten -pr:b default 2>/dev/null | awk ' $2 != "" {print $2}')/bin But I feel like there's got to be a simpler way that I've just missed somehow.
[ "When you use Conan to install a package, the binaries are placed in a directory that Conan calls the \"package cache\". By default, this directory is located at ~/.conan/data/, but you can change its location by setting the CONAN_USER_HOME environment variable.\nTo use the binaries from a package in your project, you'll need to tell your build system (e.g. CMake) where to find them. This is typically done by setting the CMAKE_PREFIX_PATH variable to the package cache directory.\nFor example, if you're using CMake and the package cache is located at ~/.conan/data/, you can add the following line to your CMakeLists.txt file:\nset(CMAKE_PREFIX_PATH \"$ENV{HOME}/.conan/data\")\n\nThis will tell CMake to look in the package cache for any dependencies that your project needs.\nIf you're still having trouble getting your project to build with Conan, I'd recommend checking out the Conan documentation or asking for help on the Conan forums.\n" ]
[ 0 ]
[]
[]
[ "c++", "conan", "emscripten" ]
stackoverflow_0074678469_c++_conan_emscripten.txt
Q: Using CMFCMenuButton::SizeToContent does not seem to work as I would like. Why? I am perplexed about the SizeToContent method of the CMFCMenuButton control. This is my dialog in the IDE: As you can see, I have specifically made the button wider than the two on the far right. I added the following code to OnInitDialog: // Resize (if required) const auto sizNewButton = m_btnReset.SizeToContent(true); CRect rctButton; m_btnReset.GetWindowRect(&rctButton); if(sizNewButton.cx > rctButton.Width()) { m_btnReset.SizeToContent(); } Yet, when I run my application in English: It has made it smaller. My application supports 50+ languages by using satellite DLLs and I was hoping to only resize to content if it was required. But it seems to resize it anyway. Have I missed a step here? I have checked the properties for the control in the IDE and it is not set to auto resize: I notice that the help documentation states: The new size of the button is calculated to fit the button text, image, and arrow. The framework also adds in predefined margins of 10 pixels for the horizontal edge and 5 pixels for the vertical edge. I had a look at my button: Default size: 48 x 23 (the GeWindowRect result). Calculated size: 57 x 23 (the SizeToContent result). If I adjusted my code like this: if((sizNewButton.cx - 10) > rctButton.Width()) That would bring it down to 47 and thus would not resize. I am assuming the code is not working right because of the padded margin that GetWindowRect knows nothing about. A: Searched it, and found that the problem is MFC's CMFCMenuButton::SizeToContent() implementation in afxmenubutton.cpp: CSize CMFCMenuButton::SizeToContent(BOOL bCalcOnly) { CSize size = CMFCButton::SizeToContent(FALSE); // <==== The culprit!!! size.cx += CMenuImages::Size().cx; if (!bCalcOnly) { SetWindowPos(NULL, -1, -1, size.cx, size.cy, SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER); } return size; } That is, it calls the base implementation of SizeToContent() with the bCalcOnly parameter set to FALSE, which means it will also resize the control to just fit the text (without the drop-down arrow). This is less than required for the text plus the arrow, and of course the original size is lost. A workaround can be get the (original) width, before the SizeToContent() call, and work with this instead of the new one: CRect rctButton; m_btnReset.GetWindowRect(&rctButton); const auto nOrigWidth = rctButton.Width(); // Store the original width const auto sizNewButton = m_btnReset.SizeToContent(true); // This resizes the control!!! if (sizNewButton.cx > nOrigWidth) // Compare to the original width rather than the new one m_btnReset.SizeToContent(); else // Restore original width m_btnReset.SetWindowPos(NULL, -1, -1, nOrigWidth, sizNewButton.cy, SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER); Alternative Workaround: Define a new CMFCMenuButton-based class, overriding SizeToContent() - in the implementation call the base CMFCButton::SizeToContent() with the bCalcOnly parameter passed by the caller, not with FALSE. Map the control to this class instead of CMFCMenuButton. That is use a class that fixes it. Too much of an overkill for just a workaround though.
Using CMFCMenuButton::SizeToContent does not seem to work as I would like. Why?
I am perplexed about the SizeToContent method of the CMFCMenuButton control. This is my dialog in the IDE: As you can see, I have specifically made the button wider than the two on the far right. I added the following code to OnInitDialog: // Resize (if required) const auto sizNewButton = m_btnReset.SizeToContent(true); CRect rctButton; m_btnReset.GetWindowRect(&rctButton); if(sizNewButton.cx > rctButton.Width()) { m_btnReset.SizeToContent(); } Yet, when I run my application in English: It has made it smaller. My application supports 50+ languages by using satellite DLLs and I was hoping to only resize to content if it was required. But it seems to resize it anyway. Have I missed a step here? I have checked the properties for the control in the IDE and it is not set to auto resize: I notice that the help documentation states: The new size of the button is calculated to fit the button text, image, and arrow. The framework also adds in predefined margins of 10 pixels for the horizontal edge and 5 pixels for the vertical edge. I had a look at my button: Default size: 48 x 23 (the GeWindowRect result). Calculated size: 57 x 23 (the SizeToContent result). If I adjusted my code like this: if((sizNewButton.cx - 10) > rctButton.Width()) That would bring it down to 47 and thus would not resize. I am assuming the code is not working right because of the padded margin that GetWindowRect knows nothing about.
[ "Searched it, and found that the problem is MFC's CMFCMenuButton::SizeToContent() implementation in afxmenubutton.cpp:\nCSize CMFCMenuButton::SizeToContent(BOOL bCalcOnly)\n{\n CSize size = CMFCButton::SizeToContent(FALSE); // <==== The culprit!!!\n size.cx += CMenuImages::Size().cx;\n\n if (!bCalcOnly)\n {\n SetWindowPos(NULL, -1, -1, size.cx, size.cy, SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);\n }\n\n return size;\n}\n\nThat is, it calls the base implementation of SizeToContent() with the bCalcOnly parameter set to FALSE, which means it will also resize the control to just fit the text (without the drop-down arrow). This is less than required for the text plus the arrow, and of course the original size is lost.\nA workaround can be get the (original) width, before the SizeToContent() call, and work with this instead of the new one:\nCRect rctButton;\nm_btnReset.GetWindowRect(&rctButton);\nconst auto nOrigWidth = rctButton.Width(); // Store the original width\nconst auto sizNewButton = m_btnReset.SizeToContent(true); // This resizes the control!!!\nif (sizNewButton.cx > nOrigWidth) // Compare to the original width rather than the new one\n m_btnReset.SizeToContent();\nelse // Restore original width\n m_btnReset.SetWindowPos(NULL, -1, -1, nOrigWidth, sizNewButton.cy, SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);\n\nAlternative Workaround: \nDefine a new CMFCMenuButton-based class, overriding SizeToContent() - in the implementation call the base CMFCButton::SizeToContent() with the bCalcOnly parameter passed by the caller, not with FALSE. Map the control to this class instead of CMFCMenuButton. That is use a class that fixes it. Too much of an overkill for just a workaround though.\n" ]
[ 1 ]
[]
[]
[ "mfc", "visual_c++" ]
stackoverflow_0074674331_mfc_visual_c++.txt
Q: How do I use custom JWT claims in springboot controller authorization? In Spring Boot I have a JWT token generated with Keycloak which has some custom claims: { ... custom_claim:123 } I can add an Authentication parameter in my rest controller and I can see this attribute but its in a deeply nested location principal.context.token.otherclaims[0] in a class called RefreshableKeycloakSecurityContext. What is the best way to use this claim in PreAuthorization? I think what I want is to compare the claim in the token with a path parameter and return an error if they don't match. @PreAuthorization("custom_claim=#my-path-parm") A: You can have the Authentication instance be "auto-magically" injected as controller parameter. By default for resource-servers, you'll get a JwtAuthenticationToken with JWT decoder and BearerTokenAuthentication with introspection ("opaque" tokens). @RequestMapping("/{machin}") @PreAuthorize("#machin eq #auth.tokenAttributes['yourclaim']") public SomeDto controllerMethod(@PathVariable("machin") String machin, AbstractOAuth2TokenAuthenticationToken<?> auth) { ... } I suggest you write a custom Authentication instance, using AbstractAuthenticationToken as base class, to wrap private claims parsing and casting (claim values are Object). You replace the Authentication instance with your own exactly the same way as you probably already replaced authorities mapping: http.oauth2ResourceServer().jwt().jwtAuthenticationConverter(jwt -> new YourAuthenticationImpl(jwt, authoritiesConverter.convert(jwt))); You might also provide a custom DSL to make security expressions more readable and, more importantly, easier to maintain: expressions definition would be at a single place instead of being spread across controllers methods. I have written a set of 3 tutorials which end with expressions like: @GetMapping("/on-behalf-of/{username}") @PreAuthorize("is(#username) or isNice() or onBehalfOf(#username).can('greet')") public String getGreetingFor(@PathVariable("username") String username, ProxiesAuthentication auth) { return "Hi %s from %s!".formatted(username, auth.getName()); } This tutorials will also teach you how to unit-test your security expressions, even with private claims and custom Authentication. The endpoint secured with preceeding expression is tested as follow: @Test @ProxiesAuth( authorities = { "AUTHOR" }, claims = @OpenIdClaims(preferredUsername = "Tonton Pirate"), proxies = { @Proxy(onBehalfOf = "ch4mpy", can = { "greet" }) }) void whenNotNiceWithProxyThenCanGreetFor() throws Exception { mockMvc.get("/greet/on-behalf-of/ch4mpy") .andExpect(status().isOk()) .andExpect(content().string("Hi ch4mpy from Tonton Pirate!")); } @Test @ProxiesAuth( authorities = { "AUTHOR", "NICE" }, claims = @OpenIdClaims(preferredUsername = "Tonton Pirate")) void whenNiceWithoutProxyThenCanGreetFor() throws Exception { mockMvc.get("/greet/on-behalf-of/ch4mpy") .andExpect(status().isOk()) .andExpect(content().string("Hi ch4mpy from Tonton Pirate!")); } @Test @ProxiesAuth( authorities = { "AUTHOR" }, claims = @OpenIdClaims(preferredUsername = "Tonton Pirate"), proxies = { @Proxy(onBehalfOf = "jwacongne", can = { "greet" }) }) void whenNotNiceWithoutRequiredProxyThenForbiddenToGreetFor() throws Exception { mockMvc.get("/greet/on-behalf-of/greeted") .andExpect(status().isForbidden()); } @Test @ProxiesAuth( authorities = { "AUTHOR" }, claims = @OpenIdClaims(preferredUsername = "Tonton Pirate")) void whenHimselfThenCanGreetFor() throws Exception { mockMvc.get("/greet/on-behalf-of/Tonton Pirate") .andExpect(status().isOk()) .andExpect(content().string("Hi Tonton Pirate from Tonton Pirate!")); }
How do I use custom JWT claims in springboot controller authorization?
In Spring Boot I have a JWT token generated with Keycloak which has some custom claims: { ... custom_claim:123 } I can add an Authentication parameter in my rest controller and I can see this attribute but its in a deeply nested location principal.context.token.otherclaims[0] in a class called RefreshableKeycloakSecurityContext. What is the best way to use this claim in PreAuthorization? I think what I want is to compare the claim in the token with a path parameter and return an error if they don't match. @PreAuthorization("custom_claim=#my-path-parm")
[ "You can have the Authentication instance be \"auto-magically\" injected as controller parameter. By default for resource-servers, you'll get a JwtAuthenticationToken with JWT decoder and BearerTokenAuthentication with introspection (\"opaque\" tokens).\n@RequestMapping(\"/{machin}\")\n@PreAuthorize(\"#machin eq #auth.tokenAttributes['yourclaim']\") \npublic SomeDto controllerMethod(@PathVariable(\"machin\") String machin, AbstractOAuth2TokenAuthenticationToken<?> auth) {\n ...\n}\n\nI suggest you write a custom Authentication instance, using AbstractAuthenticationToken as base class, to wrap private claims parsing and casting (claim values are Object). You replace the Authentication instance with your own exactly the same way as you probably already replaced authorities mapping:\nhttp.oauth2ResourceServer().jwt().jwtAuthenticationConverter(jwt -> new YourAuthenticationImpl(jwt, authoritiesConverter.convert(jwt)));\n\nYou might also provide a custom DSL to make security expressions more readable and, more importantly, easier to maintain: expressions definition would be at a single place instead of being spread across controllers methods.\nI have written a set of 3 tutorials which end with expressions like:\n@GetMapping(\"/on-behalf-of/{username}\")\n@PreAuthorize(\"is(#username) or isNice() or onBehalfOf(#username).can('greet')\")\npublic String getGreetingFor(@PathVariable(\"username\") String username, ProxiesAuthentication auth) {\n return \"Hi %s from %s!\".formatted(username, auth.getName());\n}\n\nThis tutorials will also teach you how to unit-test your security expressions, even with private claims and custom Authentication. The endpoint secured with preceeding expression is tested as follow:\n@Test\n@ProxiesAuth(\n authorities = { \"AUTHOR\" },\n claims = @OpenIdClaims(preferredUsername = \"Tonton Pirate\"),\n proxies = { @Proxy(onBehalfOf = \"ch4mpy\", can = { \"greet\" }) })\nvoid whenNotNiceWithProxyThenCanGreetFor() throws Exception {\n mockMvc.get(\"/greet/on-behalf-of/ch4mpy\")\n .andExpect(status().isOk())\n .andExpect(content().string(\"Hi ch4mpy from Tonton Pirate!\"));\n}\n\n@Test\n@ProxiesAuth(\n authorities = { \"AUTHOR\", \"NICE\" },\n claims = @OpenIdClaims(preferredUsername = \"Tonton Pirate\"))\nvoid whenNiceWithoutProxyThenCanGreetFor() throws Exception {\n mockMvc.get(\"/greet/on-behalf-of/ch4mpy\")\n .andExpect(status().isOk())\n .andExpect(content().string(\"Hi ch4mpy from Tonton Pirate!\"));\n}\n\n@Test\n@ProxiesAuth(\n authorities = { \"AUTHOR\" },\n claims = @OpenIdClaims(preferredUsername = \"Tonton Pirate\"),\n proxies = { @Proxy(onBehalfOf = \"jwacongne\", can = { \"greet\" }) })\nvoid whenNotNiceWithoutRequiredProxyThenForbiddenToGreetFor() throws Exception {\n mockMvc.get(\"/greet/on-behalf-of/greeted\")\n .andExpect(status().isForbidden());\n}\n\n@Test\n@ProxiesAuth(\n authorities = { \"AUTHOR\" },\n claims = @OpenIdClaims(preferredUsername = \"Tonton Pirate\"))\nvoid whenHimselfThenCanGreetFor() throws Exception {\n mockMvc.get(\"/greet/on-behalf-of/Tonton Pirate\")\n .andExpect(status().isOk())\n .andExpect(content().string(\"Hi Tonton Pirate from Tonton Pirate!\"));\n}\n\n" ]
[ 0 ]
[]
[]
[ "jwt", "oauth_2.0", "spring_boot" ]
stackoverflow_0074673003_jwt_oauth_2.0_spring_boot.txt
Q: When I swap two values in my list it is not a permanent swap in the list? I'm new to Python, and I have an assignment where I have a frogs vs. toads game. They are in a list and they need to swap places one step at a time. the list looks like this: ["F","F","F"," ","T","T","T"] and should look like ["T","T","T"," ","F","F","F"] to win the game. The user inputs From and To and they swap. But my code is not taking the swapped code as the new code when the new From and To are being entered. How do I fix this? This is all within a while loop as there are other options at the beginning of the game. Also, one of the rules for the assignment is that the frogs are only allowed to one one direction to the left and the toads vice versa. if anyone knows how to put that into my code that would be very much appreciated. Here's my code: elif choice== 'P': position= ["1","2","3","4","5","6","7"] frogsandtoads= ["F","F","F"," ","T","T","T"] print("Position: ",position) print("Lilypad: ",frogsandtoads) def swappositions(frogsandtoads, pos1, pos2): if pos1== 'e': exit() if pos1== 'E': exit() frogsandtoads[pos1], frogsandtoads[pos2] = frogsandtoads[pos2], frogsandtoads[pos1]#the swapping of the positions return frogsandtoads pos1 = fromplace= int(input("From: ")) pos2 = toplace= int(input("To: ")) print(swappositions(frogsandtoads, pos1-1, pos2-1)) frogsandtoads=swappositions(frogsandtoads, pos1-1, pos2-1) if frogsandtoads== ["T","T","T"," ","F","F","F"]: #this is what is not working break this is my outcome when I run the code: Please choose an option: p Position: ['1', '2', '3', '4', '5', '6', '7'] Lilypad: ['F', 'F', 'F', ' ', 'T', 'T', 'T'] From: 3 To: 4 ['F', 'F', ' ', 'F', 'T', 'T', 'T'] Position: ['1', '2', '3', '4', '5', '6', '7'] Lilypad: ['F', 'F', 'F', ' ', 'T', 'T', 'T'] From: As you can see I don't know how to make it so the lilypad changes with the input of the from and to the second time round. A: So you want it such that the lilypad list does not revert back to ['F', 'F', 'F', ' ', 'T', 'T', 'T'] and that the position list also won't revert back to ['1', '2', '3', '4', '5', '6', '7']? The problem in your code is that you reset the variables here: position= ["1","2","3","4","5","6","7"] frogsandtoads= ["F","F","F"," ","T","T","T"] If you do not want those lists to get reset to that then you should move those two lines out of your game loop aka outside of your while loop. This should fix the problem. You also have the stepping problem such that the frogs can only go to the left and the toads to the right, but I believe that you can implement this yourself. Feel free to ask questions.
When I swap two values in my list it is not a permanent swap in the list?
I'm new to Python, and I have an assignment where I have a frogs vs. toads game. They are in a list and they need to swap places one step at a time. the list looks like this: ["F","F","F"," ","T","T","T"] and should look like ["T","T","T"," ","F","F","F"] to win the game. The user inputs From and To and they swap. But my code is not taking the swapped code as the new code when the new From and To are being entered. How do I fix this? This is all within a while loop as there are other options at the beginning of the game. Also, one of the rules for the assignment is that the frogs are only allowed to one one direction to the left and the toads vice versa. if anyone knows how to put that into my code that would be very much appreciated. Here's my code: elif choice== 'P': position= ["1","2","3","4","5","6","7"] frogsandtoads= ["F","F","F"," ","T","T","T"] print("Position: ",position) print("Lilypad: ",frogsandtoads) def swappositions(frogsandtoads, pos1, pos2): if pos1== 'e': exit() if pos1== 'E': exit() frogsandtoads[pos1], frogsandtoads[pos2] = frogsandtoads[pos2], frogsandtoads[pos1]#the swapping of the positions return frogsandtoads pos1 = fromplace= int(input("From: ")) pos2 = toplace= int(input("To: ")) print(swappositions(frogsandtoads, pos1-1, pos2-1)) frogsandtoads=swappositions(frogsandtoads, pos1-1, pos2-1) if frogsandtoads== ["T","T","T"," ","F","F","F"]: #this is what is not working break this is my outcome when I run the code: Please choose an option: p Position: ['1', '2', '3', '4', '5', '6', '7'] Lilypad: ['F', 'F', 'F', ' ', 'T', 'T', 'T'] From: 3 To: 4 ['F', 'F', ' ', 'F', 'T', 'T', 'T'] Position: ['1', '2', '3', '4', '5', '6', '7'] Lilypad: ['F', 'F', 'F', ' ', 'T', 'T', 'T'] From: As you can see I don't know how to make it so the lilypad changes with the input of the from and to the second time round.
[ "So you want it such that the lilypad list does not revert back to ['F', 'F', 'F', ' ', 'T', 'T', 'T'] and that the position list also won't revert back to ['1', '2', '3', '4', '5', '6', '7']?\nThe problem in your code is that you reset the variables here:\n position= [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\"]\n frogsandtoads= [\"F\",\"F\",\"F\",\" \",\"T\",\"T\",\"T\"]\n\nIf you do not want those lists to get reset to that then you should move those two lines out of your game loop aka outside of your while loop. This should fix the problem. You also have the stepping problem such that the frogs can only go to the left and the toads to the right, but I believe that you can implement this yourself. Feel free to ask questions.\n" ]
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074672043_list_python.txt
Q: Visual Studio Nesting html,css and ts files I saw a visual studio project which consists of a folder html,css and ts files where html file is the parent file and css and ts are child files. The thing is the project doesn't use the file nesting extension(I have already checked that) and the html,css and ts files all have different logos than the normal standard. Html (The parent nodes) logo is a file with a blue circle and css and ts files(child nodes) logo have blue arrow files. P.S. This is my first post in this forum so I'm not able to upload an image else I would have shared a screen shot of the project with you guys for better understanding of my problem. A: Ok just open task manager And end process tree of 'code.exe' And restart
Visual Studio Nesting html,css and ts files
I saw a visual studio project which consists of a folder html,css and ts files where html file is the parent file and css and ts are child files. The thing is the project doesn't use the file nesting extension(I have already checked that) and the html,css and ts files all have different logos than the normal standard. Html (The parent nodes) logo is a file with a blue circle and css and ts files(child nodes) logo have blue arrow files. P.S. This is my first post in this forum so I'm not able to upload an image else I would have shared a screen shot of the project with you guys for better understanding of my problem.
[ "Ok just open task manager\nAnd end process tree of 'code.exe'\nAnd restart\n" ]
[ 0 ]
[]
[]
[ "css", "html", "nested", "typescript", "visual_studio_2013" ]
stackoverflow_0031920391_css_html_nested_typescript_visual_studio_2013.txt
Q: Select, move and deselect a card from Solitaire game pygame I want to select a card with the mouse (the card changes to another image of a card with orange edges), move it (or not) and later deselect the card clicking again, returning it to the original image of the card (without orange edges). I made the two first steps, but I can't find a way to deselect the card. for event in pygame.event.get(): if event.type==pygame.QUIT: pygame.quit() sys.exit() if event.type==pygame.MOUSEBUTTONDOWN: if event.button==1 and mouse_rect.colliderect(card_rect): card = pygame.image.load("1c2.png").convert_alpha() card = pygame.transform.scale(card, (99, 100)) if event.button == 1 and not mouse_rect.colliderect(card_rect): n = pygame.mouse.get_pos() x = n[0] y = n[1] card_rect.centerx = x card_rect.centery = y if event.button==1 and mouse_rect.colliderect(card_rect) and card_rect.width==99: card = pygame.image.load("1c.png").convert_alpha() card = pygame.transform.scale(card, (100, 100)) Original image:1c.png Image selected (with orange edges):1c2.png I try to change a little the width of the card when you select it, and after using that in the last conditional that you can see above. I also tried (in the last conditional too): if event.button==1 and mouse_rect.colliderect(card_rect) and card==pygame.image.load("1c2.png").convert_alpha(): card = pygame.image.load("1c.png").convert_alpha() card = pygame.transform.scale(card, (100, 100)) What can I do to fix it? Thanks! Wrong result: The card stays at the selected image (card with orange borders). A: Do not load the images in the application loop. Load the images before the application loop. Use a Boolean variable (card_selected) to indicate if the map is selected. Invert the state when clicking on the card (card_selected = not card_selected): card_1 = pygame.image.load("1c.png").convert_alpha() card_1 = pygame.transform.scale(card_1, (100, 100)) card_2 = pygame.image.load("1c2.png").convert_alpha() card_2 = pygame.transform.scale(card_2, (100, 100)) card = card_1 card_selected = False # [...] run = True while run: for event in pygame.event.get(): if event.type==pygame.QUIT: run = False if event.type==pygame.MOUSEBUTTONDOWN: if event.button == 1 and card_rect.collidepoint(event.pos): card_selected = not card_selected card = card_2 if card_selected else card_1 # [...] pygame.quit() sys.exit() Do not forget to clear the display in every frame. The entire scene must be redrawn in each frame.
Select, move and deselect a card from Solitaire game pygame
I want to select a card with the mouse (the card changes to another image of a card with orange edges), move it (or not) and later deselect the card clicking again, returning it to the original image of the card (without orange edges). I made the two first steps, but I can't find a way to deselect the card. for event in pygame.event.get(): if event.type==pygame.QUIT: pygame.quit() sys.exit() if event.type==pygame.MOUSEBUTTONDOWN: if event.button==1 and mouse_rect.colliderect(card_rect): card = pygame.image.load("1c2.png").convert_alpha() card = pygame.transform.scale(card, (99, 100)) if event.button == 1 and not mouse_rect.colliderect(card_rect): n = pygame.mouse.get_pos() x = n[0] y = n[1] card_rect.centerx = x card_rect.centery = y if event.button==1 and mouse_rect.colliderect(card_rect) and card_rect.width==99: card = pygame.image.load("1c.png").convert_alpha() card = pygame.transform.scale(card, (100, 100)) Original image:1c.png Image selected (with orange edges):1c2.png I try to change a little the width of the card when you select it, and after using that in the last conditional that you can see above. I also tried (in the last conditional too): if event.button==1 and mouse_rect.colliderect(card_rect) and card==pygame.image.load("1c2.png").convert_alpha(): card = pygame.image.load("1c.png").convert_alpha() card = pygame.transform.scale(card, (100, 100)) What can I do to fix it? Thanks! Wrong result: The card stays at the selected image (card with orange borders).
[ "Do not load the images in the application loop. Load the images before the application loop. Use a Boolean variable (card_selected) to indicate if the map is selected. Invert the state when clicking on the card (card_selected = not card_selected):\ncard_1 = pygame.image.load(\"1c.png\").convert_alpha()\ncard_1 = pygame.transform.scale(card_1, (100, 100))\ncard_2 = pygame.image.load(\"1c2.png\").convert_alpha()\ncard_2 = pygame.transform.scale(card_2, (100, 100))\ncard = card_1\ncard_selected = False\n\n# [...]\n\nrun = True\nwhile run:\n for event in pygame.event.get():\n if event.type==pygame.QUIT:\n run = False\n\n if event.type==pygame.MOUSEBUTTONDOWN:\n if event.button == 1 and card_rect.collidepoint(event.pos):\n card_selected = not card_selected\n card = card_2 if card_selected else card_1\n\n # [...]\n\npygame.quit()\nsys.exit()\n\nDo not forget to clear the display in every frame. The entire scene must be redrawn in each frame.\n" ]
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074678805_pygame_python.txt
Q: Tcping from Android for ICMP blocked websites How to tcping from android where icmp blocked? I want to check a website is pingable however icmp is blocked on that server A: To ping a website on an Android device when ICMP is blocked, you can use a TCP ping utility instead. A TCP ping sends a TCP packet to the specified host and port, and waits for a reply. This can be used to check if a website is reachable even if ICMP is blocked on the server. There are several TCP ping utilities available for Android, such as TCPing and TCPing Lite. To use one of these utilities, simply enter the hostname or IP address of the website you want to ping, and the port number (typically 80 for HTTP or 443 for HTTPS). The utility will then send a TCP packet to the specified host and port and display the results, including the response time and any errors that may have occurred. Alternatively, you can use the telnet command on Android to perform a TCP ping. This can be done by opening a terminal emulator app and running the following command: telnet <hostname or IP address> <port> For example, to ping the Google website on port 80, you would run the following command: telnet google.com 80 This will establish a TCP connection to the specified host and port, and display any output or errors that occur. You can then press CTRL + ] to exit the telnet session. Note that using a TCP ping may not provide the same level of accuracy as an ICMP ping, as it does not measure the actual network latency or packet loss. However, it can still be useful for checking if a website is reachable when ICMP is blocked.
Tcping from Android for ICMP blocked websites
How to tcping from android where icmp blocked? I want to check a website is pingable however icmp is blocked on that server
[ "To ping a website on an Android device when ICMP is blocked, you can use a TCP ping utility instead. A TCP ping sends a TCP packet to the specified host and port, and waits for a reply. This can be used to check if a website is reachable even if ICMP is blocked on the server.\nThere are several TCP ping utilities available for Android, such as TCPing and TCPing Lite. To use one of these utilities, simply enter the hostname or IP address of the website you want to ping, and the port number (typically 80 for HTTP or 443 for HTTPS). The utility will then send a TCP packet to the specified host and port and display the results, including the response time and any errors that may have occurred.\nAlternatively, you can use the telnet command on Android to perform a TCP ping. This can be done by opening a terminal emulator app and running the following command:\ntelnet <hostname or IP address> <port>\n\nFor example, to ping the Google website on port 80, you would run the following command:\ntelnet google.com 80\n\nThis will establish a TCP connection to the specified host and port, and display any output or errors that occur. You can then press CTRL + ] to exit the telnet session.\nNote that using a TCP ping may not provide the same level of accuracy as an ICMP ping, as it does not measure the actual network latency or packet loss. However, it can still be useful for checking if a website is reachable when ICMP is blocked.\n" ]
[ 0 ]
[]
[]
[ "android", "icmp", "java", "ping" ]
stackoverflow_0074678840_android_icmp_java_ping.txt
Q: How to check if a service is running on Android? How do I check if a background service is running? I want an Android activity that toggles the state of the service -- it lets me turn it on if it is off and off if it is on. A: I use the following from inside an activity: private boolean isMyServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } And I call it using: isMyServiceRunning(MyService.class) This works reliably, because it is based on the information about running services provided by the Android operating system through ActivityManager#getRunningServices. All the approaches using onDestroy or onSometing events or Binders or static variables will not work reliably because as a developer you never know, when Android decides to kill your process or which of the mentioned callbacks are called or not. Please note the "killable" column in the lifecycle events table in the Android documentation. A: I had the same problem not long ago. Since my service was local, I ended up simply using a static field in the service class to toggle state, as described by hackbod here EDIT (for the record): Here is the solution proposed by hackbod: If your client and server code is part of the same .apk and you are binding to the service with a concrete Intent (one that specifies the exact service class), then you can simply have your service set a global variable when it is running that your client can check. We deliberately don't have an API to check whether a service is running because, nearly without fail, when you want to do something like that you end up with race conditions in your code. A: Got it! You MUST call startService() for your service to be properly registered and passing BIND_AUTO_CREATE will not suffice. Intent bindIntent = new Intent(this,ServiceTask.class); startService(bindIntent); bindService(bindIntent,mConnection,0); And now the ServiceTools class: public class ServiceTools { private static String LOG_TAG = ServiceTools.class.getName(); public static boolean isServiceRunning(String serviceClassName){ final ActivityManager activityManager = (ActivityManager)Application.getContext().getSystemService(Context.ACTIVITY_SERVICE); final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo runningServiceInfo : services) { if (runningServiceInfo.service.getClassName().equals(serviceClassName)){ return true; } } return false; } } A: A small complement is: My goal is to know wether a service is running without actualy running it if it is not running. Calling bindService or calling an intent that can be caught by the service is not a good idea then as it will start the service if it is not running. So, as miracle2k suggested, the best is to have a static field in the service class to know whether the service has been started or not. To make it even cleaner, I suggest to transform the service in a singleton with a very very lazy fetching: that is, there is no instantiation at all of the singleton instance through static methods. The static getInstance method of your service/singleton just returns the instance of the singleton if it has been created. But it doesn't actualy start or instanciate the singleton itself. The service is only started through normal service start methods. It would then be even cleaner to modify the singleton design pattern to rename the confusing getInstance method into something like the isInstanceCreated() : boolean method. The code will look like: public class MyService extends Service { private static MyService instance = null; public static boolean isInstanceCreated() { return instance != null; }//met @Override public void onCreate() { instance = this; .... }//met @Override public void onDestroy() { instance = null; ... }//met }//class This solution is elegant, but it is only relevant if you have access to the service class and only for classes iside the app/package of the service. If your classes are outside of the service app/package then you could query the ActivityManager with limitations underlined by Pieter-Jan Van Robays. A: You can use this (I didn't try this yet, but I hope this works): if(startService(someIntent) != null) { Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show(); } The startService method returns a ComponentName object if there is an already running service. If not, null will be returned. See public abstract ComponentName startService (Intent service). This is not like checking I think, because it's starting the service, so you can add stopService(someIntent); under the code. A: /** * Check if the service is Running * @param serviceClass the class of the Service * * @return true if the service is running otherwise false */ public boolean checkServiceRunning(Class<?> serviceClass){ ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } A: An extract from Android docs: Like sendBroadcast(Intent), but if there are any receivers for the Intent this function will block and immediately dispatch them before returning. Think of this hack as "pinging" the Service. Since we can broadcast synchronously, we can broadcast and get a result synchronously, on the UI thread. Service @Override public void onCreate() { LocalBroadcastManager .getInstance(this) .registerReceiver(new ServiceEchoReceiver(), new IntentFilter("ping")); //do not forget to deregister the receiver when the service is destroyed to avoid //any potential memory leaks } private class ServiceEchoReceiver extends BroadcastReceiver { public void onReceive (Context context, Intent intent) { LocalBroadcastManager .getInstance(this) .sendBroadcastSync(new Intent("pong")); } } Activity bool serviceRunning = false; protected void onCreate (Bundle savedInstanceState){ LocalBroadcastManager.getInstance(this).registerReceiver(pong, new IntentFilter("pong")); LocalBroadcastManager.getInstance(this).sendBroadcastSync(new Intent("ping")); if(!serviceRunning){ //run the service } } private BroadcastReceiver pong = new BroadcastReceiver(){ public void onReceive (Context context, Intent intent) { serviceRunning = true; } } The winner in many applications is, of course, a static boolean field on the service that is set to true in Service.onCreate() and to false in Service.onDestroy() because it's a lot simpler. A: The proper way to check if a service is running is to simply ask it. Implement a BroadcastReceiver in your service that responds to pings from your activities. Register the BroadcastReceiver when the service starts, and unregister it when the service is destroyed. From your activity (or any component), send a local broadcast intent to the service and if it responds, you know it's running. Note the subtle difference between ACTION_PING and ACTION_PONG in the code below. public class PingableService extends Service { public static final String ACTION_PING = PingableService.class.getName() + ".PING"; public static final String ACTION_PONG = PingableService.class.getName() + ".PONG"; public int onStartCommand (Intent intent, int flags, int startId) { LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(ACTION_PING)); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy () { LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver); super.onDestroy(); } private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive (Context context, Intent intent) { if (intent.getAction().equals(ACTION_PING)) { LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getApplicationContext()); manager.sendBroadcast(new Intent(ACTION_PONG)); } } }; } public class MyActivity extends Activity { private boolean isSvcRunning = false; @Override protected void onStart() { LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getApplicationContext()); manager.registerReceiver(mReceiver, new IntentFilter(PingableService.ACTION_PONG)); // the service will respond to this broadcast only if it's running manager.sendBroadcast(new Intent(PingableService.ACTION_PING)); super.onStart(); } @Override protected void onStop() { LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver); super.onStop(); } protected BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive (Context context, Intent intent) { // here you receive the response from the service if (intent.getAction().equals(PingableService.ACTION_PONG)) { isSvcRunning = true; } } }; } A: I have slightly modified one of the solutions presented above, but passing the class instead of a generic string name, in order to be sure to compare strings coming out from the same method class.getName() public class ServiceTools { private static String LOG_TAG = ServiceTools.class.getName(); public static boolean isServiceRunning(Context context,Class<?> serviceClass){ final ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo runningServiceInfo : services) { Log.d(Constants.TAG, String.format("Service:%s", runningServiceInfo.service.getClassName())); if (runningServiceInfo.service.getClassName().equals(serviceClass.getName())){ return true; } } return false; } } and then Boolean isServiceRunning = ServiceTools.isServiceRunning( MainActivity.this.getApplicationContext(), BackgroundIntentService.class); A: Another approach using kotlin. Inspired in other users answers fun isMyServiceRunning(serviceClass: Class<*>): Boolean { val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager return manager.getRunningServices(Integer.MAX_VALUE) .any { it.service.className == serviceClass.name } } As kotlin extension fun Context.isMyServiceRunning(serviceClass: Class<*>): Boolean { val manager = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager return manager.getRunningServices(Integer.MAX_VALUE) .any { it.service.className == serviceClass.name } } Usage context.isMyServiceRunning(MyService::class.java) A: First of all you shouldn't reach the service by using the ActivityManager. (Discussed here) Services can run on their own, be bound to an Activity or both. The way to check in an Activity if your Service is running or not is by making an interface (that extends Binder) where you declare methods that both, the Activity and the Service, understand. You can do this by making your own Interface where you declare for example "isServiceRunning()". You can then bind your Activity to your Service, run the method isServiceRunning(), the Service will check for itself if it is running or not and returns a boolean to your Activity. You can also use this method to stop your Service or interact with it in another way. A: I just want to add a note to the answer by @Snicolas. The following steps can be used to check stop service with/without calling onDestroy(). onDestroy() called: Go to Settings -> Application -> Running Services -> Select and stop your service. onDestroy() not Called: Go to Settings -> Application -> Manage Applications -> Select and "Force Stop" your application in which your service is running. However, as your application is stopped here, so definitely the service instances will also be stopped. Finally, I would like to mention that the approach mentioned there using a static variable in singleton class is working for me. A: onDestroy isn't always called in the service so this is useless! For example: Just run the app again with one change from Eclipse. The application is forcefully exited using SIG: 9. A: Again, another alternative that people might find cleaner if they use pending intents (for instance with the AlarmManager: public static boolean isRunning(Class<? extends Service> serviceClass) { final Intent intent = new Intent(context, serviceClass); return (PendingIntent.getService(context, CODE, intent, PendingIntent.FLAG_NO_CREATE) != null); } Where CODE is a constant that you define privately in your class to identify the pending intents associated to your service. A: Below is an elegant hack that covers all the Ifs. This is for local services only. public final class AService extends Service { private static AService mInstance = null; public static boolean isServiceCreated() { try { // If instance was not cleared but the service was destroyed an Exception will be thrown return mInstance != null && mInstance.ping(); } catch (NullPointerException e) { // destroyed/not-started return false; } } /** * Simply returns true. If the service is still active, this method will be accessible. * @return */ private boolean ping() { return true; } @Override public void onCreate() { mInstance = this; } @Override public void onDestroy() { mInstance = null; } } And then later on: if(AService.isServiceCreated()){ ... }else{ startService(...); } A: Xamarin C# version: private bool isMyServiceRunning(System.Type cls) { ActivityManager manager = (ActivityManager)GetSystemService(Context.ActivityService); foreach (var service in manager.GetRunningServices(int.MaxValue)) { if (service.Service.ClassName.Equals(Java.Lang.Class.FromType(cls).CanonicalName)) { return true; } } return false; } A: For the use-case given here we may simply make use of the stopService() method's return value. It returns true if there exists the specified service and it is killed. Else it returns false. So you may restart the service if the result is false else it is assured that the current service has been stopped. :) It would be better if you have a look at this. A: The response of geekQ but in Kotlin class. Thanks geekQ fun isMyServiceRunning(serviceClass : Class<*> ) : Boolean{ var manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager for (service in manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.name.equals(service.service.className)) { return true } } return false } The call isMyServiceRunning(NewService::class.java) A: In your Service Sub-Class Use a Static Boolean to get the state of the Service as demonstrated below. MyService.kt class MyService : Service() { override fun onCreate() { super.onCreate() isServiceStarted = true } override fun onDestroy() { super.onDestroy() isServiceStarted = false } companion object { var isServiceStarted = false } } MainActivity.kt class MainActivity : AppCompatActivity(){ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val serviceStarted = FileObserverService.isServiceStarted if (!serviceStarted) { val startFileObserverService = Intent(this, FileObserverService::class.java) ContextCompat.startForegroundService(this, startFileObserverService) } } } A: For kotlin, you can use the below code. fun isMyServiceRunning(calssObj: Class<SERVICE_CALL_NAME>): Boolean { val manager = requireActivity().getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager for (service in manager.getRunningServices(Integer.MAX_VALUE)) { if (calssObj.getName().equals(service.service.getClassName())) { return true } } return false } A: In kotlin you can add boolean variable in companion object and check its value from any class you want: companion object{ var isRuning = false } Change it value when service is created and destroyed override fun onCreate() { super.onCreate() isRuning = true } override fun onDestroy() { super.onDestroy() isRuning = false } A: Inside TheServiceClass define: public static Boolean serviceRunning = false; Then In onStartCommand(...) public int onStartCommand(Intent intent, int flags, int startId) { serviceRunning = true; ... } @Override public void onDestroy() { serviceRunning = false; } Then, call if(TheServiceClass.serviceRunning == true) from any class. A: simple use bind with don't create auto - see ps. and update... public abstract class Context { ... /* * @return {true} If you have successfully bound to the service, * {false} is returned if the connection is not made * so you will not receive the service object. */ public abstract boolean bindService(@RequiresPermission Intent service, @NonNull ServiceConnection conn, @BindServiceFlags int flags); example : Intent bindIntent = new Intent(context, Class<Service>); boolean bindResult = context.bindService(bindIntent, ServiceConnection, 0); why not using? getRunningServices() List<ActivityManager.RunningServiceInfo> getRunningServices (int maxNum) Return a list of the services that are currently running. Note: this method is only intended for debugging or implementing service management type user interfaces. ps. android documentation is misleading i have opened an issue on google tracker to eliminate any doubts: https://issuetracker.google.com/issues/68908332 as we can see bind service actually invokes a transaction via ActivityManager binder through Service cache binders - i dint track which service is responsible for binding but as we can see the result for bind is: int res = ActivityManagerNative.getDefault().bindService(...); return res != 0; transaction is made through binder: ServiceManager.getService("activity"); next: public static IBinder getService(String name) { try { IBinder service = sCache.get(name); if (service != null) { return service; } else { return getIServiceManager().getService(name); this is set in ActivityThread via: public final void bindApplication(...) { if (services != null) { // Setup the service cache in the ServiceManager ServiceManager.initServiceCache(services); } this is called in ActivityManagerService in method: private final boolean attachApplicationLocked(IApplicationThread thread, int pid) { ... thread.bindApplication(... , getCommonServicesLocked(),...) then: private HashMap<String, IBinder> getCommonServicesLocked() { but there is no "activity" only window package and alarm.. so we need get back to call: return getIServiceManager().getService(name); sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject()); this makes call through: mRemote.transact(GET_SERVICE_TRANSACTION, data, reply, 0); which leads to : BinderInternal.getContextObject() and this is native method.... /** * Return the global "context object" of the system. This is usually * an implementation of IServiceManager, which you can use to find * other services. */ public static final native IBinder getContextObject(); i don't have time now to dug in c so until i dissect rest call i suspend my answer. but best way for check if service is running is to create bind (if bind is not created service not exist) - and query the service about its state through the bind (using stored internal flag on it state). update 23.06.2018 i found those interesting: /** * Provide a binder to an already-bound service. This method is synchronous * and will not start the target service if it is not present, so it is safe * to call from {@link #onReceive}. * * For peekService() to return a non null {@link android.os.IBinder} interface * the service must have published it before. In other words some component * must have called {@link android.content.Context#bindService(Intent, ServiceConnection, int)} on it. * * @param myContext The Context that had been passed to {@link #onReceive(Context, Intent)} * @param service Identifies the already-bound service you wish to use. See * {@link android.content.Context#bindService(Intent, ServiceConnection, int)} * for more information. */ public IBinder peekService(Context myContext, Intent service) { IActivityManager am = ActivityManager.getService(); IBinder binder = null; try { service.prepareToLeaveProcess(myContext); binder = am.peekService(service, service.resolveTypeIfNeeded( myContext.getContentResolver()), myContext.getOpPackageName()); } catch (RemoteException e) { } return binder; } in short :) "Provide a binder to an already-bound service. This method is synchronous and will not start the target service if it is not present." public IBinder peekService(Intent service, String resolvedType, String callingPackage) throws RemoteException; * public static IBinder peekService(IBinder remote, Intent service, String resolvedType) throws RemoteException { Parcel data = Parcel.obtain(); Parcel reply = Parcel.obtain(); data.writeInterfaceToken("android.app.IActivityManager"); service.writeToParcel(data, 0); data.writeString(resolvedType); remote.transact(android.os.IBinder.FIRST_CALL_TRANSACTION+84, data, reply, 0); reply.readException(); IBinder binder = reply.readStrongBinder(); reply.recycle(); data.recycle(); return binder; } * A: There can be several services with the same class name. I've just created two apps. The package name of the first app is com.example.mock. I created a subpackage called lorem in the app and a service called Mock2Service. So its fully qualified name is com.example.mock.lorem.Mock2Service. Then I created the second app and a service called Mock2Service. The package name of the second app is com.example.mock.lorem. The fully qualified name of the service is com.example.mock.lorem.Mock2Service, too. Here is my logcat output. 03-27 12:02:19.985: D/TAG(32155): Mock-01: com.example.mock.lorem.Mock2Service 03-27 12:02:33.755: D/TAG(32277): Mock-02: com.example.mock.lorem.Mock2Service A better idea is to compare ComponentName instances because equals() of ComponentName compares both package names and class names. And there can't be two apps with the same package name installed on a device. The equals() method of ComponentName. @Override public boolean equals(Object obj) { try { if (obj != null) { ComponentName other = (ComponentName)obj; // Note: no null checks, because mPackage and mClass can // never be null. return mPackage.equals(other.mPackage) && mClass.equals(other.mClass); } } catch (ClassCastException e) { } return false; } ComponentName A: Please use this code. if (isMyServiceRunning(MainActivity.this, xyzService.class)) { // Service class name // Service running } else { // Service Stop } public static boolean isMyServiceRunning(Activity activity, Class<?> serviceClass) { ActivityManager manager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } A: The only efficient/fastest/clean way of detecting if a service is running is to create a PING/PONG functionality. Implement Messenger or AIDL method inside the service: isAlive() - which return the state of the service. Do not implement broadcasts because they can be missed. A: If you have a multi-module application and you want to know that service is running or not from a module that is not depends on the module that contains the service, you can use this function: fun isServiceRunning(context: Context, serviceClassName: String): Boolean { val manager = ContextCompat.getSystemService( context, ActivityManager::class.java ) ?: return false return manager.getRunningServices(Integer.MAX_VALUE).any { serviceInfo -> serviceInfo.service.shortClassName.contains(vpnServiceClassName) } } Usage for MyService service: isServiceRunning(context, "MyService") This function may not work correctly if the service class name changes and the calling function does not change accordingly. A: This applies more towards Intent Service debugging since they spawn a thread, but may work for regular services as well. I found this thread thanks to Binging In my case, I played around with the debugger and found the thread view. It kind of looks like the bullet point icon in MS Word. Anyways, you don't have to be in debugger mode to use it. Click on the process and click on that button. Any Intent Services will show up while they are running, at least on the emulator. A: If the service belongs to another process or APK use the solution based on the ActivityManager. If you have access to its source, just use the solution based on a static field. But instead using a boolean I would suggest using a Date object. While the service is running, just update its value to 'now' and when it finishes set it to null. From the activity you can check if its null or the date is too old which will mean that it is not running. You can also send broadcast notification from your service indicating that is running along further info like progress. A: My kotlin conversion of the ActivityManager::getRunningServices based answers. Put this function in an activity- private fun isMyServiceRunning(serviceClass: Class<out Service>) = (getSystemService(ACTIVITY_SERVICE) as ActivityManager) .getRunningServices(Int.MAX_VALUE) ?.map { it.service.className } ?.contains(serviceClass.name) ?: false A: Since Android 8 (or Oreo), API getRunningServices is deprecated. Of course your can use @SuppressWarnings("deprecation") to get rid of the warning. Here is how to do without getRunninngServices if your service does not need to have more than one instance: use the singleton pattern. public class MyMusicService extends Service { private static MyMusicService instance = null; public static boolean isMyMusicServiceRunning() { return instance != null; } Then you can call the MyMusicService.isMyMusicServiceRunning from your activities or elsewhere. A: Here's good solution I've come up with, but it works only for the Services running in separate processes. This can be achieved by adding 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.
How to check if a service is running on Android?
How do I check if a background service is running? I want an Android activity that toggles the state of the service -- it lets me turn it on if it is off and off if it is on.
[ "I use the following from inside an activity:\nprivate boolean isMyServiceRunning(Class<?> serviceClass) {\n ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);\n for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {\n if (serviceClass.getName().equals(service.service.getClassName())) {\n return true;\n }\n }\n return false;\n}\n\nAnd I call it using:\nisMyServiceRunning(MyService.class)\n\nThis works reliably, because it is based on the information about running services provided by the Android operating system through ActivityManager#getRunningServices.\nAll the approaches using onDestroy or onSometing events or Binders or static variables will not work reliably because as a developer you never know, when Android decides to kill your process or which of the mentioned callbacks are called or not. Please note the \"killable\" column in the lifecycle events table in the Android documentation.\n", "I had the same problem not long ago. Since my service was local, I ended up simply using a static field in the service class to toggle state, as described by hackbod here\nEDIT (for the record):\nHere is the solution proposed by hackbod:\n\nIf your client and server code is part of the same .apk and you are \n binding to the service with a concrete Intent (one that specifies the \n exact service class), then you can simply have your service set a \n global variable when it is running that your client can check. \nWe deliberately don't have an API to check whether a service is \n running because, nearly without fail, when you want to do something \n like that you end up with race conditions in your code. \n\n", "Got it! \nYou MUST call startService() for your service to be properly registered and passing BIND_AUTO_CREATE will not suffice.\nIntent bindIntent = new Intent(this,ServiceTask.class);\nstartService(bindIntent);\nbindService(bindIntent,mConnection,0);\n\nAnd now the ServiceTools class:\npublic class ServiceTools {\n private static String LOG_TAG = ServiceTools.class.getName();\n\n public static boolean isServiceRunning(String serviceClassName){\n final ActivityManager activityManager = (ActivityManager)Application.getContext().getSystemService(Context.ACTIVITY_SERVICE);\n final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);\n\n for (RunningServiceInfo runningServiceInfo : services) {\n if (runningServiceInfo.service.getClassName().equals(serviceClassName)){\n return true;\n }\n }\n return false;\n }\n}\n\n", "A small complement is:\nMy goal is to know wether a service is running without actualy running it if it is not running.\nCalling bindService or calling an intent that can be caught by the service is not a good idea then as it will start the service if it is not running.\nSo, as miracle2k suggested, the best is to have a static field in the service class to know whether the service has been started or not.\nTo make it even cleaner, I suggest to transform the service in a singleton with a very very lazy fetching: that is, there is no instantiation at all of the singleton instance through static methods. The static getInstance method of your service/singleton just returns the instance of the singleton if it has been created. But it doesn't actualy start or instanciate the singleton itself. The service is only started through normal service start methods.\nIt would then be even cleaner to modify the singleton design pattern to rename the confusing getInstance method into something like the isInstanceCreated() : boolean method.\nThe code will look like:\npublic class MyService extends Service\n{\n private static MyService instance = null;\n\n public static boolean isInstanceCreated() {\n return instance != null;\n }//met\n\n @Override\n public void onCreate()\n {\n instance = this;\n ....\n }//met\n\n @Override\n public void onDestroy()\n {\n instance = null;\n ...\n }//met\n}//class\n\nThis solution is elegant, but it is only relevant if you have access to the service class and only for classes iside the app/package of the service. If your classes are outside of the service app/package then you could query the ActivityManager with limitations underlined by Pieter-Jan Van Robays.\n", "You can use this (I didn't try this yet, but I hope this works):\nif(startService(someIntent) != null) {\n Toast.makeText(getBaseContext(), \"Service is already running\", Toast.LENGTH_SHORT).show();\n}\nelse {\n Toast.makeText(getBaseContext(), \"There is no service running, starting service..\", Toast.LENGTH_SHORT).show();\n}\n\nThe startService method returns a ComponentName object if there is an already running service. If not, null will be returned.\nSee public abstract ComponentName startService (Intent service).\nThis is not like checking I think, because it's starting the service, so you can add stopService(someIntent); under the code.\n", "/**\n * Check if the service is Running \n * @param serviceClass the class of the Service\n *\n * @return true if the service is running otherwise false\n */\npublic boolean checkServiceRunning(Class<?> serviceClass){\n ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);\n for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))\n {\n if (serviceClass.getName().equals(service.service.getClassName()))\n {\n return true;\n }\n }\n return false;\n}\n\n", "An extract from Android docs:\n\nLike sendBroadcast(Intent), but if there are any receivers for\n the Intent this function will block and immediately dispatch them\n before returning.\n\nThink of this hack as \"pinging\" the Service. Since we can broadcast synchronously, we can broadcast and get a result synchronously, on the UI thread.\nService\n@Override\npublic void onCreate() {\n LocalBroadcastManager\n .getInstance(this)\n .registerReceiver(new ServiceEchoReceiver(), new IntentFilter(\"ping\"));\n //do not forget to deregister the receiver when the service is destroyed to avoid\n //any potential memory leaks \n}\n\nprivate class ServiceEchoReceiver extends BroadcastReceiver {\n public void onReceive (Context context, Intent intent) {\n LocalBroadcastManager\n .getInstance(this)\n .sendBroadcastSync(new Intent(\"pong\"));\n }\n}\n\nActivity\n bool serviceRunning = false;\n\n protected void onCreate (Bundle savedInstanceState){\n LocalBroadcastManager.getInstance(this).registerReceiver(pong, new IntentFilter(\"pong\"));\n LocalBroadcastManager.getInstance(this).sendBroadcastSync(new Intent(\"ping\"));\n if(!serviceRunning){\n //run the service\n }\n }\n\n private BroadcastReceiver pong = new BroadcastReceiver(){\n public void onReceive (Context context, Intent intent) {\n serviceRunning = true; \n }\n }\n\nThe winner in many applications is, of course, a static boolean field on the service that is set to true in Service.onCreate() and to false in Service.onDestroy() because it's a lot simpler.\n", "The proper way to check if a service is running is to simply ask it. Implement a BroadcastReceiver in your service that responds to pings from your activities. Register the BroadcastReceiver when the service starts, and unregister it when the service is destroyed. From your activity (or any component), send a local broadcast intent to the service and if it responds, you know it's running. Note the subtle difference between ACTION_PING and ACTION_PONG in the code below.\npublic class PingableService extends Service {\n public static final String ACTION_PING = PingableService.class.getName() + \".PING\";\n public static final String ACTION_PONG = PingableService.class.getName() + \".PONG\";\n\n public int onStartCommand (Intent intent, int flags, int startId) {\n LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(ACTION_PING));\n return super.onStartCommand(intent, flags, startId);\n }\n\n @Override\n public void onDestroy () {\n LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);\n super.onDestroy();\n }\n\n private BroadcastReceiver mReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive (Context context, Intent intent) {\n if (intent.getAction().equals(ACTION_PING)) {\n LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getApplicationContext());\n manager.sendBroadcast(new Intent(ACTION_PONG));\n }\n }\n };\n}\n\npublic class MyActivity extends Activity {\n private boolean isSvcRunning = false;\n\n @Override\n protected void onStart() {\n LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getApplicationContext());\n manager.registerReceiver(mReceiver, new IntentFilter(PingableService.ACTION_PONG));\n // the service will respond to this broadcast only if it's running\n manager.sendBroadcast(new Intent(PingableService.ACTION_PING));\n super.onStart();\n }\n\n @Override\n protected void onStop() {\n LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);\n super.onStop();\n }\n\n protected BroadcastReceiver mReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive (Context context, Intent intent) {\n // here you receive the response from the service\n if (intent.getAction().equals(PingableService.ACTION_PONG)) {\n isSvcRunning = true;\n }\n }\n };\n}\n\n", "I have slightly modified one of the solutions presented above, but passing the class instead of a generic string name, in order to be sure to compare strings coming out from the same method class.getName()\npublic class ServiceTools {\n private static String LOG_TAG = ServiceTools.class.getName();\n\n public static boolean isServiceRunning(Context context,Class<?> serviceClass){\n final ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);\n final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);\n\n for (RunningServiceInfo runningServiceInfo : services) {\n Log.d(Constants.TAG, String.format(\"Service:%s\", runningServiceInfo.service.getClassName()));\n if (runningServiceInfo.service.getClassName().equals(serviceClass.getName())){\n return true;\n }\n }\n return false;\n }\n}\n\nand then\nBoolean isServiceRunning = ServiceTools.isServiceRunning(\n MainActivity.this.getApplicationContext(),\n BackgroundIntentService.class);\n\n", "Another approach using kotlin. Inspired in other users answers\nfun isMyServiceRunning(serviceClass: Class<*>): Boolean {\n val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager\n return manager.getRunningServices(Integer.MAX_VALUE)\n .any { it.service.className == serviceClass.name }\n}\n\nAs kotlin extension \nfun Context.isMyServiceRunning(serviceClass: Class<*>): Boolean {\n val manager = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager\n return manager.getRunningServices(Integer.MAX_VALUE)\n .any { it.service.className == serviceClass.name }\n}\n\nUsage\ncontext.isMyServiceRunning(MyService::class.java)\n\n", "First of all you shouldn't reach the service by using the ActivityManager. (Discussed here)\nServices can run on their own, be bound to an Activity or both. The way to check in an Activity if your Service is running or not is by making an interface (that extends Binder) where you declare methods that both, the Activity and the Service, understand. You can do this by making your own Interface where you declare for example \"isServiceRunning()\".\nYou can then bind your Activity to your Service, run the method isServiceRunning(), the Service will check for itself if it is running or not and returns a boolean to your Activity.\nYou can also use this method to stop your Service or interact with it in another way.\n", "I just want to add a note to the answer by @Snicolas. The following steps can be used to check stop service with/without calling onDestroy().\n\nonDestroy() called: Go to Settings -> Application -> Running Services -> Select and stop your service.\nonDestroy() not Called: Go to Settings -> Application -> Manage Applications -> Select and \"Force Stop\" your application in which your service is running. However, as your application is stopped here, so definitely the service instances will also be stopped.\n\nFinally, I would like to mention that the approach mentioned there using a static variable in singleton class is working for me.\n", "onDestroy isn't always called in the service so this is useless! \nFor example: Just run the app again with one change from Eclipse. The application is forcefully exited using SIG: 9.\n", "Again, another alternative that people might find cleaner if they use pending intents (for instance with the AlarmManager: \npublic static boolean isRunning(Class<? extends Service> serviceClass) {\n final Intent intent = new Intent(context, serviceClass);\n return (PendingIntent.getService(context, CODE, intent, PendingIntent.FLAG_NO_CREATE) != null);\n}\n\nWhere CODE is a constant that you define privately in your class to identify the pending intents associated to your service.\n", "Below is an elegant hack that covers all the Ifs. This is for local services only.\n public final class AService extends Service {\n\n private static AService mInstance = null;\n\n public static boolean isServiceCreated() {\n try {\n // If instance was not cleared but the service was destroyed an Exception will be thrown\n return mInstance != null && mInstance.ping();\n } catch (NullPointerException e) {\n // destroyed/not-started\n return false;\n }\n }\n\n /**\n * Simply returns true. If the service is still active, this method will be accessible.\n * @return\n */\n private boolean ping() {\n return true;\n }\n\n @Override\n public void onCreate() {\n mInstance = this;\n }\n\n @Override\n public void onDestroy() {\n mInstance = null;\n }\n }\n\nAnd then later on:\n if(AService.isServiceCreated()){\n ...\n }else{\n startService(...);\n }\n\n", "Xamarin C# version:\nprivate bool isMyServiceRunning(System.Type cls)\n{\n ActivityManager manager = (ActivityManager)GetSystemService(Context.ActivityService);\n\n foreach (var service in manager.GetRunningServices(int.MaxValue)) {\n if (service.Service.ClassName.Equals(Java.Lang.Class.FromType(cls).CanonicalName)) {\n return true;\n }\n }\n return false;\n}\n\n", "For the use-case given here we may simply make use of the stopService() method's return value. It returns true if there exists the specified service and it is killed. Else it returns false. So you may restart the service if the result is false else it is assured that the current service has been stopped. :) It would be better if you have a look at this.\n", "\nThe response of geekQ but in Kotlin class. Thanks geekQ \n\nfun isMyServiceRunning(serviceClass : Class<*> ) : Boolean{\n var manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager\n for (service in manager.getRunningServices(Integer.MAX_VALUE)) {\n if (serviceClass.name.equals(service.service.className)) {\n return true\n }\n }\n return false\n}\n\nThe call\nisMyServiceRunning(NewService::class.java)\n\n", "In your Service Sub-Class Use a Static Boolean to get the state of the Service as demonstrated below.\nMyService.kt\nclass MyService : Service() {\n override fun onCreate() {\n super.onCreate()\n isServiceStarted = true\n }\n override fun onDestroy() {\n super.onDestroy()\n isServiceStarted = false\n }\n companion object {\n var isServiceStarted = false\n }\n}\n\nMainActivity.kt\nclass MainActivity : AppCompatActivity(){\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n\n val serviceStarted = FileObserverService.isServiceStarted\n if (!serviceStarted) {\n val startFileObserverService = Intent(this, FileObserverService::class.java)\n ContextCompat.startForegroundService(this, startFileObserverService)\n }\n }\n}\n\n", "For kotlin, you can use the below code.\nfun isMyServiceRunning(calssObj: Class<SERVICE_CALL_NAME>): Boolean {\n val manager = requireActivity().getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager\n for (service in manager.getRunningServices(Integer.MAX_VALUE)) {\n if (calssObj.getName().equals(service.service.getClassName())) {\n return true\n }\n }\n return false\n}\n\n", "In kotlin you can add boolean variable in companion object and check its value from any class you want: \ncompanion object{\n var isRuning = false\n\n}\n\nChange it value when service is created and destroyed\n override fun onCreate() {\n super.onCreate()\n isRuning = true\n }\n\noverride fun onDestroy() {\n super.onDestroy()\n isRuning = false\n }\n\n", "Inside TheServiceClass define:\n public static Boolean serviceRunning = false;\n\nThen In onStartCommand(...) \n public int onStartCommand(Intent intent, int flags, int startId) {\n\n serviceRunning = true;\n ...\n}\n\n @Override\npublic void onDestroy()\n{\n serviceRunning = false;\n\n} \n\nThen, call if(TheServiceClass.serviceRunning == true) from any class.\n", "simple use bind with don't create auto - see ps. and update...\npublic abstract class Context {\n\n ... \n\n /*\n * @return {true} If you have successfully bound to the service, \n * {false} is returned if the connection is not made \n * so you will not receive the service object.\n */\n public abstract boolean bindService(@RequiresPermission Intent service,\n @NonNull ServiceConnection conn, @BindServiceFlags int flags);\n\nexample :\n Intent bindIntent = new Intent(context, Class<Service>);\n boolean bindResult = context.bindService(bindIntent, ServiceConnection, 0);\n\nwhy not using? getRunningServices() \nList<ActivityManager.RunningServiceInfo> getRunningServices (int maxNum)\nReturn a list of the services that are currently running.\n\nNote: this method is only intended for debugging or implementing service management type user interfaces.\n\nps. android documentation is misleading i have opened an issue on google tracker to eliminate any doubts:\nhttps://issuetracker.google.com/issues/68908332\nas we can see bind service actually invokes a transaction via ActivityManager binder through Service cache binders - i dint track which service is responsible for binding but as we can see the result for bind is:\nint res = ActivityManagerNative.getDefault().bindService(...);\nreturn res != 0;\n\ntransaction is made through binder:\nServiceManager.getService(\"activity\");\n\nnext:\n public static IBinder getService(String name) {\n try {\n IBinder service = sCache.get(name);\n if (service != null) {\n return service;\n } else {\n return getIServiceManager().getService(name);\n\nthis is set in ActivityThread via:\n public final void bindApplication(...) {\n\n if (services != null) {\n // Setup the service cache in the ServiceManager\n ServiceManager.initServiceCache(services);\n }\n\nthis is called in ActivityManagerService in method:\n private final boolean attachApplicationLocked(IApplicationThread thread,\n int pid) {\n ...\n thread.bindApplication(... , getCommonServicesLocked(),...)\n\nthen: \n private HashMap<String, IBinder> getCommonServicesLocked() {\n\nbut there is no \"activity\" only window package and alarm..\nso we need get back to call: \n return getIServiceManager().getService(name);\n\n sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());\n\nthis makes call through:\n mRemote.transact(GET_SERVICE_TRANSACTION, data, reply, 0);\n\nwhich leads to :\nBinderInternal.getContextObject()\n\nand this is native method....\n /**\n * Return the global \"context object\" of the system. This is usually\n * an implementation of IServiceManager, which you can use to find\n * other services.\n */\n public static final native IBinder getContextObject();\n\ni don't have time now to dug in c so until i dissect rest call i suspend my answer.\nbut best way for check if service is running is to create bind (if bind is not created service not exist) - and query the service about its state through the bind (using stored internal flag on it state).\nupdate 23.06.2018\ni found those interesting:\n/**\n * Provide a binder to an already-bound service. This method is synchronous\n * and will not start the target service if it is not present, so it is safe\n * to call from {@link #onReceive}.\n *\n * For peekService() to return a non null {@link android.os.IBinder} interface\n * the service must have published it before. In other words some component\n * must have called {@link android.content.Context#bindService(Intent, ServiceConnection, int)} on it.\n *\n * @param myContext The Context that had been passed to {@link #onReceive(Context, Intent)}\n * @param service Identifies the already-bound service you wish to use. See\n * {@link android.content.Context#bindService(Intent, ServiceConnection, int)}\n * for more information.\n */\npublic IBinder peekService(Context myContext, Intent service) {\n IActivityManager am = ActivityManager.getService();\n IBinder binder = null;\n try {\n service.prepareToLeaveProcess(myContext);\n binder = am.peekService(service, service.resolveTypeIfNeeded(\n myContext.getContentResolver()), myContext.getOpPackageName());\n } catch (RemoteException e) {\n }\n return binder;\n}\n\nin short :) \n\"Provide a binder to an already-bound service. This method is synchronous and will not start the target service if it is not present.\"\npublic IBinder peekService(Intent service, String resolvedType,\n String callingPackage) throws RemoteException;\n\n*\n\npublic static IBinder peekService(IBinder remote, Intent service, String resolvedType)\n throws RemoteException {\n Parcel data = Parcel.obtain();\n Parcel reply = Parcel.obtain();\n data.writeInterfaceToken(\"android.app.IActivityManager\");\n service.writeToParcel(data, 0);\n data.writeString(resolvedType);\n remote.transact(android.os.IBinder.FIRST_CALL_TRANSACTION+84, data, reply, 0);\n reply.readException();\n IBinder binder = reply.readStrongBinder();\n reply.recycle();\n data.recycle();\n return binder;\n}\n\n\n*\n\n", "There can be several services with the same class name. \nI've just created two apps. The package name of the first app is com.example.mock. I created a subpackage called lorem in the app and a service called Mock2Service. So its fully qualified name is com.example.mock.lorem.Mock2Service.\nThen I created the second app and a service called Mock2Service. The package name of the second app is com.example.mock.lorem. The fully qualified name of the service is com.example.mock.lorem.Mock2Service, too.\nHere is my logcat output.\n03-27 12:02:19.985: D/TAG(32155): Mock-01: com.example.mock.lorem.Mock2Service\n03-27 12:02:33.755: D/TAG(32277): Mock-02: com.example.mock.lorem.Mock2Service\n\nA better idea is to compare ComponentName instances because equals() of ComponentName compares both package names and class names. And there can't be two apps with the same package name installed on a device.\nThe equals() method of ComponentName.\n@Override\npublic boolean equals(Object obj) {\n try {\n if (obj != null) {\n ComponentName other = (ComponentName)obj;\n // Note: no null checks, because mPackage and mClass can\n // never be null.\n return mPackage.equals(other.mPackage)\n && mClass.equals(other.mClass);\n }\n } catch (ClassCastException e) {\n }\n return false;\n}\n\nComponentName\n", "Please use this code. \nif (isMyServiceRunning(MainActivity.this, xyzService.class)) { // Service class name\n // Service running\n} else {\n // Service Stop\n}\n\n\npublic static boolean isMyServiceRunning(Activity activity, Class<?> serviceClass) {\n ActivityManager manager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);\n for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {\n if (serviceClass.getName().equals(service.service.getClassName())) {\n return true;\n }\n }\n return false;\n }\n\n", "The only efficient/fastest/clean way of detecting if a service is running is to create a PING/PONG functionality.\nImplement Messenger or AIDL method inside the service: isAlive() - which return the state of the service.\nDo not implement broadcasts because they can be missed.\n", "If you have a multi-module application and you want to know that service is running or not from a module that is not depends on the module that contains the service, you can use this function:\nfun isServiceRunning(context: Context, serviceClassName: String): Boolean {\n\n val manager = ContextCompat.getSystemService(\n context,\n ActivityManager::class.java\n ) ?: return false\n\n return manager.getRunningServices(Integer.MAX_VALUE).any { serviceInfo ->\n serviceInfo.service.shortClassName.contains(vpnServiceClassName)\n }\n}\n\nUsage for MyService service:\nisServiceRunning(context, \"MyService\")\n\n\nThis function may not work correctly if the service class name changes and the calling function does not change accordingly.\n\n", "This applies more towards Intent Service debugging since they spawn a thread, but may work for regular services as well. I found this thread thanks to Binging\nIn my case, I played around with the debugger and found the thread view. It kind of looks like the bullet point icon in MS Word. Anyways, you don't have to be in debugger mode to use it. Click on the process and click on that button. Any Intent Services will show up while they are running, at least on the emulator.\n", "If the service belongs to another process or APK use the solution based on the ActivityManager.\nIf you have access to its source, just use the solution based on a static field. But instead using a boolean I would suggest using a Date object. While the service is running, just update its value to 'now' and when it finishes set it to null. From the activity you can check if its null or the date is too old which will mean that it is not running.\nYou can also send broadcast notification from your service indicating that is running along further info like progress.\n", "My kotlin conversion of the ActivityManager::getRunningServices based answers. Put this function in an activity-\nprivate fun isMyServiceRunning(serviceClass: Class<out Service>) =\n (getSystemService(ACTIVITY_SERVICE) as ActivityManager)\n .getRunningServices(Int.MAX_VALUE)\n ?.map { it.service.className }\n ?.contains(serviceClass.name) ?: false\n\n", "Since Android 8 (or Oreo), API getRunningServices is deprecated.\nOf course your can use @SuppressWarnings(\"deprecation\") to get rid of the warning.\nHere is how to do without getRunninngServices if your service does not need to have more than one instance: use the singleton pattern.\npublic class MyMusicService extends Service {\n\n private static MyMusicService instance = null;\n \n public static boolean isMyMusicServiceRunning() {\n return instance != null;\n }\n\nThen you can call the MyMusicService.isMyMusicServiceRunning from your activities or elsewhere.\n", "Here's good solution I've come up with, but it works only for the Services running in separate processes. This can be achieved by adding 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.\n" ]
[ 1767, 314, 81, 64, 31, 29, 25, 15, 14, 14, 9, 9, 8, 8, 8, 7, 6, 3, 3, 3, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0 ]
[ "Take it easy guys... :)\nI think the most suitable solution is holding a key-value pair in SharedPreferences about if the service is running or not.\nLogic is very straight; at any desired position in your service class; put a boolean value which will act as a flag for you about whether the service is running or not. Then read this value whereever you want in your application.\nA sample code which I am using in my app is below:\nIn my Service class (A service for Audio Stream), I execute the following code when the service is up;\nprivate void updatePlayerStatus(boolean isRadioPlaying)\n{\n SharedPreferences sharedPref = this.getSharedPreferences(getString(R.string.str_shared_file_name), Context.MODE_PRIVATE);\n SharedPreferences.Editor editor = sharedPref.edit();\n editor.putBoolean(getString(R.string.str_shared_file_radio_status_key), isRadioPlaying);\n editor.commit();\n}\n\nThen in any activity of my application, I am checking the status of the service with the help of following code;\nprivate boolean isRadioRunning() {\n SharedPreferences sharedPref = this.getSharedPreferences(getString(R.string.str_shared_file_name), Context.MODE_PRIVATE);\n\n return sharedPref.getBoolean(getString(R.string.str_shared_file_radio_status_key), false);\n}\n\nNo special permissions, no loops... Easy way, clean solution :)\nIf you need extra information, please refer the link \nHope this helps.\n", "It is possible for you to use this options from the Android Developer options to see if your service is still running in the background.\n1. Open Settings in your Android device.\n2. Find Developer Options.\n3. Find Running Services option.\n4. Find your app icon.\n5. You will then see all the service that belongs to your app running in the background.\n\n" ]
[ -5, -7 ]
[ "android", "android_service" ]
stackoverflow_0000600207_android_android_service.txt
Q: Controller Reconcile on object changes Im trying to listen to secret change using the operator sdk The problem is that im not getting the reconcile event when I apply the secret with the labels that I define in the operator I did the following mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ Scheme: scheme, … NewCache: cache.BuilderWithOptions(cache.Options{ SelectorsByObject: cache.SelectorsByObject{ &corev1.Secret{}: { Label: labels.SelectorFromSet(labels.Set{"foo": "bar"}), }, }, }), I run the operator and apply the following secret and the reconcile is not invoked, any idea? apiVersion: v1 kind: Secret metadata: labels: foo: bar name: mysecret namespace: dev type: Opaque data: USER_NAME: YWRtaW4= PASSWORD: dGVzdBo= A: It looks like you are using the cache.Options.SelectorsByObject field to specify the labels that should trigger a reconcile event. However, this field is used to specify the labels that should be used to select objects from the cache, not the labels that should trigger a reconcile event. To specify the labels that should trigger a reconcile event, you can use the ctrl.Watch function, like this: mgr.Watch(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestForObject{}, predicate.Funcs{ UpdateFunc: func(e event.UpdateEvent) bool { return labels.Set(e.MetaNew.GetLabels()).Has("foo", "bar") }, })
Controller Reconcile on object changes
Im trying to listen to secret change using the operator sdk The problem is that im not getting the reconcile event when I apply the secret with the labels that I define in the operator I did the following mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ Scheme: scheme, … NewCache: cache.BuilderWithOptions(cache.Options{ SelectorsByObject: cache.SelectorsByObject{ &corev1.Secret{}: { Label: labels.SelectorFromSet(labels.Set{"foo": "bar"}), }, }, }), I run the operator and apply the following secret and the reconcile is not invoked, any idea? apiVersion: v1 kind: Secret metadata: labels: foo: bar name: mysecret namespace: dev type: Opaque data: USER_NAME: YWRtaW4= PASSWORD: dGVzdBo=
[ "It looks like you are using the cache.Options.SelectorsByObject field to specify the labels that should trigger a reconcile event. However, this field is used to specify the labels that should be used to select objects from the cache, not the labels that should trigger a reconcile event.\nTo specify the labels that should trigger a reconcile event, you can use the ctrl.Watch function, like this:\nmgr.Watch(&source.Kind{Type: &corev1.Secret{}},\n &handler.EnqueueRequestForObject{},\n predicate.Funcs{\n UpdateFunc: func(e event.UpdateEvent) bool {\n return labels.Set(e.MetaNew.GetLabels()).Has(\"foo\", \"bar\")\n },\n })\n\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "go", "kubebuilder", "kubernetes" ]
stackoverflow_0074677080_amazon_web_services_go_kubebuilder_kubernetes.txt
Q: Python interact with OS cmd I would like to know if it was possible via the OS module to iterate on several lines with the command prompt Here is an example of what I would have liked to do but which does not work (non-persistent session): from os import popen, system, getlogin system(f'cd C:/Users/{getlogin()}') print(popen('pip freeze')) A: I tested this on Windows and it worked with check_output from subprocess, using cmd /C to execute both commands and exit from os import getlogin from subprocess import check_output cmd_str = fr'cmd.exe /C "cd C:\Users\{getlogin()} && pip freeze"' output = check_output(cmd_str, shell=True).decode() for line in output.split('\r\n'): print(line) output: absl-py==1.3.0 aiohttp==3.7.3 altgraph==0.17 astroid==2.4.2 astunparse==1.6.3 ..... A: It is not possible to use the popen or system functions from the os module to iterate over multiple lines with the command prompt. These functions are designed to run a single command and return the output or result as a string. In order to iterate over multiple lines with the command prompt, you would need to use a different approach, such as spawning a new shell process using the subprocess module and then using the stdin and stdout streams to interact with the command prompt. Here is an example of how you might do this: import subprocess from os import getlogin # Spawn a new shell process p = subprocess.Popen(['cmd'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) # Change the working directory to the user's home directory p.stdin.write(f'cd C:/Users/{getlogin()}\n') # Run the pip freeze command p.stdin.write('pip freeze\n') # Read the output of the command output = p.stdout.read() # Print the output to the console print(output) In this example, the subprocess module is used to spawn a new shell process and create stdin and stdout streams for interacting with the command prompt. The cd command is then used to change the working directory, and the pip freeze command is run. The output of the command is read from the stdout stream and printed to the console. Hope this helps!
Python interact with OS cmd
I would like to know if it was possible via the OS module to iterate on several lines with the command prompt Here is an example of what I would have liked to do but which does not work (non-persistent session): from os import popen, system, getlogin system(f'cd C:/Users/{getlogin()}') print(popen('pip freeze'))
[ "I tested this on Windows and it worked with check_output from subprocess, using cmd /C to execute both commands and exit\nfrom os import getlogin\nfrom subprocess import check_output\n\ncmd_str = fr'cmd.exe /C \"cd C:\\Users\\{getlogin()} && pip freeze\"'\n\noutput = check_output(cmd_str, shell=True).decode()\nfor line in output.split('\\r\\n'):\n print(line)\n\noutput:\nabsl-py==1.3.0\naiohttp==3.7.3\naltgraph==0.17\nastroid==2.4.2\nastunparse==1.6.3\n.....\n\n", "It is not possible to use the popen or system functions from the os module to iterate over multiple lines with the command prompt. These functions are designed to run a single command and return the output or result as a string. In order to iterate over multiple lines with the command prompt, you would need to use a different approach, such as spawning a new shell process using the subprocess module and then using the stdin and stdout streams to interact with the command prompt. Here is an example of how you might do this:\nimport subprocess\nfrom os import getlogin\n\n# Spawn a new shell process\np = subprocess.Popen(['cmd'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n\n# Change the working directory to the user's home directory\np.stdin.write(f'cd C:/Users/{getlogin()}\\n')\n\n# Run the pip freeze command\np.stdin.write('pip freeze\\n')\n\n# Read the output of the command\noutput = p.stdout.read()\n\n# Print the output to the console\nprint(output)\n\nIn this example, the subprocess module is used to spawn a new shell process and create stdin and stdout streams for interacting with the command prompt. The cd command is then used to change the working directory, and the pip freeze command is run. The output of the command is read from the stdout stream and printed to the console.\nHope this helps!\n" ]
[ 1, 0 ]
[]
[]
[ "cmd", "python", "python_os" ]
stackoverflow_0074677640_cmd_python_python_os.txt
Q: i have a problem when making file .env in Vs. the file icon is wrong. help me enter image description here it must be like this. the iconenter image description here A: It's probably caused by an icon image extension, the icons are changed by those kind of extensions. A: Install VSCode Great Icons from VsCode>Extensions The icons will look like below image, and there no problem with your .env file even if you don't install the extensions, it's the other extension which causing this kind of image. Without any image Extension the default .env file icon will look like settings icon.
i have a problem when making file .env in Vs. the file icon is wrong. help me
enter image description here it must be like this. the iconenter image description here
[ "It's probably caused by an icon image extension,\nthe icons are changed by those kind of extensions.\n", "Install VSCode Great Icons from VsCode>Extensions\nThe icons will look like below image, and there no problem with your .env file even if you don't install the extensions, it's the other extension which causing this kind of image.\nWithout any image Extension the default .env file icon will look like settings icon.\n\n" ]
[ 0, 0 ]
[]
[]
[ ".env" ]
stackoverflow_0074678816_.env.txt
Q: Does sonar cloud support decorative messages for Python in a GitHub PR with workflow? I used the generic workflow https://github.com/SonarSource/sonarcloud-github-action-samples/blob/generic/.github/workflows/build.yml as suggested in the docs. But I'm not receiving the message from the bot in the repository, code is analyzed just fine and I can see it in the website. workflow name: CI on: push: branches: [ "main", "develop" ] pull_request: branches: [ "main", "develop" ] types: [opened, synchronize, reopened] workflow_dispatch: permissions: pull-requests: read # allows SonarCloud to decorate PRs with analysis results jobs: sonar_cloud_report: runs-on: ubuntu-latest steps: - uses : actions/checkout@v3 - uses: ./.github/actions/dependencies - uses: SonarSource/sonarcloud-github-action@master env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} # Generate a token on Sonarcloud.io, add it to the secrets of this repo with the name SONAR_TOKEN (Settings > Secrets > Actions > add new repository secret) with: # Additional arguments for the sonarcloud scanner args: # Unique keys of your project and organization. You can find them in SonarCloud > Information (bottom-left menu) # mandatory -Dsonar.projectKey=XXX -Dsonar.organization=XXX -Dsonar.scm.provider=git # Comma-separated paths to directories containing main source files. #-Dsonar.sources= # optional, default is project base directory # When you need the analysis to take place in a directory other than the one from which it was launched #-Dsonar.projectBaseDir= # optional, default is . # Comma-separated paths to directories containing test source files. #-Dsonar.tests= # optional. For more info about Code Coverage, please refer to https://docs.sonarcloud.io/enriching/test-coverage/overview/ # Adds more detail to both client and server-side analysis logs, activating DEBUG mode for the scanner, and adding client-side environment variables and system properties to the server-side log of analysis report processing. #-Dsonar.verbose= # optional, default is false - name: SonarCloud Scan uses: SonarSource/sonarcloud-github-action@master env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} sonar-project.properties sonar.projectKey=XXX sonar.organization=XXX sonar.verbose=true sonar.python.coverage.reportPaths=coverage.xml # This is the name and version displayed in the SonarCloud UI. #sonar.projectName=XXX #sonar.projectVersion=1.0 # Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows. #sonar.sources=. # Encoding of the source code. Default is default system encoding #sonar.sourceEncoding=UTF-8 A: Yes, SonarCloud does support decorating pull requests with analysis results for Python projects. In order for this to work, your GitHub workflow needs to include the pull-requests permission and use the SonarSource/sonarcloud-github-action action to run the SonarCloud analysis. Based on the information you provided, it looks like your workflow is correctly set up to run the analysis and decorate pull requests. However, there are a few things you can check to troubleshoot this issue: Make sure that your SonarCloud organization and project keys are correct in the sonar-project.properties file and the args section of the workflow. Check if your repository has the pull-requests permission enabled. You can do this by going to the repository settings in GitHub and looking for the "SonarCloud" section under "Permissions". Verify that the SONAR_TOKEN secret is correctly set up in your repository. You can do this by going to the repository settings in GitHub, selecting the "Secrets" tab, and looking for the SONAR_TOKEN secret. If you are running the analysis on a pull request, make sure that the pull request is targeting the correct branch (e.g. main or develop) and that the sonar.projectKey and sonar.organization properties are correct in the sonar-project.properties file. If you are still having trouble with this, you may want to check the logs of the SonarCloud Scan step in your workflow to see if there are any error messages or other information that can help you troubleshoot the issue. You can also contact the SonarCloud support team for further assistance. A: To receive a message from the bot in your repository, you need to set up webhooks in your repository. Go to your repository on GitHub and click on "Settings". In the left menu, click on "Webhooks". Click on the "Add webhook" button. In the "Payload URL" field, enter the URL of the webhook. This is typically in the format https:/// (e.g. https://mycompany.com/webhooks). In the "Content type" field, select the appropriate content type (e.g. "application/json"). In the "Secret" field, enter the secret token that you want to use to verify the authenticity of the webhook request. In the "Which events would you like to trigger this webhook?" section, select the events that you want to trigger the webhook (e.g. "Push", "Pull request"). Click on the "Add webhook" button to save the webhook. After you have set up the webhook, the bot should be able to send messages to your repository. You may need to configure your bot to use the webhook URL and secret that you provided in the previous steps.
Does sonar cloud support decorative messages for Python in a GitHub PR with workflow?
I used the generic workflow https://github.com/SonarSource/sonarcloud-github-action-samples/blob/generic/.github/workflows/build.yml as suggested in the docs. But I'm not receiving the message from the bot in the repository, code is analyzed just fine and I can see it in the website. workflow name: CI on: push: branches: [ "main", "develop" ] pull_request: branches: [ "main", "develop" ] types: [opened, synchronize, reopened] workflow_dispatch: permissions: pull-requests: read # allows SonarCloud to decorate PRs with analysis results jobs: sonar_cloud_report: runs-on: ubuntu-latest steps: - uses : actions/checkout@v3 - uses: ./.github/actions/dependencies - uses: SonarSource/sonarcloud-github-action@master env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} # Generate a token on Sonarcloud.io, add it to the secrets of this repo with the name SONAR_TOKEN (Settings > Secrets > Actions > add new repository secret) with: # Additional arguments for the sonarcloud scanner args: # Unique keys of your project and organization. You can find them in SonarCloud > Information (bottom-left menu) # mandatory -Dsonar.projectKey=XXX -Dsonar.organization=XXX -Dsonar.scm.provider=git # Comma-separated paths to directories containing main source files. #-Dsonar.sources= # optional, default is project base directory # When you need the analysis to take place in a directory other than the one from which it was launched #-Dsonar.projectBaseDir= # optional, default is . # Comma-separated paths to directories containing test source files. #-Dsonar.tests= # optional. For more info about Code Coverage, please refer to https://docs.sonarcloud.io/enriching/test-coverage/overview/ # Adds more detail to both client and server-side analysis logs, activating DEBUG mode for the scanner, and adding client-side environment variables and system properties to the server-side log of analysis report processing. #-Dsonar.verbose= # optional, default is false - name: SonarCloud Scan uses: SonarSource/sonarcloud-github-action@master env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} sonar-project.properties sonar.projectKey=XXX sonar.organization=XXX sonar.verbose=true sonar.python.coverage.reportPaths=coverage.xml # This is the name and version displayed in the SonarCloud UI. #sonar.projectName=XXX #sonar.projectVersion=1.0 # Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows. #sonar.sources=. # Encoding of the source code. Default is default system encoding #sonar.sourceEncoding=UTF-8
[ "Yes, SonarCloud does support decorating pull requests with analysis results for Python projects. In order for this to work, your GitHub workflow needs to include the pull-requests permission and use the SonarSource/sonarcloud-github-action action to run the SonarCloud analysis.\nBased on the information you provided, it looks like your workflow is correctly set up to run the analysis and decorate pull requests. However, there are a few things you can check to troubleshoot this issue:\nMake sure that your SonarCloud organization and project keys are correct in the sonar-project.properties file and the args section of the workflow.\nCheck if your repository has the pull-requests permission enabled. You can do this by going to the repository settings in GitHub and looking for the \"SonarCloud\" section under \"Permissions\".\nVerify that the SONAR_TOKEN secret is correctly set up in your repository. You can do this by going to the repository settings in GitHub, selecting the \"Secrets\" tab, and looking for the SONAR_TOKEN secret.\nIf you are running the analysis on a pull request, make sure that the pull request is targeting the correct branch (e.g. main or develop) and that the sonar.projectKey and sonar.organization properties are correct in the sonar-project.properties file.\nIf you are still having trouble with this, you may want to check the logs of the SonarCloud Scan step in your workflow to see if there are any error messages or other information that can help you troubleshoot the issue. You can also contact the SonarCloud support team for further assistance.\n", "To receive a message from the bot in your repository, you need to set up webhooks in your repository.\n\nGo to your repository on GitHub and click on \"Settings\".\nIn the left menu, click on \"Webhooks\".\nClick on the \"Add webhook\" button.\nIn the \"Payload URL\" field, enter the URL of the webhook. This is typically in the format https:/// (e.g. https://mycompany.com/webhooks).\nIn the \"Content type\" field, select the appropriate content type (e.g. \"application/json\").\nIn the \"Secret\" field, enter the secret token that you want to use to verify the authenticity of the webhook request.\nIn the \"Which events would you like to trigger this webhook?\" section, select the events that you want to trigger the webhook (e.g. \"Push\", \"Pull request\").\nClick on the \"Add webhook\" button to save the webhook.\n\nAfter you have set up the webhook, the bot should be able to send messages to your repository. You may need to configure your bot to use the webhook URL and secret that you provided in the previous steps.\n" ]
[ 1, 0 ]
[]
[]
[ "github", "github_actions", "python", "sonarcloud", "workflow" ]
stackoverflow_0074559957_github_github_actions_python_sonarcloud_workflow.txt
Q: Getting text of children tags with CSS selector with Scrapy returns nothing While its a very common question at first, I have tried many different approach to scrap all the text recursively from the following html code, but for some reason none of them worked: <span class="coupon__logo coupon__logo--for-shops"> <span class="amount"><b>20</b>%</span> <span class="type">Cupom</span> </span> What I tried : p.css('span.coupon__logo coupon__logo--for-shops *::text').get() p.css('span.amount ::text').get() p.css('span.amount *::text').get() And even a xpath one: p.xpath('//span[@class="coupon__logo coupon__logo--for-shops"]//text()').get() p.xpath('//span[@class="amount"]//text()').get() The best thing I got was p.css('span.amount *::text').getall(), but it will extract the text from all of the concurrences, what requires me to create a code to organize them individually, while is way better if i could get only the text of the current instance, especially because I'm looping trough many of them, and because it would be vulnerable to any changes from the website . A: instead of getting all the text of all the children of <span class="coupon__logo coupon__logo--for-shops"> you can get the text of specific children. CSS: scrapy shell file:///path/to/file.html In [1]: ' '.join(response.css('span.coupon__logo.coupon__logo--for-shops span *::text').getall()) Out[1]: '20 % Cupom' xpath: scrapy shell file:///path/to/file.html In [1]: ' '.join(response.xpath('//span[@class="coupon__logo coupon__logo--for-shops"]/span//text()').getall()) Out[1]: '20 % Cupom' If you have more span tags and you only want amount and type you can use this: CSS: scrapy shell file:///path/to/file.html In [1]: ' '.join(response.css('span.coupon__logo.coupon__logo--for-shops span.amount *::text, span.type::text').getall()) Out[1]: '20 % Cupom' xpath: scrapy shell file:///path/to/file.html In [1]: ' '.join(response.xpath('//span[@class="coupon__logo coupon__logo--for-shops"]/span[@class="amount" or @class="type"]//text()').getall()) Out[1]: '20 % Cupom'
Getting text of children tags with CSS selector with Scrapy returns nothing
While its a very common question at first, I have tried many different approach to scrap all the text recursively from the following html code, but for some reason none of them worked: <span class="coupon__logo coupon__logo--for-shops"> <span class="amount"><b>20</b>%</span> <span class="type">Cupom</span> </span> What I tried : p.css('span.coupon__logo coupon__logo--for-shops *::text').get() p.css('span.amount ::text').get() p.css('span.amount *::text').get() And even a xpath one: p.xpath('//span[@class="coupon__logo coupon__logo--for-shops"]//text()').get() p.xpath('//span[@class="amount"]//text()').get() The best thing I got was p.css('span.amount *::text').getall(), but it will extract the text from all of the concurrences, what requires me to create a code to organize them individually, while is way better if i could get only the text of the current instance, especially because I'm looping trough many of them, and because it would be vulnerable to any changes from the website .
[ "instead of getting all the text of all the children of <span class=\"coupon__logo coupon__logo--for-shops\"> you can get the text of specific children.\nCSS:\nscrapy shell file:///path/to/file.html\n\nIn [1]: ' '.join(response.css('span.coupon__logo.coupon__logo--for-shops span *::text').getall())\nOut[1]: '20 % Cupom'\n\nxpath:\nscrapy shell file:///path/to/file.html\n\nIn [1]: ' '.join(response.xpath('//span[@class=\"coupon__logo coupon__logo--for-shops\"]/span//text()').getall())\nOut[1]: '20 % Cupom'\n\nIf you have more span tags and you only want amount and type you can use this:\nCSS:\nscrapy shell file:///path/to/file.html\n\nIn [1]: ' '.join(response.css('span.coupon__logo.coupon__logo--for-shops span.amount *::text, span.type::text').getall())\nOut[1]: '20 % Cupom'\n\nxpath:\nscrapy shell file:///path/to/file.html\n\nIn [1]: ' '.join(response.xpath('//span[@class=\"coupon__logo coupon__logo--for-shops\"]/span[@class=\"amount\" or @class=\"type\"]//text()').getall())\nOut[1]: '20 % Cupom'\n\n" ]
[ 1 ]
[]
[]
[ "python_3.x", "scrapy" ]
stackoverflow_0074678565_python_3.x_scrapy.txt
Q: How to enable debug in slf4j Logger? How to globally enable debug for all the slf4j.Logger objects? A: Programmatically, with logback: setLoggingLevel(ch.qos.logback.classic.Level.DEBUG); where public static void setLoggingLevel(ch.qos.logback.classic.Level level) { ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); root.setLevel(level); } A: exists various capability to switch debug log on: this article have good explanation all of those. to me good fit is: Using slf4j with Log4j logger create file src/main/resources/log4j.properties log4j.rootLogger=DEBUG, STDOUT log4j.logger.deng=INFO log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout log4j.appender.STDOUT.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n A: Pass the System Property -Dorg.slf4j.simpleLogger.defaultLogLevel=DEBUG at your Java startup for the SLF4J Simple api A: Use logback as the slf4j binding. The default behaviour without an configuration file is to log all events at level DEBUG and above to System.out. See http://logback.qos.ch/manual/configuration.html#automaticConf for details. A: Just add the following to the application.properties logging.level.org.springframework.web=DEBUG logging.level.org.springframework.context=DEBUG A: depends on what binding you are using... if e.g. it's log4j have a look at http://logging.apache.org/log4j/1.2/manual.html and its Configuration chapter A: If you use log4j as the binding of slf4j you can crete a log4j.xml (or log4j.properties) file and add it to the classpath. An example could be: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false"> <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender"> <param name="Target" value="System.out" /> <param name="Threshold" value="DEBUG" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{HH:mm:ss,SSS} %-5p [%c{1}] %m%n" /> </layout> </appender> <root> <appender-ref ref="CONSOLE" /> </root> </log4j:configuration> A: For log4j <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true"> <!-- ============================== --> <!-- Append messages to the console --> <!-- ============================== --> <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender"> <param name="Target" value="System.out"/> <param name="Threshold" value="INFO"/> <layout class="org.apache.log4j.PatternLayout"> <!-- The default pattern: Date Priority [Category] Message\n --> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n"/> </layout> </appender> <appender name="web" class="org.apache.log4j.DailyRollingFileAppender"> <param name="Threshold" value="DEBUG"/> <param name="Append" value="true"/> <param name="File" value="${catalina.home}/logs/web.log"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n"/> </layout> </appender> <category name="com.idc.scd" additivity="false"> <priority value="${log4j.category.com.mypackage}"/> <appender-ref ref="web"/> </category> </log4j:configuration> by this cofiguration your all "com.mypackage" logs will be written in "web.log" file under catalina.home. A: Here's a sample configuration I usually use to setup logging with logback.Gradle dependencies (the same apply to Maven) compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25' compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.3' logback.xml configuration to be placed in the project's classpath (src/main/resources) <configuration> <statusListener class="ch.qos.logback.core.status.NopStatusListener" /> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n</Pattern> </layout> </appender> <!-- enable debug only on org.hibernate.SQL package --> <logger name="org.hibernate.SQL" level="debug" additivity="false"> <appender-ref ref="STDOUT" /> </logger> <root level="info"> <appender-ref ref="STDOUT" /> </root> </configuration> A: If you are using slf4j with springboot, you just need to set debug level in application.properties. logging.level.root=DEBUG You also can set the specific part by setting logging.group. Image that, if you have com.pxample, com.example, com.dxample in src/main/java/ and you setting: logging.group.mycustomgroup=com.pxample, com.example logging.level.mycustomgroup=DEBUG , then only com.pxample, com.example will show debug output for you.
How to enable debug in slf4j Logger?
How to globally enable debug for all the slf4j.Logger objects?
[ "Programmatically, with logback:\nsetLoggingLevel(ch.qos.logback.classic.Level.DEBUG);\n\nwhere\npublic static void setLoggingLevel(ch.qos.logback.classic.Level level) {\n ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);\n root.setLevel(level);\n}\n\n", "exists various capability to switch debug log on:\nthis article have good explanation all of those. to me good fit is:\nUsing slf4j with Log4j logger\ncreate file src/main/resources/log4j.properties\nlog4j.rootLogger=DEBUG, STDOUT\nlog4j.logger.deng=INFO\nlog4j.appender.STDOUT=org.apache.log4j.ConsoleAppender\nlog4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout\nlog4j.appender.STDOUT.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n\n\n", "Pass the System Property -Dorg.slf4j.simpleLogger.defaultLogLevel=DEBUG at your Java startup for the SLF4J Simple api\n\n", "Use logback as the slf4j binding. \nThe default behaviour without an configuration file is to log all events at level DEBUG and above to System.out. See http://logback.qos.ch/manual/configuration.html#automaticConf for details.\n", "Just add the following to the application.properties\nlogging.level.org.springframework.web=DEBUG\nlogging.level.org.springframework.context=DEBUG\n\n", "depends on what binding you are using... if e.g. it's log4j have a look at http://logging.apache.org/log4j/1.2/manual.html and its Configuration chapter\n", "If you use log4j as the binding of slf4j you can crete a log4j.xml (or log4j.properties) file and add it to the classpath. An example could be:\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\" debug=\"false\">\n <appender name=\"CONSOLE\" class=\"org.apache.log4j.ConsoleAppender\">\n <param name=\"Target\" value=\"System.out\" />\n <param name=\"Threshold\" value=\"DEBUG\" />\n <layout class=\"org.apache.log4j.PatternLayout\">\n <param name=\"ConversionPattern\" value=\"%d{HH:mm:ss,SSS} %-5p [%c{1}] %m%n\" />\n </layout>\n </appender>\n <root>\n <appender-ref ref=\"CONSOLE\" />\n </root>\n</log4j:configuration>\n\n", "For log4j\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\" debug=\"true\">\n\n<!-- ============================== -->\n<!-- Append messages to the console -->\n<!-- ============================== -->\n\n<appender name=\"CONSOLE\" class=\"org.apache.log4j.ConsoleAppender\">\n <param name=\"Target\" value=\"System.out\"/>\n <param name=\"Threshold\" value=\"INFO\"/>\n\n <layout class=\"org.apache.log4j.PatternLayout\">\n <!-- The default pattern: Date Priority [Category] Message\\n -->\n <param name=\"ConversionPattern\" value=\"%d [%t] %-5p %c - %m%n\"/>\n </layout>\n</appender>\n\n<appender name=\"web\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n <param name=\"Threshold\" value=\"DEBUG\"/>\n <param name=\"Append\" value=\"true\"/>\n <param name=\"File\" value=\"${catalina.home}/logs/web.log\"/>\n <layout class=\"org.apache.log4j.PatternLayout\">\n <param name=\"ConversionPattern\" value=\"%d [%t] %-5p %c - %m%n\"/>\n </layout>\n</appender>\n\n<category name=\"com.idc.scd\" additivity=\"false\">\n <priority value=\"${log4j.category.com.mypackage}\"/>\n <appender-ref ref=\"web\"/>\n</category>\n\n</log4j:configuration>\n\nby this cofiguration your all \"com.mypackage\" logs will be written in \"web.log\" file under catalina.home.\n", "Here's a sample configuration I usually use to setup logging with logback.Gradle dependencies (the same apply to Maven)\ncompile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25'\ncompile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.3'\n\nlogback.xml configuration to be placed in the project's classpath (src/main/resources)\n<configuration>\n\n <statusListener class=\"ch.qos.logback.core.status.NopStatusListener\" />\n\n <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n <layout class=\"ch.qos.logback.classic.PatternLayout\">\n <Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\\(%line\\) - %msg%n</Pattern>\n </layout>\n </appender>\n \n <!-- enable debug only on org.hibernate.SQL package -->\n <logger name=\"org.hibernate.SQL\" level=\"debug\" additivity=\"false\">\n <appender-ref ref=\"STDOUT\" />\n </logger>\n\n <root level=\"info\">\n <appender-ref ref=\"STDOUT\" />\n </root>\n\n</configuration>\n\n", "If you are using slf4j with springboot, you just need to set debug level in application.properties.\nlogging.level.root=DEBUG\n\nYou also can set the specific part by setting logging.group.\nImage that, if you have com.pxample, com.example, com.dxample in src/main/java/ and you setting:\nlogging.group.mycustomgroup=com.pxample, com.example\nlogging.level.mycustomgroup=DEBUG\n\n, then only com.pxample, com.example will show debug output for you.\n" ]
[ 40, 16, 10, 2, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "java", "logging", "slf4j" ]
stackoverflow_0010847458_java_logging_slf4j.txt
Q: Javascript regex to replace part of substring not working as expected? I'm working with times and meridiems. I could have '2:0 a. m.' or '2:0 am' or '3:0 p. m.' or '3:0 pm' Basically what I'm trying to do is transform the first in the second when it happens. My attempts: console.info('2:0 a. m.'.replace(/(.*?\s)([ampAMP]*?)/, "$1")); // 2:0 a. m. This one I really don't understand... '2:0 a. m.'.replace(/(.*?\s)([ampAMP]).*?([ampAMP])/, "$1"); // 2:0 . This one works but looks weird, not sure it's the best way '2:0 a. m.'.replace(/(.*?\s)([ampAMP]).*?([ampAMP]).*?$/, "$1$2$3"); I was barely able to remove the meridiem from the time, but how can I replace all characters not matching [aAmMpP] just AFTER the first space? A: If you want to match am or pm, using [ampAMP] matches only a single character. If you use it twice, then you would allow for mm which is not a valid format. You could make the pattern match more variations and capture what you want to keep. Then in the replacement use the capture groups to create the format that you want. If the dots are mandatory: \b(\d{1,2})\s*:\s*(\d{1,2})\s*([ap])\.\s*m\. \b A word boundary (\d{1,2}) Capture group 1, match 1-2 digits \s*:\s* Math : between optional whitespace chars (\d{1,2}) Capture group 2, match 1-2 digits \s* Match optional whitespace chars ([ap]) Capture group 3, match either a or b \.\s*m\. Match . optional whitespace chars m and . See a regex demo. In the replacement use (as you already know that you have matched the m char) $1:$2 $3m const regex = /\b(\d{1,2})\s*:\s*(\d{1,2})\s*([ap])\.\s*m\./; [ "2:0 a. m.", "2:0 p. m.", "3:0 p. m.", "3:0p.m.", "2:0 am" ].forEach(s => console.log(s.replace(regex, "$1:$2 $3m"))); A bit more time like specific pattern, allowing an optional digit 0-5 for the seconds part: \b([0-1]?[0-9]|2[0-3])\s*:\s*([0-5]?[0-9])\s*([ap])\.\s*m\. Regex demo A: For now after many attempts this works, alghough not very clean let time = "02:00 p. m."; time = time.replace(/(.*?\s)([ampAMP]).*?([ampAMP]).*?$/, "$1$2$3"); console.log(time); with the selected answer I had let time = "02:00 a. m."; time = time.replace(/\b(\d{1,2})\s*:\s*(\d{1,2})\s*([ap])\.\s*m\./i, "$1:$2 $3m"); console.log(time); but by the way I ended up doing this: let time = "02:00 a. m."; time = time .replace(/\.\s*/g, ""); console.log(time); because although it was good, I had performance issues. hope it helps A: To replace the text "a. m." or "am" with "am" and the text "p. m." or "pm" with "pm" in a string, you can use the following regular expression: /^(.?\s)(a.?\sm|p.?\s*m)/g This regular expression will match the text "a. m." or "am" at the beginning of the string (indicated by the ^ character), after any number of characters followed by a space (indicated by the .*?\s pattern). It will also match the text "p. m." or "pm" in the same way. To use this regular expression in the replace() method, you can pass it as the first argument, and "am" or "pm" as the second argument, depending on the matched text. For example: '2:0 a. m.'.replace(/^(.?\s)(a.?\sm|p.?\s*m)/g, "$1am"); // returns "2:0 am" '2:0 p. m.'.replace(/^(.?\s)(a.?\sm|p.?\s*m)/g, "$1pm"); // returns "2:0 EDIT To replace the text "a. m." or "am" with "am" and the text "p. m." or "pm" dynamically, you can use a regular expression with a capturing group to match the "am" or "pm" part of the string, and then use the capturing group in the replacement string. Here's an example regular expression that you can use: /^(.?\s)(a.?\sm|p.?\s*m)/g This regular expression will match the text "a. m." or "am" at the beginning of the string (indicated by the ^ character), after any number of characters followed by a space (indicated by the .*?\s pattern). It will also match the text "p. m." or "pm" in the same way. The part of the string that matches "am" or "pm" will be captured in the second capturing group (indicated by the parentheses around the second part of the regular expression). To use this regular expression in the replace() method, you can use the $2 placeholder in the replacement string to refer to the second capturing group. For example: '2:0 a. m.'.replace(/^(.?\s)(a.?\sm|p.?\s*m)/g, "$1$2"); // returns "2:0 am" '2:0 p. m.'.replace(/^(.?\s)(a.?\sm|p.?\s*m)/g, "$1$2"); // returns "2:0 pm"
Javascript regex to replace part of substring not working as expected?
I'm working with times and meridiems. I could have '2:0 a. m.' or '2:0 am' or '3:0 p. m.' or '3:0 pm' Basically what I'm trying to do is transform the first in the second when it happens. My attempts: console.info('2:0 a. m.'.replace(/(.*?\s)([ampAMP]*?)/, "$1")); // 2:0 a. m. This one I really don't understand... '2:0 a. m.'.replace(/(.*?\s)([ampAMP]).*?([ampAMP])/, "$1"); // 2:0 . This one works but looks weird, not sure it's the best way '2:0 a. m.'.replace(/(.*?\s)([ampAMP]).*?([ampAMP]).*?$/, "$1$2$3"); I was barely able to remove the meridiem from the time, but how can I replace all characters not matching [aAmMpP] just AFTER the first space?
[ "If you want to match am or pm, using [ampAMP] matches only a single character. If you use it twice, then you would allow for mm which is not a valid format.\nYou could make the pattern match more variations and capture what you want to keep. Then in the replacement use the capture groups to create the format that you want.\nIf the dots are mandatory:\n\\b(\\d{1,2})\\s*:\\s*(\\d{1,2})\\s*([ap])\\.\\s*m\\.\n\n\n\\b A word boundary\n(\\d{1,2}) Capture group 1, match 1-2 digits\n\\s*:\\s* Math : between optional whitespace chars\n(\\d{1,2}) Capture group 2, match 1-2 digits\n\\s* Match optional whitespace chars\n([ap]) Capture group 3, match either a or b\n\\.\\s*m\\. Match . optional whitespace chars m and .\n\nSee a regex demo.\nIn the replacement use (as you already know that you have matched the m char)\n$1:$2 $3m\n\n\n\nconst regex = /\\b(\\d{1,2})\\s*:\\s*(\\d{1,2})\\s*([ap])\\.\\s*m\\./;\n[\n \"2:0 a. m.\",\n \"2:0 p. m.\",\n \"3:0 p. m.\",\n \"3:0p.m.\",\n \"2:0 am\"\n].forEach(s => console.log(s.replace(regex, \"$1:$2 $3m\")));\n\n\n\nA bit more time like specific pattern, allowing an optional digit 0-5 for the seconds part:\n\\b([0-1]?[0-9]|2[0-3])\\s*:\\s*([0-5]?[0-9])\\s*([ap])\\.\\s*m\\.\n\nRegex demo\n", "For now after many attempts this works, alghough not very clean\n\n\nlet time = \"02:00 p. m.\";\ntime = time.replace(/(.*?\\s)([ampAMP]).*?([ampAMP]).*?$/, \"$1$2$3\");\nconsole.log(time);\n\n\n\nwith the selected answer I had\n\n\nlet time = \"02:00 a. m.\";\ntime = time.replace(/\\b(\\d{1,2})\\s*:\\s*(\\d{1,2})\\s*([ap])\\.\\s*m\\./i, \"$1:$2 $3m\");\nconsole.log(time);\n\n\n\nbut by the way I ended up doing this:\n\n\nlet time = \"02:00 a. m.\";\ntime = time .replace(/\\.\\s*/g, \"\");\nconsole.log(time);\n\n\n\nbecause although it was good, I had performance issues.\nhope it helps\n", "To replace the text \"a. m.\" or \"am\" with \"am\" and the text \"p. m.\" or \"pm\" with \"pm\" in a string, you can use the following regular expression:\n/^(.?\\s)(a.?\\sm|p.?\\s*m)/g\nThis regular expression will match the text \"a. m.\" or \"am\" at the beginning of the string (indicated by the ^ character), after any number of characters followed by a space (indicated by the .*?\\s pattern). It will also match the text \"p. m.\" or \"pm\" in the same way.\nTo use this regular expression in the replace() method, you can pass it as the first argument, and \"am\" or \"pm\" as the second argument, depending on the matched text. For example:\n'2:0 a. m.'.replace(/^(.?\\s)(a.?\\sm|p.?\\s*m)/g, \"$1am\");\n// returns \"2:0 am\"\n'2:0 p. m.'.replace(/^(.?\\s)(a.?\\sm|p.?\\s*m)/g, \"$1pm\");\n// returns \"2:0\nEDIT\nTo replace the text \"a. m.\" or \"am\" with \"am\" and the text \"p. m.\" or \"pm\" dynamically, you can use a regular expression with a capturing group to match the \"am\" or \"pm\" part of the string, and then use the capturing group in the replacement string.\nHere's an example regular expression that you can use:\n/^(.?\\s)(a.?\\sm|p.?\\s*m)/g\nThis regular expression will match the text \"a. m.\" or \"am\" at the beginning of the string (indicated by the ^ character), after any number of characters followed by a space (indicated by the .*?\\s pattern). It will also match the text \"p. m.\" or \"pm\" in the same way. The part of the string that matches \"am\" or \"pm\" will be captured in the second capturing group (indicated by the parentheses around the second part of the regular expression).\nTo use this regular expression in the replace() method, you can use the $2 placeholder in the replacement string to refer to the second capturing group. For example:\n'2:0 a. m.'.replace(/^(.?\\s)(a.?\\sm|p.?\\s*m)/g, \"$1$2\"); // returns \"2:0 am\"\n'2:0 p. m.'.replace(/^(.?\\s)(a.?\\sm|p.?\\s*m)/g, \"$1$2\"); // returns \"2:0 pm\"\n" ]
[ 2, 1, 1 ]
[ "If I understood correctly by first in the second, this should work.\nconst regex = /^([^\\s]\\s)([^aAmMpP])/;\nconst string = '2:0 a. m.';\nconst result = string.replace(regex, '$1am');\n\nconsole.log(result); // Output: '2:0 am'\n\nregex using the \" /^([^\\s]\\s)([^aAmMpP])/\"\n" ]
[ -1 ]
[ "javascript", "match", "regex", "replace", "substring" ]
stackoverflow_0074678747_javascript_match_regex_replace_substring.txt
Q: Drawing "ascii" (text) schematics with unicode characters I'm trying to draw electronic schematics with text. I used to do this with ascii-only letters, but wanted to have something more fancy. Here is an example in ascii: VDD -------------*---------*-----*-----------------*-----*---------*------- | | | | | | | | | | | | |---| |---| |---| |---| |---| |---| vclk o----o|--------o| |o-- --o| |o--------|o----o vclk |---| |---| |---| \ / |---| |---| |---| | | | x | | | | |-----*-------* *-------*-----| | | | x | | | |---| / \ |---| | | |--- ---| | | |---| |---| | | | | | |---------------* *---------------| | | |---| |---| vinp o-----| |o----o vinn |---| |---| |--------*--------| | | |---| vclk o----| |---| | | VSS --------------------------------------*--------------------------------- which I now changed to VDD ─────────────┬─────────┬─────┬─────────────────┬─────┬─────────┐ │ │ │ │ │ │ │ │ │ │ │ │ ║───┘ ║───┘ └───║ ║───┘ └───║ └───║ vclk o────o║────────o║ ║o── ──o║ ║o────────║o────o vclk ║───┐ ║───┐ ┌───║ ╲ ╱ ║───┐ ┌───║ ┌───║ │ │ │ ╳ │ │ │ │ └─────┼──────── ────────┼─────┘ │ │ │ ╳ │ │ │ └───║ ╱ ╲ ║───┘ │ │ ║─── ───║ │ │ ┌───║ ║───┐ │ │ │ │ │ └───────────────┤ ├───────────────┘ │ │ ║───┘ └───║ vinp o─────║ ║o────o vinn ║───┐ ┌───║ └────────┬────────┘ │ │ ║───┘ vclk o────║ ║───┐ │ │ VSS ───────────────────────────────────────────────────────────────── I'm quite happy with the result, but the newer drawing is missing some important things: Is it possible to get little dots ON the wires where wires cross, similar to the asterisks that I used in the ascii schematic? I tried a few combining characters but nothing looked right. Is there a possibility to connect the diagonal lines to the straight ones? From what I found online these characters don't exist, but maybe I'm wrong or there is another way. To be precise, the two questions are (for example) about these parts: here └────────┬────────┘ │ and ── ── ╲ ╱ ╳ ─── ─── ╳ ╱ ╲ ── ── ^ here A: I wound up here while searching for basically anything about drawing circuit diagrams with unicode, and sadly there doesn't seem to be much of it out there. Which is a real shame, because unicode is really only missing a few characters that would make this work quite well. Poking around the unicode tables for options, angle brackets look viable for the sideways-Y intersections: ── ── ╲ ╱ ╳ ──❬ ❭── ╳ ╱ ╲ ── ── But transitioning from diagonal to orthogonal otherwise doesn't seem to have any clean answers. IMHO it's probably best to stick with right angles. As for junctions, I think maybe using the heavy versions of the box drawings characters might work: └────────┳────────┘ │ Maybe even in combination with the split-thickness lines: └───────╼┳╾───────┘ ╿ I think that's the best I can offer. Hope it helps you or anyone else who comes along looking for the same thing.
Drawing "ascii" (text) schematics with unicode characters
I'm trying to draw electronic schematics with text. I used to do this with ascii-only letters, but wanted to have something more fancy. Here is an example in ascii: VDD -------------*---------*-----*-----------------*-----*---------*------- | | | | | | | | | | | | |---| |---| |---| |---| |---| |---| vclk o----o|--------o| |o-- --o| |o--------|o----o vclk |---| |---| |---| \ / |---| |---| |---| | | | x | | | | |-----*-------* *-------*-----| | | | x | | | |---| / \ |---| | | |--- ---| | | |---| |---| | | | | | |---------------* *---------------| | | |---| |---| vinp o-----| |o----o vinn |---| |---| |--------*--------| | | |---| vclk o----| |---| | | VSS --------------------------------------*--------------------------------- which I now changed to VDD ─────────────┬─────────┬─────┬─────────────────┬─────┬─────────┐ │ │ │ │ │ │ │ │ │ │ │ │ ║───┘ ║───┘ └───║ ║───┘ └───║ └───║ vclk o────o║────────o║ ║o── ──o║ ║o────────║o────o vclk ║───┐ ║───┐ ┌───║ ╲ ╱ ║───┐ ┌───║ ┌───║ │ │ │ ╳ │ │ │ │ └─────┼──────── ────────┼─────┘ │ │ │ ╳ │ │ │ └───║ ╱ ╲ ║───┘ │ │ ║─── ───║ │ │ ┌───║ ║───┐ │ │ │ │ │ └───────────────┤ ├───────────────┘ │ │ ║───┘ └───║ vinp o─────║ ║o────o vinn ║───┐ ┌───║ └────────┬────────┘ │ │ ║───┘ vclk o────║ ║───┐ │ │ VSS ───────────────────────────────────────────────────────────────── I'm quite happy with the result, but the newer drawing is missing some important things: Is it possible to get little dots ON the wires where wires cross, similar to the asterisks that I used in the ascii schematic? I tried a few combining characters but nothing looked right. Is there a possibility to connect the diagonal lines to the straight ones? From what I found online these characters don't exist, but maybe I'm wrong or there is another way. To be precise, the two questions are (for example) about these parts: here └────────┬────────┘ │ and ── ── ╲ ╱ ╳ ─── ─── ╳ ╱ ╲ ── ── ^ here
[ "I wound up here while searching for basically anything about drawing circuit diagrams with unicode, and sadly there doesn't seem to be much of it out there. Which is a real shame, because unicode is really only missing a few characters that would make this work quite well.\nPoking around the unicode tables for options, angle brackets look viable for the sideways-Y intersections:\n── ──\n ╲ ╱ \n ╳ \n──❬ ❭──\n ╳ \n ╱ ╲ \n── ──\n\nBut transitioning from diagonal to orthogonal otherwise doesn't seem to have any clean answers. IMHO it's probably best to stick with right angles.\nAs for junctions, I think maybe using the heavy versions of the box drawings characters might work:\n└────────┳────────┘\n │\n\nMaybe even in combination with the split-thickness lines:\n└───────╼┳╾───────┘\n ╿\n\nI think that's the best I can offer. Hope it helps you or anyone else who comes along looking for the same thing.\n" ]
[ 0 ]
[]
[]
[ "drawing", "unicode" ]
stackoverflow_0073218559_drawing_unicode.txt
Q: removing DOM elements client side in Google App Scripts I'm creating a dynamic sidebar in a Document with a Google Apps Scripts sidebar served by HTMLService. In the client-side sidebar template script, I can find my container via a jQuery selector and dynamically append DOM buttons to it, but I cannot remove any button elements from the same container (which is best practice since each holds an event handler which, as I understand it, would not be deleted from memory). The function within the sidebar.html responsible for these actions: function fillContainerWithWords(arrayOfWords, container, wordClass) { while (container.first()) { // empty word container container.remove(container.first()); } arrayOfWords.forEach(word => { // fill word container let wordButton = `<div><button class="${wordClass}" onclick=getNewWords("${word}")>${word}</button></div>`; container.append(wordButton); }) } CAN append to the container correctly, but DOES NOT remove any children from the container (so it ends up stacking DOM elements onto the container) I've tried deviations of the same intent, such as: container.firstChild, (typical javascript way) $(container).firstChild, (the jQuery way) container.removeChild(container.first()) and nothing seems to work. The "firstChild" approach produces an "undefined" (clearly not a property of the container.) The code above is the closest I've managed, but produces an error deep in the jQuery implementation (or perhaps with Caja?): jquery.min.js:4 Uncaught TypeError: t.replace is not a function at st.matchesSelector (**jquery.min.js:4:10383**) at Function.filter (**jquery.min.js:4:23300**) at init.remove (**jquery.min.js:4:26762**) at **fillContainerWithWords** (userCodeAppPanel:73:17) at userCodeAppPanel:55:17 at Of (2515706220-mae_html_user_bin_i18n_mae_html_user.js:94:266) at 2515706220-mae_html_user_bin_i18n_mae_html_user.js:25:132 at Ug.U (2515706220-mae_html_user_bin_i18n_mae_html_user.js:123:380) at Bd (2515706220-mae_html_user_bin_i18n_mae_html_user.js:54:477) at a (2515706220-mae_html_user_bin_i18n_mae_html_user.js:52:52) Any info on restrictions or possible options is greatly appreciated... Stripped down minimum example: Code.gs /** * @OnlyCurrentDoc */ function onOpen(e) { DocumentApp.getUi().createAddonMenu() .addItem('Start', 'showSidebar') .addToUi(); } function onInstall(e) { onOpen(e); } function showSidebar() { const ui = HtmlService.createHtmlOutputFromFile('basic').setTitle('stackoverflow').setSandboxMode(HtmlService.SandboxMode.EMULATED);; DocumentApp.getUi().showSidebar(ui); } basic.html <!DOCTYPE html> <html> <head> <base target="_top"> </head> <style> .col-contain { overflow: hidden; } .col-one { float: left; width: 50%; } .blue { color: blue; } .red { color: red; } </style> <body> <button class="blue" id="change-button">Change List</button> <div class="block col-contain"> <div class="col-one" id="list"></div> </div> </body> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> $(function() { $('#change-button').click(() => fillContainerWithWords(['five', 'six', 'seven'], $("#list"), 'blue')); }); function fillContainerWithWords(arrayOfWords, container, wordClass) { // while (container.first()) { // empty word container // container.remove(container.first()); // } arrayOfWords.forEach(word => { // fill word container let wordButton = `<div><button class="${wordClass}">${word}</button></div>`; container.append(wordButton); }) } fillContainerWithWords(['one', 'two', 'three', 'four'], $("#list"), 'red'); </script> </html> A: Remove .setSandboxMode(HtmlService.SandboxMode.EMULATED); Remove <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> Replace $(function() { $('#change-button').click(() => fillContainerWithWords(['five', 'six', 'seven'], $("#list"), 'blue')); }); by const list = document.querySelector('#list'); document.querySelector('#change-button').addEventListener('click', () => { fillContainerWithWords(['five', 'six', 'seven'], list, 'blue')) }); and replace fillContainerWithWords(['one', 'two', 'three', 'four'], $("#list"), 'red'); by fillContainerWithWords(['one', 'two', 'three', 'four'], list, 'red'); It looks that the references that you used to write your code are obsolete as it includes A very old jQuery version, 1.9.1. While this should still work, the client-side code doesn't look to really need jQuery nowadays, i.e. Document.querySelector and Document.querySelectorAll could be used with CSS-selectors to select DOM elements in a similar way that jQuery used them. A deprecated method sandox mode, HtmlService.SandboxMode.EMULATED. From https://developers.google.com/apps-script/reference/html/sandbox-mode The NATIVE and EMULATED modes were deprecated on October 13, 2015 and both are now sunset. Only IFRAME mode is now supported. jQuery is not bad per se but, IMHO, nowadays it's better to avoid it's use in very small web apps like usually are Google editors custom dialogs and sidebars as the tecnhologies that support them have evolved a lot making jQuery not as "indispensable" as it was several years ago. A: Thanks Ruben - that put me on the right track. For anyone curious for the full set of modifications required to get the function to work successfully to both remove and replace the list: function fillContainerWithWords(arrayOfWords, container, wordClass) { while (container.firstChild) { // empty word container container.removeChild(container.firstChild); } arrayOfWords.forEach(word => { // fill word container let button = document.createElement('BUTTON'); button.id = word; button.classList.add(wordClass); let text = document.createTextNode(word); button.appendChild(text); let div = document.createElement('DIV'); div.appendChild(button); container.appendChild(div); }) }
removing DOM elements client side in Google App Scripts
I'm creating a dynamic sidebar in a Document with a Google Apps Scripts sidebar served by HTMLService. In the client-side sidebar template script, I can find my container via a jQuery selector and dynamically append DOM buttons to it, but I cannot remove any button elements from the same container (which is best practice since each holds an event handler which, as I understand it, would not be deleted from memory). The function within the sidebar.html responsible for these actions: function fillContainerWithWords(arrayOfWords, container, wordClass) { while (container.first()) { // empty word container container.remove(container.first()); } arrayOfWords.forEach(word => { // fill word container let wordButton = `<div><button class="${wordClass}" onclick=getNewWords("${word}")>${word}</button></div>`; container.append(wordButton); }) } CAN append to the container correctly, but DOES NOT remove any children from the container (so it ends up stacking DOM elements onto the container) I've tried deviations of the same intent, such as: container.firstChild, (typical javascript way) $(container).firstChild, (the jQuery way) container.removeChild(container.first()) and nothing seems to work. The "firstChild" approach produces an "undefined" (clearly not a property of the container.) The code above is the closest I've managed, but produces an error deep in the jQuery implementation (or perhaps with Caja?): jquery.min.js:4 Uncaught TypeError: t.replace is not a function at st.matchesSelector (**jquery.min.js:4:10383**) at Function.filter (**jquery.min.js:4:23300**) at init.remove (**jquery.min.js:4:26762**) at **fillContainerWithWords** (userCodeAppPanel:73:17) at userCodeAppPanel:55:17 at Of (2515706220-mae_html_user_bin_i18n_mae_html_user.js:94:266) at 2515706220-mae_html_user_bin_i18n_mae_html_user.js:25:132 at Ug.U (2515706220-mae_html_user_bin_i18n_mae_html_user.js:123:380) at Bd (2515706220-mae_html_user_bin_i18n_mae_html_user.js:54:477) at a (2515706220-mae_html_user_bin_i18n_mae_html_user.js:52:52) Any info on restrictions or possible options is greatly appreciated... Stripped down minimum example: Code.gs /** * @OnlyCurrentDoc */ function onOpen(e) { DocumentApp.getUi().createAddonMenu() .addItem('Start', 'showSidebar') .addToUi(); } function onInstall(e) { onOpen(e); } function showSidebar() { const ui = HtmlService.createHtmlOutputFromFile('basic').setTitle('stackoverflow').setSandboxMode(HtmlService.SandboxMode.EMULATED);; DocumentApp.getUi().showSidebar(ui); } basic.html <!DOCTYPE html> <html> <head> <base target="_top"> </head> <style> .col-contain { overflow: hidden; } .col-one { float: left; width: 50%; } .blue { color: blue; } .red { color: red; } </style> <body> <button class="blue" id="change-button">Change List</button> <div class="block col-contain"> <div class="col-one" id="list"></div> </div> </body> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> $(function() { $('#change-button').click(() => fillContainerWithWords(['five', 'six', 'seven'], $("#list"), 'blue')); }); function fillContainerWithWords(arrayOfWords, container, wordClass) { // while (container.first()) { // empty word container // container.remove(container.first()); // } arrayOfWords.forEach(word => { // fill word container let wordButton = `<div><button class="${wordClass}">${word}</button></div>`; container.append(wordButton); }) } fillContainerWithWords(['one', 'two', 'three', 'four'], $("#list"), 'red'); </script> </html>
[ "\nRemove .setSandboxMode(HtmlService.SandboxMode.EMULATED);\n\nRemove\n\n\n<script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js\"></script>\n\n\nReplace\n\n$(function() {\n $('#change-button').click(() => fillContainerWithWords(['five', 'six', 'seven'], $(\"#list\"), 'blue'));\n });\n\nby\nconst list = document.querySelector('#list');\ndocument.querySelector('#change-button').addEventListener('click', () => {\n fillContainerWithWords(['five', 'six', 'seven'], list, 'blue'))\n});\n\n\nand replace\nfillContainerWithWords(['one', 'two', 'three', 'four'], $(\"#list\"), 'red');\n\nby\nfillContainerWithWords(['one', 'two', 'three', 'four'], list, 'red');\n\n\nIt looks that the references that you used to write your code are obsolete as it includes\n\nA very old jQuery version, 1.9.1. While this should still work, the client-side code doesn't look to really need jQuery nowadays, i.e. Document.querySelector and Document.querySelectorAll could be used with CSS-selectors to select DOM elements in a similar way that jQuery used them.\nA deprecated method sandox mode, HtmlService.SandboxMode.EMULATED.\nFrom https://developers.google.com/apps-script/reference/html/sandbox-mode\n\nThe NATIVE and EMULATED modes were deprecated on October 13, 2015 and both are now sunset. Only IFRAME mode is now supported.\n\n\n\njQuery is not bad per se but, IMHO, nowadays it's better to avoid it's use in very small web apps like usually are Google editors custom dialogs and sidebars as the tecnhologies that support them have evolved a lot making jQuery not as \"indispensable\" as it was several years ago.\n", "Thanks Ruben - that put me on the right track.\nFor anyone curious for the full set of modifications required to get the function to work successfully to both remove and replace the list:\n function fillContainerWithWords(arrayOfWords, container, wordClass) {\n while (container.firstChild) { // empty word container\n container.removeChild(container.firstChild);\n }\n\n arrayOfWords.forEach(word => { // fill word container\n let button = document.createElement('BUTTON');\n button.id = word;\n button.classList.add(wordClass);\n let text = document.createTextNode(word);\n button.appendChild(text); \n let div = document.createElement('DIV');\n div.appendChild(button);\n \n container.appendChild(div);\n })\n }\n\n" ]
[ 0, 0 ]
[]
[]
[ "dom_manipulation", "google_apps_script", "jquery", "web_applications" ]
stackoverflow_0074620671_dom_manipulation_google_apps_script_jquery_web_applications.txt
Q: In perl is \*STDIN the same as STDIN? I'm the author of Pythonizer and I'm trying to translate the code of CGI.pm from the standard perl library to Python. I came across this code in read_from_client: read(\*STDIN, $$buff, $len, $offset) Is \*STDIN the same thing as just STDIN? I'm not understanding why they are using it this way. Thanks for your help! The module also references \*main::STDIN - is this the same as STDIN too (I would translate plain STDIN to sys.stdin in python)? Code: foreach my $fh ( \*main::STDOUT, \*main::STDIN, \*main::STDERR, ) { ... } A: Instead of translating CGI.pm line for line, I'll recommend you understand the interface then do whatever Python would do for that. Or, better yet, just forget it exists. It often seems like a translation will be a drop-in replacement, but since the libraries and structures you'll use in the new language are different enough that you are just going to make new bugs. Since you are going to make new bugs anyway, you might as well do something smarter. But, I know nothing about your situation, so let's get to the literal question. You're looking at: # Read data from a file handle sub read_from_client { my($self, $buff, $len, $offset) = @_; local $^W=0; # prevent a warning return $MOD_PERL ? $self->r->read($$buff, $len, $offset) : read(\*STDIN, $$buff, $len, $offset); } Instead of worrying about the Perl code, just do whatever you need to do in Python to satisfy the interface. Given a buffer and a length, get some more data from the filehandle. Since you are not handling mod_perl (I'm guessing, because how would you?), you can ignore most stuff there. The \*main::STDIN and \*STDIN are references to a typeglob, which is a way to track all the Perl variables with the same name (scalar, array, hash, subroutine, filehandle, and a few others). The STDIN identifier is a special case variable that is main by default, so adding the package main:: in front is probably merely developer comfort. When you use those reference in a place that wants to work on a filehandle, the filehandle portion of the type glob is used. It's just a way to pass the identifier STDIN and have something else use it as a filehandle. You see this as a way to pass around the named, standard file handles. The read takes a filehandle (or reference to typeglob) as its first argument. In python, you'd do something like sys.stdin.read(...). A: The following can usually be used a file handle: An IO object (*STDIN{IO}) A glob containing an IO object (*STDIN) A reference to a glob containing an IO object (\*STDIN) The name of a glob containing an IO object ("STDIN") The builtin operators that expect a file handle allow you to omit the * when providing a glob. For example, read( FH, ... ) means read( *FH, ... ). The builtin functions that expect a file handle should accept all of these. So you could any of the following: read( *STDIN{IO}, ... ) read( STDIN, ... ) read( *STDIN, ... ) read( \*STDIN, ... ) read( "STDIN", ... ). They will have the same effect. Third-party libraries probably accept the globs and reference to globs, and they should also expect IO objects. I expect the least support for the providing the name as a string. Your mileage may vary. You can't go wrong with a reference to a glob (\*FH) since that's what open( my $fh, ... ) produces.
In perl is \*STDIN the same as STDIN?
I'm the author of Pythonizer and I'm trying to translate the code of CGI.pm from the standard perl library to Python. I came across this code in read_from_client: read(\*STDIN, $$buff, $len, $offset) Is \*STDIN the same thing as just STDIN? I'm not understanding why they are using it this way. Thanks for your help! The module also references \*main::STDIN - is this the same as STDIN too (I would translate plain STDIN to sys.stdin in python)? Code: foreach my $fh ( \*main::STDOUT, \*main::STDIN, \*main::STDERR, ) { ... }
[ "Instead of translating CGI.pm line for line, I'll recommend you understand the interface then do whatever Python would do for that. Or, better yet, just forget it exists. It often seems like a translation will be a drop-in replacement, but since the libraries and structures you'll use in the new language are different enough that you are just going to make new bugs. Since you are going to make new bugs anyway, you might as well do something smarter.\nBut, I know nothing about your situation, so let's get to the literal question.\nYou're looking at:\n# Read data from a file handle\nsub read_from_client {\n my($self, $buff, $len, $offset) = @_;\n local $^W=0; # prevent a warning\n return $MOD_PERL\n ? $self->r->read($$buff, $len, $offset)\n : read(\\*STDIN, $$buff, $len, $offset);\n}\n\nInstead of worrying about the Perl code, just do whatever you need to do in Python to satisfy the interface. Given a buffer and a length, get some more data from the filehandle. Since you are not handling mod_perl (I'm guessing, because how would you?), you can ignore most stuff there.\n\nThe \\*main::STDIN and \\*STDIN are references to a typeglob, which is a way to track all the Perl variables with the same name (scalar, array, hash, subroutine, filehandle, and a few others). The STDIN identifier is a special case variable that is main by default, so adding the package main:: in front is probably merely developer comfort.\nWhen you use those reference in a place that wants to work on a filehandle, the filehandle portion of the type glob is used. It's just a way to pass the identifier STDIN and have something else use it as a filehandle.\nYou see this as a way to pass around the named, standard file handles.\nThe read takes a filehandle (or reference to typeglob) as its first argument.\nIn python, you'd do something like sys.stdin.read(...).\n", "The following can usually be used a file handle:\n\nAn IO object (*STDIN{IO})\nA glob containing an IO object (*STDIN)\nA reference to a glob containing an IO object (\\*STDIN)\nThe name of a glob containing an IO object (\"STDIN\")\n\nThe builtin operators that expect a file handle allow you to omit the * when providing a glob. For example, read( FH, ... ) means read( *FH, ... ).\nThe builtin functions that expect a file handle should accept all of these. So you could any of the following:\n\nread( *STDIN{IO}, ... )\nread( STDIN, ... )\nread( *STDIN, ... )\nread( \\*STDIN, ... )\nread( \"STDIN\", ... ).\n\nThey will have the same effect.\n\nThird-party libraries probably accept the globs and reference to globs, and they should also expect IO objects. I expect the least support for the providing the name as a string. Your mileage may vary.\nYou can't go wrong with a reference to a glob (\\*FH) since that's what open( my $fh, ... ) produces.\n" ]
[ 3, 3 ]
[]
[]
[ "perl", "reference", "stdin", "typeglob" ]
stackoverflow_0074678226_perl_reference_stdin_typeglob.txt
Q: Xcode UI test plans : show attachment previews in test results In the Apple overview page of Xcode Cloud, I can see this image of the result of a test executed with Xcode Cloud: The attachements of the test are displayed as a full image. But on my side, the attachements are displayed inline and not as a full image preview. I can still QuickLook them but they are always collapsed. I created an extensions of XCTestCase to easily generate screenshot attachements for my UI tests: extension XCTestCase { /// Take a screenshot of a given app and add it to the test attachements. /// - Parameters: /// - app: The app to take a screenshot of. /// - name: The name of the screenshot. func takeScreenshot(of app: XCUIApplication, named name: String) { let screenshot = app.windows.firstMatch.screenshot() let attachment = XCTAttachment(screenshot: screenshot) #if os(iOS) attachment.name = "Screenshot-\(name)-\(UIDevice.current.name).png" #else attachment.name = "Screenshot-\(name)-macOS.png" #endif attachment.lifetime = .keepAlways add(attachment) } } And use it like so on my UI Test: final class LocalizationTests: XCTestCase { override class var runsForEachTargetApplicationUIConfiguration: Bool { true } func testLaunchScreen() throws { let app = XCUIApplication() app.launch() takeScreenshot(of: app, named: "Launch") } } Here is also my test plan configuration: There are a lot of WWDC sessions about Xcode Cloud and unit testing, but I couldn't find one of them that talks about this feature. Maybe I'm missing something really obvious, but this feature would be a super nice addition to my workflow. I'm using Xcode 14.1 (14B47b) and macOS Ventura 13.0.1 (22A400). Does anyone know if it is possible to replicate the behavior showed on the Apple website? Thanks in advance for your help. A: This seems to be describing a kind-of-hidden feature of the Xcode test results viewer called Gallery mode. From the Assistant dropdown, you can navigate to Gallery mode if you are looking at a test result inside Xcode. It's in the top right of the center panel, and the menu item is "Show Gallery"
Xcode UI test plans : show attachment previews in test results
In the Apple overview page of Xcode Cloud, I can see this image of the result of a test executed with Xcode Cloud: The attachements of the test are displayed as a full image. But on my side, the attachements are displayed inline and not as a full image preview. I can still QuickLook them but they are always collapsed. I created an extensions of XCTestCase to easily generate screenshot attachements for my UI tests: extension XCTestCase { /// Take a screenshot of a given app and add it to the test attachements. /// - Parameters: /// - app: The app to take a screenshot of. /// - name: The name of the screenshot. func takeScreenshot(of app: XCUIApplication, named name: String) { let screenshot = app.windows.firstMatch.screenshot() let attachment = XCTAttachment(screenshot: screenshot) #if os(iOS) attachment.name = "Screenshot-\(name)-\(UIDevice.current.name).png" #else attachment.name = "Screenshot-\(name)-macOS.png" #endif attachment.lifetime = .keepAlways add(attachment) } } And use it like so on my UI Test: final class LocalizationTests: XCTestCase { override class var runsForEachTargetApplicationUIConfiguration: Bool { true } func testLaunchScreen() throws { let app = XCUIApplication() app.launch() takeScreenshot(of: app, named: "Launch") } } Here is also my test plan configuration: There are a lot of WWDC sessions about Xcode Cloud and unit testing, but I couldn't find one of them that talks about this feature. Maybe I'm missing something really obvious, but this feature would be a super nice addition to my workflow. I'm using Xcode 14.1 (14B47b) and macOS Ventura 13.0.1 (22A400). Does anyone know if it is possible to replicate the behavior showed on the Apple website? Thanks in advance for your help.
[ "This seems to be describing a kind-of-hidden feature of the Xcode test results viewer called Gallery mode.\nFrom the Assistant dropdown, you can navigate to Gallery mode if you are looking at a test result inside Xcode.\nIt's in the top right of the center panel, and the menu item is \"Show Gallery\"\n" ]
[ 0 ]
[]
[]
[ "swift", "xcode", "xcode_cloud", "xcode_ui_testing", "xctest" ]
stackoverflow_0074432314_swift_xcode_xcode_cloud_xcode_ui_testing_xctest.txt
Q: Complete list of Clang flags Where can I find a complete list of Clang flags? There are some, like -include-pch, that don't appear to be even listed in the man page. :( I know that GCC uses some of the same flags, but it doesn't include documentation for stuff like -Os which I believe is only available in Clang. Is there a place where I can find a single, consolidated list of all the Clang options ever? A: I don't know if this is exactly what you want. Maybe more options are described elsewhere, but I think you are interested in the Clang frontend options. By default, the options displayed seem to describe the "GCC-compatible driver". clang -cc1 --help should give you what you want. A: For Clang, they are listed in the diagnostics reference, which can be found on the documentation website here A: There are many hidden options in LLVM: clang --help-hidden opt --help-hidden A: If you want to get a complete list of warning flags, including hierarchies (IE which sub-flags are enabled by groups like -Wall), you can use the LLVM tool diagtool. $ diagtool tree Will print the complete list of warnings clang supports. $ diagtool tree -Wnon-gcc will print the warnings enabled by -Wnon-gcc. The warnings are color-coded: RED = it does nothing, exists only for GCC compatibility GREEN = the warning is enabled by default YELLOW = the flag enables new behavior Finally, I wrote a short script if you're interested in viewing the diff between sets of flags (see image below) For example: -Wall -> -Wall -Wextra ->-Wall -Wextra -Wnon-gcc: https://twitter.com/GavinRayDev/status/1599126252136280064 https://gist.github.com/GavinRay97/c28ca31a86f6a106bb46e426e2603be0 Here is a set of flags not enabled by your typical -Wall -Wextra -Wpedantic for Clang (as of LLVM 16 dev) you might find useful, that I scraped from the output of diagtool: https://gist.github.com/GavinRay97/bae1d93925e55ce0a0084946f24984cf Hope someone out there finds this information useful =)
Complete list of Clang flags
Where can I find a complete list of Clang flags? There are some, like -include-pch, that don't appear to be even listed in the man page. :( I know that GCC uses some of the same flags, but it doesn't include documentation for stuff like -Os which I believe is only available in Clang. Is there a place where I can find a single, consolidated list of all the Clang options ever?
[ "I don't know if this is exactly what you want. Maybe more options are described elsewhere, but I think you are interested in the Clang frontend options. By default, the options displayed seem to describe the \"GCC-compatible driver\".\nclang -cc1 --help should give you what you want.\n", "For Clang, they are listed in the diagnostics reference, which can be found on the documentation website here\n", "There are many hidden options in LLVM:\nclang --help-hidden\nopt --help-hidden\n\n", "If you want to get a complete list of warning flags, including hierarchies (IE which sub-flags are enabled by groups like -Wall), you can use the LLVM tool diagtool.\n\n$ diagtool tree Will print the complete list of warnings clang supports.\n$ diagtool tree -Wnon-gcc will print the warnings enabled by -Wnon-gcc.\n\nThe warnings are color-coded:\n\nRED = it does nothing, exists only for GCC compatibility\nGREEN = the warning is enabled by default\nYELLOW = the flag enables new behavior\n\n\n\nFinally, I wrote a short script if you're interested in viewing the diff between sets of flags (see image below)\nFor example: -Wall -> -Wall -Wextra ->-Wall -Wextra -Wnon-gcc:\n\nhttps://twitter.com/GavinRayDev/status/1599126252136280064\nhttps://gist.github.com/GavinRay97/c28ca31a86f6a106bb46e426e2603be0\n\nHere is a set of flags not enabled by your typical -Wall -Wextra -Wpedantic for Clang (as of LLVM 16 dev) you might find useful, that I scraped from the output of diagtool:\n\nhttps://gist.github.com/GavinRay97/bae1d93925e55ce0a0084946f24984cf\n\nHope someone out there finds this information useful =)\n\n" ]
[ 88, 7, 7, 0 ]
[]
[]
[ "clang" ]
stackoverflow_0007880812_clang.txt
Q: Django waitress- How to run it in Daemon Mode I've a django application with waitress (gunicorn doesn't work on windows) to serve it. Because its production code and its based on windows 2012 server. But I want the django application to run in daemon mode is it possible? Daemon mode - app running without command prompt visible also I'll be helpful to open shell without even closing the server. AutoStart if for some reason system has to restart. Note: Restrictions: The project cannot be moved to UNIX based system. Third Party application like any .exe file cannot be used. A: For production: create a file server.py at same level as manage.py and add following: from waitress import serve from myapp.wsgi import application if __name__ == '__main__': serve(application, port='8000') Start-Process python -NoNewWindow -ArgumentList "server.py" You can close the terminal after that and it still runs. If you later want to stop, you have to do with Get-Process and then TaskKill Running with CMD: START "myapp" /B python server.py Running in cmd A: Just add & at the end of command A: Another solution - to use Docker, and in your docker you can use gunicorn or any other linux feature A: It is possible to run a Django application in daemon mode on a Windows server using the built-in Windows Services feature. Here are the steps to do this: Open the Command Prompt as an administrator. Navigate to the directory where your Django application is located. Use the following command to install the application as a Windows service: python manage.py installservice Use the following command to start the service: net start <service name> Where is the name of the service that was installed in step 3. Once the service is started, it will run in the background as a daemon and will continue to run even if the command prompt is closed or the user logs out. To make the service start automatically whenever the system is restarted, you can use the following command: sc config <service name> start=auto Where is the name of the service that was installed in step 3. To open a shell for the Django application without stopping the service, you can use the following command: python manage.py shell This will open a Python shell with access to the Django application, allowing you to run commands and interact with the application.
Django waitress- How to run it in Daemon Mode
I've a django application with waitress (gunicorn doesn't work on windows) to serve it. Because its production code and its based on windows 2012 server. But I want the django application to run in daemon mode is it possible? Daemon mode - app running without command prompt visible also I'll be helpful to open shell without even closing the server. AutoStart if for some reason system has to restart. Note: Restrictions: The project cannot be moved to UNIX based system. Third Party application like any .exe file cannot be used.
[ "For production:\ncreate a file server.py at same level as manage.py and add following:\nfrom waitress import serve\n \nfrom myapp.wsgi import application\n \nif __name__ == '__main__':\n serve(application, port='8000')\n\nStart-Process python -NoNewWindow -ArgumentList \"server.py\"\nYou can close the terminal after that and it still runs.\nIf you later want to stop, you have to do with Get-Process and then\nTaskKill\nRunning with CMD:\nSTART \"myapp\" /B python server.py\nRunning in cmd\n", "Just add & at the end of command\n", "Another solution - to use Docker, and in your docker you can use gunicorn or any other linux feature\n", "It is possible to run a Django application in daemon mode on a Windows server using the built-in Windows Services feature. Here are the steps to do this:\n\nOpen the Command Prompt as an administrator.\nNavigate to the directory where your Django application is located.\nUse the following command to install the application as a Windows service:\n\npython manage.py installservice\n\nUse the following command to start the service:\nnet start <service name>\n\nWhere is the name of the service that was installed in step 3.\nOnce the service is started, it will run in the background as a daemon and will continue to run even if the command prompt is closed or the user logs out.\nTo make the service start automatically whenever the system is restarted, you can use the following command:\nsc config <service name> start=auto\n\nWhere is the name of the service that was installed in step 3.\nTo open a shell for the Django application without stopping the service, you can use the following command:\npython manage.py shell\n\nThis will open a Python shell with access to the Django application, allowing you to run commands and interact with the application.\n" ]
[ 2, 0, 0, 0 ]
[]
[]
[ "daemon", "django", "python", "waitress", "windows" ]
stackoverflow_0074574627_daemon_django_python_waitress_windows.txt
Q: How to handle horizontal and vertical scrolling at the same time within a webpage I'm currently stumbling on a bit of a problem involving (smooth)scrolling and trying to "update" a navigation bar at the same time. Currently I have a large webpage that has a lot of content under different headers. These headers are displayed in a navigation bar that spans the whole view width of the page, each of these elements are href's to smoothly scroll to the current position of the header. The header the user is currently is viewing gets highlighted within the navigation bar. However I would also like to scroll this header to the front or middle of the navigation bar for easily navigating the page. Using the following code: nav_bar.scrollBy(scrollAmount-125,0); All of this works completely fine until I introduce: html {scroll-behavior: smooth;} to the CSS. As soon as I call the .scrollBy() the smooth scrolling get interupted and halted before it can complete the scrolling to the element referenced by the href. Is there any solution to fixing this problem, I tried to get the .scrollBy() to run after the scrolling is complete but have not been able to get this to fully function. The problem is with the html {scroll-behavior: smooth;} since removing this property gives the desired results for functionality but without my desired User Experience. A: Can u try it ? <style> html { scroll-behavior: auto; } </style> <script> let navBar = document.getElementById("nav-bar"); navBar.scrollBy(scrollAmount - 125, 0); </script>
How to handle horizontal and vertical scrolling at the same time within a webpage
I'm currently stumbling on a bit of a problem involving (smooth)scrolling and trying to "update" a navigation bar at the same time. Currently I have a large webpage that has a lot of content under different headers. These headers are displayed in a navigation bar that spans the whole view width of the page, each of these elements are href's to smoothly scroll to the current position of the header. The header the user is currently is viewing gets highlighted within the navigation bar. However I would also like to scroll this header to the front or middle of the navigation bar for easily navigating the page. Using the following code: nav_bar.scrollBy(scrollAmount-125,0); All of this works completely fine until I introduce: html {scroll-behavior: smooth;} to the CSS. As soon as I call the .scrollBy() the smooth scrolling get interupted and halted before it can complete the scrolling to the element referenced by the href. Is there any solution to fixing this problem, I tried to get the .scrollBy() to run after the scrolling is complete but have not been able to get this to fully function. The problem is with the html {scroll-behavior: smooth;} since removing this property gives the desired results for functionality but without my desired User Experience.
[ "Can u try it ?\n<style>\n \n html {\n scroll-behavior: auto;\n }\n</style>\n\n<script>\n \n let navBar = document.getElementById(\"nav-bar\");\n\n navBar.scrollBy(scrollAmount - 125, 0);\n</script>\n\n" ]
[ 0 ]
[]
[]
[ "css", "javascript", "navigationbar", "scroll", "vertical_scrolling" ]
stackoverflow_0074677831_css_javascript_navigationbar_scroll_vertical_scrolling.txt
Q: opengl shared memory layout and size Given the following glsl declarations (this is just an example): struct S{ f16vec3 a; float16_t b; f16vec3_t c; float16_t d; }; shared float16_t my_float_array[100]; shared S my_S_array[100]; I have the following questions: How much shared memory will be used by a given declaration, in the above example for instance? Which memory layout is used for variables in shared memory? std140, std430 or something else? How does this play with bank conflicts? I was able to get the total shared memory required by a program using glGetProgramBinary and skiping until the begining of the text part indicated by a line starting with "!!NV": ... !!NVcp5.0 OPTION NV_shader_buffer_load; OPTION NV_internal; OPTION NV_gpu_program_fp64; OPTION NV_shader_storage_buffer; OPTION NV_bindless_texture; OPTION NV_gpu_program5_mem_extended; GROUP_SIZE 4 4 4; SHARED_MEMORY 4480; SHARED shared_mem[] = { program.sharedmem }; ... This is rather indirect though and does not tell much about the alignment/packing rules. A: Which memory layout is used for variables in shared memory? std140, std430 or something else? It's implementation-defined. The layouts applied to buffer-backed storage matter because code external to the shader needs to be able to access it. shared variables cannot be externally to the shader, so the layout of such variables is functionally implementation-defined. In short, you cannot know for certain how much storage any particular shared variable declaration will consume. You can assume that it will take up at least as many bytes as is minimally required to store the data you asked to store. But that's about it. How does this play with bank conflicts? "Banks" are not a concept which OpenGL or GLSL recognizes. It is therefore implementation-defined.
opengl shared memory layout and size
Given the following glsl declarations (this is just an example): struct S{ f16vec3 a; float16_t b; f16vec3_t c; float16_t d; }; shared float16_t my_float_array[100]; shared S my_S_array[100]; I have the following questions: How much shared memory will be used by a given declaration, in the above example for instance? Which memory layout is used for variables in shared memory? std140, std430 or something else? How does this play with bank conflicts? I was able to get the total shared memory required by a program using glGetProgramBinary and skiping until the begining of the text part indicated by a line starting with "!!NV": ... !!NVcp5.0 OPTION NV_shader_buffer_load; OPTION NV_internal; OPTION NV_gpu_program_fp64; OPTION NV_shader_storage_buffer; OPTION NV_bindless_texture; OPTION NV_gpu_program5_mem_extended; GROUP_SIZE 4 4 4; SHARED_MEMORY 4480; SHARED shared_mem[] = { program.sharedmem }; ... This is rather indirect though and does not tell much about the alignment/packing rules.
[ "\nWhich memory layout is used for variables in shared memory? std140, std430 or something else?\n\nIt's implementation-defined.\nThe layouts applied to buffer-backed storage matter because code external to the shader needs to be able to access it. shared variables cannot be externally to the shader, so the layout of such variables is functionally implementation-defined.\nIn short, you cannot know for certain how much storage any particular shared variable declaration will consume. You can assume that it will take up at least as many bytes as is minimally required to store the data you asked to store. But that's about it.\n\nHow does this play with bank conflicts?\n\n\"Banks\" are not a concept which OpenGL or GLSL recognizes. It is therefore implementation-defined.\n" ]
[ 1 ]
[ "The amount of shared memory that will be used by a given declaration depends on the type and number of variables declared in the shared memory block. In the example you provided, the shared memory block will use 4480 bytes of shared memory.\nThe memory layout used for variables in shared memory is std140. This means that each basic type (e.g. float, int, etc.) is stored as a sequence of contiguous memory locations with specific alignment requirements. For example, a float value must be aligned to a 4-byte boundary, and a vec3 value (three float values) must be aligned to a 16-byte boundary.\nAs for bank conflicts, they can occur when multiple threads in a CUDA block try to access the same memory bank in shared memory simultaneously. This can cause performance degradation because only one thread can access a given memory bank at a time. To avoid bank conflicts, it is important to ensure that variables are laid out in shared memory in a way that avoids conflicts. For example, by aligning variables to multiples of their size, or by using padding to ensure that different variables are mapped to different memory banks.\nTo determine the amount of shared memory used by a program, you can use the GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT and GL_SHADER_STORAGE_BUFFER_SIZE parameters of the glGetProgramiv function. These parameters will give you the alignment and size of the shared memory block, respectively.\nYou can use these values to calculate the amount of shared memory used by a given program, and to determine the memory layout of the variables in the shared memory block. However, this is an indirect way of doing it, and it may not be possible to determine the exact memory layout of the variables in the shared memory block. For this, you would need to use a debugging tool that can provide more detailed information about the memory layout of variables in shared memory.\n" ]
[ -2 ]
[ "glsl", "opengl" ]
stackoverflow_0074678769_glsl_opengl.txt
Q: C# Encrypt Large files in a certain Folder I'm new to AES encryption in C# so excuse me if this question is a bit stupid. I'm using the current C# code to encrypt and decrypt large files, but I'm stuck figuring out a way to encrypt a lot of files in a certain folder, and then I want them moved into another directory once encrypted. Here's the code I've found in another StackOverflow post it works with encrypting large files very well but i couldn't figure out how to make it encrypt a lot of files in a certain directory and then move those encrypted files into another directory. using System; using System.IO; using System.Security.Cryptography; using System.Text; ... // Rfc2898DeriveBytes constants: public readonly byte[] salt = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // Must be at least eight bytes. MAKE THIS SALTIER! public const int iterations = 1042; // Recommendation is >= 1000. /// <summary>Decrypt a file.</summary> /// <remarks>NB: "Padding is invalid and cannot be removed." is the Universal CryptoServices error. Make sure the password, salt and iterations are correct before getting nervous.</remarks> /// <param name="sourceFilename">The full path and name of the file to be decrypted.</param> /// <param name="destinationFilename">The full path and name of the file to be output.</param> /// <param name="password">The password for the decryption.</param> /// <param name="salt">The salt to be applied to the password.</param> /// <param name="iterations">The number of iterations Rfc2898DeriveBytes should use before generating the key and initialization vector for the decryption.</param> public void DecryptFile(string sourceFilename, string destinationFilename, string password, byte[] salt, int iterations) { AesManaged aes = new AesManaged(); aes.BlockSize = aes.LegalBlockSizes[0].MaxSize; aes.KeySize = aes.LegalKeySizes[0].MaxSize; // NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides. Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations); aes.Key = key.GetBytes(aes.KeySize / 8); aes.IV = key.GetBytes(aes.BlockSize / 8); aes.Mode = CipherMode.CBC; ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV); using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write)) { try { using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) { source.CopyTo(cryptoStream); } } catch (CryptographicException exception) { if (exception.Message == "Padding is invalid and cannot be removed.") throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception); else throw; } } } } /// <summary>Encrypt a file.</summary> /// <param name="sourceFilename">The full path and name of the file to be encrypted.</param> /// <param name="destinationFilename">The full path and name of the file to be output.</param> /// <param name="password">The password for the encryption.</param> /// <param name="salt">The salt to be applied to the password.</param> /// <param name="iterations">The number of iterations Rfc2898DeriveBytes should use before generating the key and initialization vector for the decryption.</param> public void EncryptFile(string sourceFilename, string destinationFilename, string password, byte[] salt, int iterations) { AesManaged aes = new AesManaged(); aes.BlockSize = aes.LegalBlockSizes[0].MaxSize; aes.KeySize = aes.LegalKeySizes[0].MaxSize; // NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides. Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations); aes.Key = key.GetBytes(aes.KeySize / 8); aes.IV = key.GetBytes(aes.BlockSize / 8); aes.Mode = CipherMode.CBC; ICryptoTransform transform = aes.CreateEncryptor(aes.Key, aes.IV); using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write)) { using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) { source.CopyTo(cryptoStream); } } } } A: You can enumerate files in your directory: foreach (var file in Directory.EnumerateFiles("DirectoryWithRawFilesPath")) { // using System.IO // Encrypt file File.Move(file, Path.Combine("DirectoryWithEncryptedFilesPath", file)); }
C# Encrypt Large files in a certain Folder
I'm new to AES encryption in C# so excuse me if this question is a bit stupid. I'm using the current C# code to encrypt and decrypt large files, but I'm stuck figuring out a way to encrypt a lot of files in a certain folder, and then I want them moved into another directory once encrypted. Here's the code I've found in another StackOverflow post it works with encrypting large files very well but i couldn't figure out how to make it encrypt a lot of files in a certain directory and then move those encrypted files into another directory. using System; using System.IO; using System.Security.Cryptography; using System.Text; ... // Rfc2898DeriveBytes constants: public readonly byte[] salt = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // Must be at least eight bytes. MAKE THIS SALTIER! public const int iterations = 1042; // Recommendation is >= 1000. /// <summary>Decrypt a file.</summary> /// <remarks>NB: "Padding is invalid and cannot be removed." is the Universal CryptoServices error. Make sure the password, salt and iterations are correct before getting nervous.</remarks> /// <param name="sourceFilename">The full path and name of the file to be decrypted.</param> /// <param name="destinationFilename">The full path and name of the file to be output.</param> /// <param name="password">The password for the decryption.</param> /// <param name="salt">The salt to be applied to the password.</param> /// <param name="iterations">The number of iterations Rfc2898DeriveBytes should use before generating the key and initialization vector for the decryption.</param> public void DecryptFile(string sourceFilename, string destinationFilename, string password, byte[] salt, int iterations) { AesManaged aes = new AesManaged(); aes.BlockSize = aes.LegalBlockSizes[0].MaxSize; aes.KeySize = aes.LegalKeySizes[0].MaxSize; // NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides. Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations); aes.Key = key.GetBytes(aes.KeySize / 8); aes.IV = key.GetBytes(aes.BlockSize / 8); aes.Mode = CipherMode.CBC; ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV); using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write)) { try { using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) { source.CopyTo(cryptoStream); } } catch (CryptographicException exception) { if (exception.Message == "Padding is invalid and cannot be removed.") throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception); else throw; } } } } /// <summary>Encrypt a file.</summary> /// <param name="sourceFilename">The full path and name of the file to be encrypted.</param> /// <param name="destinationFilename">The full path and name of the file to be output.</param> /// <param name="password">The password for the encryption.</param> /// <param name="salt">The salt to be applied to the password.</param> /// <param name="iterations">The number of iterations Rfc2898DeriveBytes should use before generating the key and initialization vector for the decryption.</param> public void EncryptFile(string sourceFilename, string destinationFilename, string password, byte[] salt, int iterations) { AesManaged aes = new AesManaged(); aes.BlockSize = aes.LegalBlockSizes[0].MaxSize; aes.KeySize = aes.LegalKeySizes[0].MaxSize; // NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides. Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations); aes.Key = key.GetBytes(aes.KeySize / 8); aes.IV = key.GetBytes(aes.BlockSize / 8); aes.Mode = CipherMode.CBC; ICryptoTransform transform = aes.CreateEncryptor(aes.Key, aes.IV); using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write)) { using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) { source.CopyTo(cryptoStream); } } } }
[ "You can enumerate files in your directory:\nforeach (var file in Directory.EnumerateFiles(\"DirectoryWithRawFilesPath\")) { // using System.IO\n // Encrypt file\n\n File.Move(file, Path.Combine(\"DirectoryWithEncryptedFilesPath\", file));\n}\n\n" ]
[ 2 ]
[]
[]
[ "aes", "c#", "encryption", "winforms" ]
stackoverflow_0074678729_aes_c#_encryption_winforms.txt
Q: Should navigation property be nullable or not Look at this entity: class EntityA { public int Id { get;set; } public string Name { get;set; } public int? ClientId { get; set; } // Navigation properties: public ClientEntity? Client { get; set; } } As you can see, this entity contains an optional property: ClientId. This means the client is optional. In this case, the ClientId field will contain NULL in the sql server database. I am working with navigation properties for foreign keys: This is the "Client" property. When ClientId is null, Client should be null too. This is why i have declared: "ClientEntity?" type for the Client property. But i see people who declare "ClientEntity" (not nullable) in same circumstances. But i do not understand how they can manipulate null clients in this case... Any idea ? Thanks A: Leaving this for anyone that also ran into this when enabling nullability for their project, the Navigational Properties should not be Nullable. Per Microsoft, Collection navigations, which contain references to multiple related entities, should always be non-nullable. An empty collection means that no related entities exist, but the list itself should never be null. https://learn.microsoft.com/en-us/ef/core/miscellaneous/nullable-reference-types So the solution to code this would be: class EntityA { public int Id { get;set; } public string Name { get;set; } public int ClientId { get; set; } // Navigation properties: public ClientEntity Client { get; set; } = null!; }
Should navigation property be nullable or not
Look at this entity: class EntityA { public int Id { get;set; } public string Name { get;set; } public int? ClientId { get; set; } // Navigation properties: public ClientEntity? Client { get; set; } } As you can see, this entity contains an optional property: ClientId. This means the client is optional. In this case, the ClientId field will contain NULL in the sql server database. I am working with navigation properties for foreign keys: This is the "Client" property. When ClientId is null, Client should be null too. This is why i have declared: "ClientEntity?" type for the Client property. But i see people who declare "ClientEntity" (not nullable) in same circumstances. But i do not understand how they can manipulate null clients in this case... Any idea ? Thanks
[ "Leaving this for anyone that also ran into this when enabling nullability for their project, the Navigational Properties should not be Nullable.\nPer Microsoft,\n\nCollection navigations, which contain references to multiple related entities, should always be non-nullable. An empty collection means that no related entities exist, but the list itself should never be null.\n\nhttps://learn.microsoft.com/en-us/ef/core/miscellaneous/nullable-reference-types\nSo the solution to code this would be:\nclass EntityA\n{\n public int Id { get;set; }\n public string Name { get;set; }\n public int ClientId { get; set; }\n\n // Navigation properties:\n public ClientEntity Client { get; set; } = null!;\n}\n\n" ]
[ 0 ]
[]
[]
[ "entity_framework", "linq" ]
stackoverflow_0072857722_entity_framework_linq.txt
Q: Is there a way not to print out the else statement when inputting a valid number? This is the problem that I need to code in C++ The question/problem I can't seem to know the problem of my code. Here's the code: #include <iostream> using namespace std; int main(void) { cout << "Total Purchase Cost: Php "; double total; cin >> total; cout << "Loyalty Card Type: "; int cardType; cin >> cardType; double discount = 0; double type1 = 0.10; double type2 = 0; double type3 = 0.15; if (cardType == 1) discount = total * type1; if (cardType == 2) discount = total * type2; if (cardType == 3) discount = total * type3; else cout << "Invalid Card"; cout << "Discounted Cost: Php \n" << discount; return 0; } When I try to run it, the discount price is correct and the computations is right and the output text "Discounted Cost: Php ---" seems to be working perfeclty. But when I started to add an else statement so that when I input an invalid number to my if statement, it will output a "Invalid Card" message. But when I input a valid number, the else statement still prints out even if it shouldn't be. A: To solve your immediate problem, I suggest that you replace all if statements except the first one with else if: if (cardType == 1) discount = total * type1; else if (cardType == 2) discount = total * type2; else if (cardType == 3) discount = total * type3; else cout << "Invalid Card" << '\n'; cout << "Discounted Cost: Php \n" << discount << '\n'; However, the logic above still has the problem that the line cout << "Discounted Cost: Php \n" << discount; will be printed even if the card is invalid, which you probably do not want. For this reason, it would be probabably better to add a variable bool valid and to only print "Discounted Cost" if that variable is true: bool valid = false; if (cardType == 1) { discount = total * type1; valid = true; } else if (cardType == 2) { discount = total * type2; valid = true; } else if (cardType == 3) { discount = total * type3; valid = true; } else { cout << "Invalid Card" << '\n'; } if ( valid ) { cout << "Discounted Cost: Php \n" << discount << '\n'; } Instead of using a chain of if...else if statements, you can also use a switch statement: bool valid = false; switch ( cardType ) { case 1: discount = total * type1; valid = true; break; case 2: discount = total * type2; valid = true; break; case 3: discount = total * type3; valid = true; break; default: cout << "Invalid Card" << '\n'; } if ( valid ) { cout << "Discounted Cost: Php \n" << discount << '\n'; } This logic could be simplified a bit by using a pointer instead, which can be set to nullptr to indicate that the card is invalid. double *type = nullptr; switch ( cardType ) { case 1: type = &type1; break; case 2: type = &type2; break; case 3: type = &type3; break; default: cout << "Invalid Card" << '\n'; } if ( type != nullptr ) cout << "Discounted Cost: Php \n" << total * *type << '\n'; } However, an even simpler way of writing the whole program would be: #include <iostream> using namespace std; int main() { cout << "Total Purchase Cost: Php "; double total; cin >> total; cout << "Loyalty Card Type: "; int cardType; cin >> cardType; constexpr double types[3] = { 0.10, 0, 0.15 }; if ( 1 <= cardType && cardType <= 3 ) { cout << "Discounted Cost: Php \n" << total * types[cardType-1] << '\n'; } else { cout << "Invalid Card" << '\n'; } return 0; } Another issue in your code (and also in my code above) is that you seem to be calculating the discount, but you are printing this value out as the "Discounted cost". This is incorrect. The proper mathematical formula is: discounted cost = full price - discount To fix this, the line constexpr double types[3] = { 0.10, 0, 0.15 }; should be changed to: constexpr double types[3] = { 0.90, 1.00, 0.85 };
Is there a way not to print out the else statement when inputting a valid number?
This is the problem that I need to code in C++ The question/problem I can't seem to know the problem of my code. Here's the code: #include <iostream> using namespace std; int main(void) { cout << "Total Purchase Cost: Php "; double total; cin >> total; cout << "Loyalty Card Type: "; int cardType; cin >> cardType; double discount = 0; double type1 = 0.10; double type2 = 0; double type3 = 0.15; if (cardType == 1) discount = total * type1; if (cardType == 2) discount = total * type2; if (cardType == 3) discount = total * type3; else cout << "Invalid Card"; cout << "Discounted Cost: Php \n" << discount; return 0; } When I try to run it, the discount price is correct and the computations is right and the output text "Discounted Cost: Php ---" seems to be working perfeclty. But when I started to add an else statement so that when I input an invalid number to my if statement, it will output a "Invalid Card" message. But when I input a valid number, the else statement still prints out even if it shouldn't be.
[ "To solve your immediate problem, I suggest that you replace all if statements except the first one with else if:\nif (cardType == 1)\n discount = total * type1;\nelse if (cardType == 2)\n discount = total * type2;\nelse if (cardType == 3)\n discount = total * type3;\nelse\n cout << \"Invalid Card\" << '\\n';\ncout << \"Discounted Cost: Php \\n\" << discount << '\\n';\n\nHowever, the logic above still has the problem that the line\ncout << \"Discounted Cost: Php \\n\" << discount;\n\nwill be printed even if the card is invalid, which you probably do not want. For this reason, it would be probabably better to add a variable bool valid and to only print \"Discounted Cost\" if that variable is true:\nbool valid = false;\n\nif (cardType == 1)\n{\n discount = total * type1;\n valid = true;\n}\nelse if (cardType == 2)\n{\n discount = total * type2;\n valid = true;\n}\nelse if (cardType == 3)\n{\n discount = total * type3;\n valid = true;\n}\nelse\n{\n cout << \"Invalid Card\" << '\\n';\n}\n\nif ( valid )\n{\n cout << \"Discounted Cost: Php \\n\" << discount << '\\n';\n}\n\nInstead of using a chain of if...else if statements, you can also use a switch statement:\nbool valid = false;\n\nswitch ( cardType )\n{\n case 1:\n discount = total * type1;\n valid = true;\n break;\n case 2:\n discount = total * type2;\n valid = true;\n break;\n case 3:\n discount = total * type3;\n valid = true;\n break;\n default:\n cout << \"Invalid Card\" << '\\n';\n}\n\nif ( valid )\n{\n cout << \"Discounted Cost: Php \\n\" << discount << '\\n';\n}\n\nThis logic could be simplified a bit by using a pointer instead, which can be set to nullptr to indicate that the card is invalid.\ndouble *type = nullptr;\n\nswitch ( cardType )\n{\n case 1:\n type = &type1;\n break;\n case 2:\n type = &type2;\n break;\n case 3:\n type = &type3;\n break;\n default:\n cout << \"Invalid Card\" << '\\n';\n}\n\nif ( type != nullptr )\n cout << \"Discounted Cost: Php \\n\" << total * *type << '\\n';\n}\n\nHowever, an even simpler way of writing the whole program would be:\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n cout << \"Total Purchase Cost: Php \";\n double total;\n cin >> total;\n \n cout << \"Loyalty Card Type: \";\n int cardType;\n cin >> cardType;\n\n constexpr double types[3] = { 0.10, 0, 0.15 };\n \n if ( 1 <= cardType && cardType <= 3 )\n {\n cout << \"Discounted Cost: Php \\n\" << total * types[cardType-1] << '\\n';\n }\n else\n {\n cout << \"Invalid Card\" << '\\n';\n }\n\n return 0;\n}\n\nAnother issue in your code (and also in my code above) is that you seem to be calculating the discount, but you are printing this value out as the \"Discounted cost\". This is incorrect. The proper mathematical formula is:\ndiscounted cost = full price - discount\n\nTo fix this, the line\nconstexpr double types[3] = { 0.10, 0, 0.15 };\n\nshould be changed to:\nconstexpr double types[3] = { 0.90, 1.00, 0.85 };\n\n" ]
[ 2 ]
[]
[]
[ "c++", "if_statement", "switch_statement" ]
stackoverflow_0074678624_c++_if_statement_switch_statement.txt
Q: Apache Beam Python SDK on Flink Runner to use Snowflake IO I have an existing Flink cluster in k8s. I am using Flink's session mode. I want to set up a periodic ETL job from Snowflake using Apache Beam. Thus, I have tried to use from apache_beam.io.snowflake import ReadFromSnowflake. I am aware that an expansion service is required, but here is where I am struggling. I have set up Python worker, and a Bean flink runner job server (version 2.43.0) as a sidecar in k8s pod. I have passed these pipeline options. [ "--runner=FlinkRunner", "--flink_version=1.15", "--flink_master=http://{host}:8081", "--environment_type=EXTERNAL", "--environment_config=localhost:50000", "--flink_submit_uber_jar", ] However, I am seeing the following logs. 2022/12/03 11:28:26 Failed to retrieve staged files: failed to retrieve /tmp/1-1/staged in 3 attempts: failed to retrieve chunk for /tmp/1-1/staged/beam-sdks-java-io-snowflake-expansion-service-2.43.0-4Bf-1AqvnTnIQ0PSXTz9S5MQ4RrIvMC3eNLcBf99voU.jar caused by: rpc error: code = Canceled desc = Server sendMessage() failed with Error; failed to retrieve chunk for /tmp/1-1/staged/beam-sdks-java-io-snowflake-expansion-service-2.43.0-4Bf-1AqvnTnIQ0PSXTz9S5MQ4RrIvMC3eNLcBf99voU.jar caused by: rpc error: code = Canceled desc = Server sendMessage() failed with Error; failed to retrieve chunk for /tmp/1-1/staged/beam-sdks-java-io-snowflake-expansion-service-2.43.0-4Bf-1AqvnTnIQ0PSXTz9S5MQ4RrIvMC3eNLcBf99voU.jar caused by: rpc error: code = Internal desc = unexpected EOF; failed to retrieve chunk for /tmp/1-1/staged/beam-sdks-java-io-snowflake-expansion-service-2.43.0-4Bf-1AqvnTnIQ0PSXTz9S5MQ4RrIvMC3eNLcBf99voU.jar caused by: rpc error: code = Internal desc = unexpected EOF I have started the expansion service using beam-sdks-java-io-snowflake-expansion-service-2.43.0.jar. I am unsure why the service isn't retrieved. Any help? A: It seems that you are using FlinkRunner, and it means that it will use non-portable Flink. I have checked with a committer that works on portability (@chamikara) and he suggested using the PortableRunner if you need portability.
Apache Beam Python SDK on Flink Runner to use Snowflake IO
I have an existing Flink cluster in k8s. I am using Flink's session mode. I want to set up a periodic ETL job from Snowflake using Apache Beam. Thus, I have tried to use from apache_beam.io.snowflake import ReadFromSnowflake. I am aware that an expansion service is required, but here is where I am struggling. I have set up Python worker, and a Bean flink runner job server (version 2.43.0) as a sidecar in k8s pod. I have passed these pipeline options. [ "--runner=FlinkRunner", "--flink_version=1.15", "--flink_master=http://{host}:8081", "--environment_type=EXTERNAL", "--environment_config=localhost:50000", "--flink_submit_uber_jar", ] However, I am seeing the following logs. 2022/12/03 11:28:26 Failed to retrieve staged files: failed to retrieve /tmp/1-1/staged in 3 attempts: failed to retrieve chunk for /tmp/1-1/staged/beam-sdks-java-io-snowflake-expansion-service-2.43.0-4Bf-1AqvnTnIQ0PSXTz9S5MQ4RrIvMC3eNLcBf99voU.jar caused by: rpc error: code = Canceled desc = Server sendMessage() failed with Error; failed to retrieve chunk for /tmp/1-1/staged/beam-sdks-java-io-snowflake-expansion-service-2.43.0-4Bf-1AqvnTnIQ0PSXTz9S5MQ4RrIvMC3eNLcBf99voU.jar caused by: rpc error: code = Canceled desc = Server sendMessage() failed with Error; failed to retrieve chunk for /tmp/1-1/staged/beam-sdks-java-io-snowflake-expansion-service-2.43.0-4Bf-1AqvnTnIQ0PSXTz9S5MQ4RrIvMC3eNLcBf99voU.jar caused by: rpc error: code = Internal desc = unexpected EOF; failed to retrieve chunk for /tmp/1-1/staged/beam-sdks-java-io-snowflake-expansion-service-2.43.0-4Bf-1AqvnTnIQ0PSXTz9S5MQ4RrIvMC3eNLcBf99voU.jar caused by: rpc error: code = Internal desc = unexpected EOF I have started the expansion service using beam-sdks-java-io-snowflake-expansion-service-2.43.0.jar. I am unsure why the service isn't retrieved. Any help?
[ "It seems that you are using FlinkRunner, and it means that it will use non-portable Flink.\nI have checked with a committer that works on portability (@chamikara) and he suggested using the PortableRunner if you need portability.\n" ]
[ 0 ]
[]
[]
[ "apache_beam", "apache_flink", "python", "snowflake_cloud_data_platform" ]
stackoverflow_0074666364_apache_beam_apache_flink_python_snowflake_cloud_data_platform.txt
Q: What is a network interface and what are they implemented for? I've read a book on the theory of computer networks, and now I'm familiar with some protocols such as TCP, IP, Ethernet, etc. However, in practice, in any modern operating system, you also have some other abstraction called "network interface". But in the RFC standards and theory books there's not a single word about this essential concept. I have such questions: 1. What is a network interface? 2. I've heard that network interfaces were invented to "simplify networks administration". How exactly do they simplify this? 3. How do network interfaces correspond to network protocols (Ethernet, IP, TCP) and their OSI layers? Am I right that interface represents a "host" in an IP network? But why then can there be an interface without an IP address? 4. How do network interfaces correspond to linux sockets? Is a certain interface implicitly selected when you send some data over a socket? 5. Why is there a separate interface for the loopback address 127.0.0.1? 6. What is a typical reason for defining a new network interface on a server? I haven't found any detailed description of network interfaces other than practical guides on how to use some real tools to "up" them or "down", assign an ip address, and the like. A: A network interface is a physical or logical device that enables a computer or other device to connect to a network and exchange data with other devices on the network. This can include a wide variety of devices, such as Ethernet cards, wireless adapters, and virtual network interfaces. Network interfaces simplify network administration by providing a standard way for devices to connect to a network and communicate with each other. This allows network administrators to easily configure and manage network connections without having to worry about the specific details of each device's hardware or software. Network interfaces correspond to network protocols and their OSI layers in that they provide the physical connection and data transmission capabilities that allow the protocols to operate. For example, an Ethernet interface would correspond to the OSI model's Physical and Data Link layers, while an IP interface would correspond to the Network layer. An interface can represent a "host" in an IP network, but it is not required to have an IP address in order to function. Network interfaces and Linux sockets are related in that they both provide a way for a computer to connect to a network and exchange data. However, a network interface is a physical or logical device that provides the actual connection to the network, while a socket is a software abstraction that allows applications to access the network through the interface. When sending data over a socket, a specific interface is not necessarily selected, as the socket API provides a way for the application to specify the destination address and let the operating system choose the appropriate interface. The loopback interface is a special interface that is used to communicate with the local host rather than with other devices on the network. This allows a device to send and receive data to itself, which can be useful for testing and development purposes. The loopback address (127.0.0.1) is typically associated with this interface and is used to identify the local host when sending data over the loopback interface. A typical reason for defining a new network interface on a server would be to add additional network connectivity or to improve network performance. For example, a server might have multiple network interfaces to allow it to connect to multiple networks or to provide failover capabilities in case one of the interfaces goes down. Additionally, a server might use multiple interfaces to increase its overall network bandwidth or to separate different types of traffic onto different interfaces to improve performance. Also check Official Internet Protocol Standards and Introduction to Network Interfaces
What is a network interface and what are they implemented for?
I've read a book on the theory of computer networks, and now I'm familiar with some protocols such as TCP, IP, Ethernet, etc. However, in practice, in any modern operating system, you also have some other abstraction called "network interface". But in the RFC standards and theory books there's not a single word about this essential concept. I have such questions: 1. What is a network interface? 2. I've heard that network interfaces were invented to "simplify networks administration". How exactly do they simplify this? 3. How do network interfaces correspond to network protocols (Ethernet, IP, TCP) and their OSI layers? Am I right that interface represents a "host" in an IP network? But why then can there be an interface without an IP address? 4. How do network interfaces correspond to linux sockets? Is a certain interface implicitly selected when you send some data over a socket? 5. Why is there a separate interface for the loopback address 127.0.0.1? 6. What is a typical reason for defining a new network interface on a server? I haven't found any detailed description of network interfaces other than practical guides on how to use some real tools to "up" them or "down", assign an ip address, and the like.
[ "\nA network interface is a physical or logical device that enables a computer or other device to connect to a network and exchange data with other devices on the network. This can include a wide variety of devices, such as Ethernet cards, wireless adapters, and virtual network interfaces.\n\nNetwork interfaces simplify network administration by providing a standard way for devices to connect to a network and communicate with each other. This allows network administrators to easily configure and manage network connections without having to worry about the specific details of each device's hardware or software.\n\nNetwork interfaces correspond to network protocols and their OSI layers in that they provide the physical connection and data transmission capabilities that allow the protocols to operate. For example, an Ethernet interface would correspond to the OSI model's Physical and Data Link layers, while an IP interface would correspond to the Network layer. An interface can represent a \"host\" in an IP network, but it is not required to have an IP address in order to function.\n\nNetwork interfaces and Linux sockets are related in that they both provide a way for a computer to connect to a network and exchange data. However, a network interface is a physical or logical device that provides the actual connection to the network, while a socket is a software abstraction that allows applications to access the network through the interface. When sending data over a socket, a specific interface is not necessarily selected, as the socket API provides a way for the application to specify the destination address and let the operating system choose the appropriate interface.\n\nThe loopback interface is a special interface that is used to communicate with the local host rather than with other devices on the network. This allows a device to send and receive data to itself, which can be useful for testing and development purposes. The loopback address (127.0.0.1) is typically associated with this interface and is used to identify the local host when sending data over the loopback interface.\n\nA typical reason for defining a new network interface on a server would be to add additional network connectivity or to improve network performance. For example, a server might have multiple network interfaces to allow it to connect to multiple networks or to provide failover capabilities in case one of the interfaces goes down. Additionally, a server might use multiple interfaces to increase its overall network bandwidth or to separate different types of traffic onto different interfaces to improve performance.\n\n\nAlso check Official Internet Protocol Standards and Introduction to Network Interfaces\n" ]
[ 1 ]
[]
[]
[ "ip", "linux", "networking", "operating_system", "osi" ]
stackoverflow_0074677908_ip_linux_networking_operating_system_osi.txt
Q: create a new column based on the conditions applied on the calculated average value in mysql, finally join the tables I have two tables in mysql database subjectids id subject 11 Physics 12 Chemistry 13 Maths 14 Biology 15 History 16 Geography studentsScores id student subjectid score 1 Ahaan 11 45 2 Ahaan 12 33 3 Ahaan 13 49 4 Ivaan 11 41 5 Ivaan 12 38 6 Ivaan 13 46 7 Ann 11 40 8 Ann 12 30 9 Ann 13 50 I am trying to find the average of each subject and give a tag of easy , medium, hard based on the average value, like hard if avg<35, medium if avg between 35 and 45 and easy if avg greater than 45. My expected result is subject subjectid avg_score level physics 11 42 medium chemistry 12 33 hard math 13 48 easy I am new to sql, it would be great if you can help. A: A simple case statement would do the trick. select si.subject, si.id, AVG(ss.score) as avg_score, case when AVG(ss.score) < 35 then 'hard' when AVG(ss.score) between 35 and 45 then 'medium' when AVG(ss.score) > 45 then 'easy' end as level from subjectids si inner join studentsScores ss on si.id=ss.subjectid group by si.subject,si.id ; https://dbfiddle.uk/IDS43R9W A: A simple JOIN and GROUP BY is enough to get your wanted result SELECT `subject`, `subjectid`, ROUND(AVG(`score`),0) avg_score, CASE WHEN AVG(`score`) < 35 THEN 'hard' WHEN AVG(`score`) between 35 and 45 then 'medium' WHEN AVG(`score`) > 45 THEN 'easy' end as level FROM studentsScores ss JOIN subjectids si ON ss.`subjectid` = si.`id` GROUP BY `subject`,`subjectid` subject subjectid avg_score level Physics 11 42 medium Chemistry 12 34 hard Maths 13 48 easy fiddle
create a new column based on the conditions applied on the calculated average value in mysql, finally join the tables
I have two tables in mysql database subjectids id subject 11 Physics 12 Chemistry 13 Maths 14 Biology 15 History 16 Geography studentsScores id student subjectid score 1 Ahaan 11 45 2 Ahaan 12 33 3 Ahaan 13 49 4 Ivaan 11 41 5 Ivaan 12 38 6 Ivaan 13 46 7 Ann 11 40 8 Ann 12 30 9 Ann 13 50 I am trying to find the average of each subject and give a tag of easy , medium, hard based on the average value, like hard if avg<35, medium if avg between 35 and 45 and easy if avg greater than 45. My expected result is subject subjectid avg_score level physics 11 42 medium chemistry 12 33 hard math 13 48 easy I am new to sql, it would be great if you can help.
[ "A simple case statement would do the trick.\n select si.subject,\n si.id,\n AVG(ss.score) as avg_score,\n case when AVG(ss.score) < 35 then 'hard'\n when AVG(ss.score) between 35 and 45 then 'medium'\n when AVG(ss.score) > 45 then 'easy'\n end as level\nfrom subjectids si \ninner join studentsScores ss on si.id=ss.subjectid\ngroup by si.subject,si.id ;\n\nhttps://dbfiddle.uk/IDS43R9W\n", "A simple JOIN and GROUP BY is enough to get your wanted result\nSELECT `subject`, `subjectid`, ROUND(AVG(`score`),0) avg_score,\n CASE \n WHEN AVG(`score`) < 35 THEN 'hard'\n WHEN AVG(`score`) between 35 and 45 then 'medium'\n WHEN AVG(`score`) > 45 THEN 'easy'\n end as level\nFROM studentsScores ss JOIN subjectids si ON ss.`subjectid` = si.`id`\nGROUP BY `subject`,`subjectid`\n\n\n\n\n\nsubject\nsubjectid\navg_score\nlevel\n\n\n\n\nPhysics\n11\n42\nmedium\n\n\nChemistry\n12\n34\nhard\n\n\nMaths\n13\n48\neasy\n\n\n\n\nfiddle\n" ]
[ 0, 0 ]
[]
[]
[ "mysql", "sql" ]
stackoverflow_0074678276_mysql_sql.txt
Q: Cloud Computing Heuristic (Greedy) and Genetic algorithms for task scheduling Hello Everyone if somebody give me a hand by solving this coding (C++, Python) problem for cloud computing task scheduling by Heuristic (Greedy) and Genetic algorithms I have no clue how to write the code I have surfed through Google to find a code inspire me tackle the problem: the proble is: Problem: Task Scheduling in Cloud Computing Suppose you are given N tasks and M virtual machines (VMs). Each task has a specified size (unit: million instructions) and deadline (unit: seconds). Each VM also has a main characteristic called processing speed (unit: million instructions per second). The task scheduling problem can be defined as follows: Mapping tasks to VMs in such a way that the completion time of the last task, i.e., Makespan, is optimized while meeting the deadline of the tasks. If the deadline of a task is not met, that task must be rejected. Solve and implement this problem using the following algorithms: A) An efficient heuristic algorithm b) Genetic Algorithm (GA) Finally, put the results of these two algorithms into an Excel file so that we can compare them with each other. In order to increase the reliability of the results, please run each algorithm 10 times and report the average, maximum and minimum values. Choose the size of the tasks randomly from the range [1000-1000]. The deadline of the tasks should be chosen randomly from the interval [10-60]. The processing speed of virtual machines should be randomly selected from the range [2000-8000]. First scenario: consider the number of tasks from 50 to 300 with steps of 50 and the number of VMs equal to 15. Second scenario: Consider the number of VMs from 5 to 30 with steps of 5 and the number of tasks equal to 200. For the genetic algorithm, consider the initial population size equal to 20 and the number of iterations equal to 100. I have no clue where I have to start! A: Here is a simple outline for implementing the task scheduling problem using heuristic and genetic algorithms in C++ and Python. For the heuristic algorithm, you can start by creating a class or struct to represent each task and VM. This class or struct should have fields for the task size, deadline, and processing speed of the VM. Next, you can implement the heuristic algorithm itself. This will involve mapping tasks to VMs in such a way that the completion time of the last task (makespan) is optimized while meeting the deadline of the tasks. One possible approach is to sort the tasks by deadline and then assign them to the fastest VMs until they are all mapped. If a task cannot be mapped before its deadline, it must be rejected. To evaluate the performance of the heuristic algorithm, you can run it multiple times and keep track of the average, maximum, and minimum makespan values. You can also print these values to an Excel file for comparison with the results of the genetic algorithm. For the genetic algorithm, you can start by implementing a function to generate a random initial population of task-to-VM mappings. This function should create a set of mappings that meet the deadlines of the tasks and have a reasonable makespan. Next, you can implement the genetic algorithm itself. This will involve applying genetic operators (such as crossover and mutation) to the population of mappings to produce new, improved mappings. You can use a fitness function to evaluate the quality of each mapping and select the best ones for reproduction. As with the heuristic algorithm, you can evaluate the performance of the genetic algorithm by running it multiple times and keeping track of the average, maximum, and minimum makespan values. You can then print these values to an Excel file for comparison with the results of the heuristic algorithm. Overall, this problem can be challenging, but it is a good opportunity to learn about algorithms for task scheduling and optimization. I hope this outline helps you get started!
Cloud Computing Heuristic (Greedy) and Genetic algorithms for task scheduling
Hello Everyone if somebody give me a hand by solving this coding (C++, Python) problem for cloud computing task scheduling by Heuristic (Greedy) and Genetic algorithms I have no clue how to write the code I have surfed through Google to find a code inspire me tackle the problem: the proble is: Problem: Task Scheduling in Cloud Computing Suppose you are given N tasks and M virtual machines (VMs). Each task has a specified size (unit: million instructions) and deadline (unit: seconds). Each VM also has a main characteristic called processing speed (unit: million instructions per second). The task scheduling problem can be defined as follows: Mapping tasks to VMs in such a way that the completion time of the last task, i.e., Makespan, is optimized while meeting the deadline of the tasks. If the deadline of a task is not met, that task must be rejected. Solve and implement this problem using the following algorithms: A) An efficient heuristic algorithm b) Genetic Algorithm (GA) Finally, put the results of these two algorithms into an Excel file so that we can compare them with each other. In order to increase the reliability of the results, please run each algorithm 10 times and report the average, maximum and minimum values. Choose the size of the tasks randomly from the range [1000-1000]. The deadline of the tasks should be chosen randomly from the interval [10-60]. The processing speed of virtual machines should be randomly selected from the range [2000-8000]. First scenario: consider the number of tasks from 50 to 300 with steps of 50 and the number of VMs equal to 15. Second scenario: Consider the number of VMs from 5 to 30 with steps of 5 and the number of tasks equal to 200. For the genetic algorithm, consider the initial population size equal to 20 and the number of iterations equal to 100. I have no clue where I have to start!
[ "Here is a simple outline for implementing the task scheduling problem using heuristic and genetic algorithms in C++ and Python.\nFor the heuristic algorithm, you can start by creating a class or struct to represent each task and VM. This class or struct should have fields for the task size, deadline, and processing speed of the VM.\nNext, you can implement the heuristic algorithm itself. This will involve mapping tasks to VMs in such a way that the completion time of the last task (makespan) is optimized while meeting the deadline of the tasks. One possible approach is to sort the tasks by deadline and then assign them to the fastest VMs until they are all mapped. If a task cannot be mapped before its deadline, it must be rejected.\nTo evaluate the performance of the heuristic algorithm, you can run it multiple times and keep track of the average, maximum, and minimum makespan values. You can also print these values to an Excel file for comparison with the results of the genetic algorithm.\nFor the genetic algorithm, you can start by implementing a function to generate a random initial population of task-to-VM mappings. This function should create a set of mappings that meet the deadlines of the tasks and have a reasonable makespan.\nNext, you can implement the genetic algorithm itself. This will involve applying genetic operators (such as crossover and mutation) to the population of mappings to produce new, improved mappings. You can use a fitness function to evaluate the quality of each mapping and select the best ones for reproduction.\nAs with the heuristic algorithm, you can evaluate the performance of the genetic algorithm by running it multiple times and keeping track of the average, maximum, and minimum makespan values. You can then print these values to an Excel file for comparison with the results of the heuristic algorithm.\nOverall, this problem can be challenging, but it is a good opportunity to learn about algorithms for task scheduling and optimization. I hope this outline helps you get started!\n" ]
[ 0 ]
[]
[]
[ "c++", "cloud", "genetic_algorithm", "greedy", "python" ]
stackoverflow_0074678875_c++_cloud_genetic_algorithm_greedy_python.txt
Q: Converting .jpg to .mp4 with ffmpeg with lots of files in a broken order so I tried to enhance a 16m long video with real-ESRGAN and ffmpeg, but since I have no idea how to actually get the files to sync in order, I am here. So I have been given a file on how it's supposed to operate, and I understand most of it, except for one thing I just can't figure out, and that's the file order it's supposed to compile it in. ffmpeg -i out_frames/frame%08d.jpg -i test.mp4 -map 0:v:0 -map 1:a:0 -c:a copy -c:v libx264 -r 23.98 -pix_fmt yuv420p test.mp4 This is the file, and the bolded part is very confusing for me since the original file that was given with it actually has about 100 or more files(frames), and the "08" here makes no sense to me. Basically what I need is "that bolded part" but so it can compile an order like this: frame00054953.jpg <-- End frame frame00001946.jpg <-- Start frame I've deleted the intros to save filesize because it's currently sitting at 53,010 files with 140GB. I just tried different combos to see if one could work out(like frame%01946d, dumb stuff like that), but could only get the basic one file to render and that resulted in a single frame, over 16m long audio... Going on their website, I also completely lost my mind. Any help is appreciated. A: I actually solved this with just a simple -start_number command I found later.
Converting .jpg to .mp4 with ffmpeg with lots of files in a broken order
so I tried to enhance a 16m long video with real-ESRGAN and ffmpeg, but since I have no idea how to actually get the files to sync in order, I am here. So I have been given a file on how it's supposed to operate, and I understand most of it, except for one thing I just can't figure out, and that's the file order it's supposed to compile it in. ffmpeg -i out_frames/frame%08d.jpg -i test.mp4 -map 0:v:0 -map 1:a:0 -c:a copy -c:v libx264 -r 23.98 -pix_fmt yuv420p test.mp4 This is the file, and the bolded part is very confusing for me since the original file that was given with it actually has about 100 or more files(frames), and the "08" here makes no sense to me. Basically what I need is "that bolded part" but so it can compile an order like this: frame00054953.jpg <-- End frame frame00001946.jpg <-- Start frame I've deleted the intros to save filesize because it's currently sitting at 53,010 files with 140GB. I just tried different combos to see if one could work out(like frame%01946d, dumb stuff like that), but could only get the basic one file to render and that resulted in a single frame, over 16m long audio... Going on their website, I also completely lost my mind. Any help is appreciated.
[ "I actually solved this with just a simple -start_number command I found later.\n" ]
[ 0 ]
[]
[]
[ "ffmpeg", "jpeg", "mp4", "video" ]
stackoverflow_0074675310_ffmpeg_jpeg_mp4_video.txt
Q: Include external library to c++ project in Xcode I am pretty new to c++. I have experience with other programming languages where including external stuff is handled by package managers or the language itself. It looks like this is not the case for c++ where you have to manually specify where your external libraries reside. I use macOS as my work environment and I'd like to use Xcode but I didn't use it that much in the past (I have developed in Java and Node.js). I have created a Command Line Tool c++ project with Xcode and made a cli application with it. Now I am trying to include some external library to add a GUI and I wanted to explore the available options but I couldn't successfully build my project with any of the external libraries I've tried. To include an external library to my Xcode project I have tried the following steps based on info found online: Install the library with homebrew or build it. Add the .a file to Library search paths Add the library's include folder (containing the headers) to Headers search paths Add -l*libraryname* to Other Linker flags I didn't got this to work. I followed the instructions found on the libraries docs but when I try to run my project again with Xcode, it fails no matter what library I try to use. I know that different libraries have different ways to be used but I think I am missing something basic here. I would like some info pointing me out in the right direction. As I said, I am learning c++ coming from very different languages and I feel a bit confused about this thing of including external stuff. I need to enter the right mindset and would appreciate a clarification or even some resource I could learn what I am asking for from. What is the most conventional way of adding an external library to a c++ file and compile it? How you do it in a Xcode project? Where can I find exhaustive info about this? A: To add an external library to your Xcode project, follow these steps: Open your Xcode project and select the project file in the Project navigator on the left side of the window. In the main editor area, select the "Build Phases" tab. Under the "Link Binary with Libraries" section, click the "+" button to add a new library. In the "Choose frameworks and libraries to add" dialog, search for the library you want to add and select it. Then, click the "Add" button. The library should now appear in the "Link Binary with Libraries" section. If the library is not installed in a default location, you may also need to add the library's header files to your project. To do this, select the "Build Settings" tab and add the path to the library's header files to the "Header Search Paths" setting. If the library is not written in Objective-C or Swift, you may also need to add a bridging header to your project. To do this, create a new file in your project and name it with the ".h" extension (e.g. "MyLibrary.h"). Then, import the library's header files in this file and add the path to this file to the "Objective-C Bridging Header" setting in the "Build Settings" tab. After completing these steps, you should be able to use the external library in your Xcode project. Note that you may need to consult the library's documentation for specific instructions on how to use it.
Include external library to c++ project in Xcode
I am pretty new to c++. I have experience with other programming languages where including external stuff is handled by package managers or the language itself. It looks like this is not the case for c++ where you have to manually specify where your external libraries reside. I use macOS as my work environment and I'd like to use Xcode but I didn't use it that much in the past (I have developed in Java and Node.js). I have created a Command Line Tool c++ project with Xcode and made a cli application with it. Now I am trying to include some external library to add a GUI and I wanted to explore the available options but I couldn't successfully build my project with any of the external libraries I've tried. To include an external library to my Xcode project I have tried the following steps based on info found online: Install the library with homebrew or build it. Add the .a file to Library search paths Add the library's include folder (containing the headers) to Headers search paths Add -l*libraryname* to Other Linker flags I didn't got this to work. I followed the instructions found on the libraries docs but when I try to run my project again with Xcode, it fails no matter what library I try to use. I know that different libraries have different ways to be used but I think I am missing something basic here. I would like some info pointing me out in the right direction. As I said, I am learning c++ coming from very different languages and I feel a bit confused about this thing of including external stuff. I need to enter the right mindset and would appreciate a clarification or even some resource I could learn what I am asking for from. What is the most conventional way of adding an external library to a c++ file and compile it? How you do it in a Xcode project? Where can I find exhaustive info about this?
[ "To add an external library to your Xcode project, follow these steps:\n\nOpen your Xcode project and select the project file in the Project\nnavigator on the left side of the window.\nIn the main editor area, select the \"Build Phases\" tab.\nUnder the \"Link Binary with Libraries\" section, click the \"+\" button\nto add a new library.\nIn the \"Choose frameworks and libraries to add\" dialog, search for\nthe library you want to add and select it. Then, click the \"Add\"\nbutton.\nThe library should now appear in the \"Link Binary with Libraries\"\nsection.\nIf the library is not installed in a default location, you may also\nneed to add the library's header files to your project. To do this,\nselect the \"Build Settings\" tab and add the path to the library's\nheader files to the \"Header Search Paths\" setting.\nIf the library is not written in Objective-C or Swift, you may also\nneed to add a bridging header to your project. To do this, create a\nnew file in your project and name it with the \".h\" extension (e.g.\n\"MyLibrary.h\"). Then, import the library's header files in this file\nand add the path to this file to the \"Objective-C Bridging Header\"\nsetting in the \"Build Settings\" tab.\n\nAfter completing these steps, you should be able to use the external library in your Xcode project. Note that you may need to consult the library's documentation for specific instructions on how to use it.\n" ]
[ 0 ]
[]
[]
[ "c++", "xcode" ]
stackoverflow_0074678135_c++_xcode.txt
Q: How to mention the optional parameters in reactjs children I m using reactjs + typescript for a react application. I have a parent component called <Video>, like so: <Video param1={param1} param2={param2} param3={param3} /> Inside Video component, there is a child component, the <VideoControls/> <VideoControls param1={param1} param2={param2} param3={param3} /> From page1 i call the <Video Param1={param1} Param2={param2} /> with just Param1 and Param2, so i have a type : type props { param1: string, param2: string, param3?: string, } From page2 i call the <Video Param1={param1} Param2={param2} Param3={param3} /> with all the parameters. But when it comes to the child component <VideoControls /> i dont know how to pass the parameters, because some times its all the 3 params and some times its just the 2 of them. Should i pass all the 3 params and when it comes from page1, the param3 will pass undefined ? is there any doc for that case ? A: You should pass all of the props from the parent component to the child component, even if some of the props are optional. This will ensure that all of the props are available to the child component, and the child component can choose which props to use. One way to do this is using the ... spread operator. This will automatically include all of the props from the Video component, including any optional props that may not have been provided. For example: const Video: React.FC<Props> = (props) => { return ( <> <VideoControls {...props} /> </> ); } Then, inside of VideoControls, decide how you want to handle the props, depending on whether or not they are available.
How to mention the optional parameters in reactjs children
I m using reactjs + typescript for a react application. I have a parent component called <Video>, like so: <Video param1={param1} param2={param2} param3={param3} /> Inside Video component, there is a child component, the <VideoControls/> <VideoControls param1={param1} param2={param2} param3={param3} /> From page1 i call the <Video Param1={param1} Param2={param2} /> with just Param1 and Param2, so i have a type : type props { param1: string, param2: string, param3?: string, } From page2 i call the <Video Param1={param1} Param2={param2} Param3={param3} /> with all the parameters. But when it comes to the child component <VideoControls /> i dont know how to pass the parameters, because some times its all the 3 params and some times its just the 2 of them. Should i pass all the 3 params and when it comes from page1, the param3 will pass undefined ? is there any doc for that case ?
[ "You should pass all of the props from the parent component to the child component, even if some of the props are optional. This will ensure that all of the props are available to the child component, and the child component can choose which props to use.\nOne way to do this is using the ... spread operator. This will automatically include all of the props from the Video component, including any optional props that may not have been provided. For example:\nconst Video: React.FC<Props> = (props) => {\n return (\n <>\n <VideoControls {...props} />\n </>\n );\n}\n\nThen, inside of VideoControls, decide how you want to handle the props, depending on whether or not they are available.\n" ]
[ 1 ]
[]
[]
[ "javascript", "reactjs" ]
stackoverflow_0074678710_javascript_reactjs.txt
Q: My SMS Transfer related App rejected due to Violation of Permissions policy I had submitted my SMS Transfer app on Google Play Store and I had added READ_SMS and WRITE_SMS permission in the manifest. I had selected "Cross-device synchronization or transfer of SMS or calls" from Declare permissions for your app but Google rejected the app with the below information: Apps with a declared core functionality for Cross-device synchronization or transfer of SMS or calls can only access these permissions: READ_SMS, RECEIVE_MMS, RECEIVE_SMS, RECEIVE_WAP_PUSH, SEND_SMS, READ_CALL_LOG. Please remove the permission(s) WRITE_SMS. Based on our review, we found your app’s expressed user experience did not match your declared core functionality Cross-device synchronization or transfer of SMS or calls. Please remove these permissions from your app. Your app has default handler capability, which was not disclosed in the declaration form. Please remove the unnecessary capability and / or submit a revised declaration form. A: It is due to Google's restriction on SMS or Call log permission. If you really need these permissions to fulfil certain functionalities, you should be filling 6-page Permission Declaration Form and submitting to Google Play for review. A: Try to use this app it allows to send received SMS to other device or slack https://play.google.com/store/apps/details?id=com.sms.pipe
My SMS Transfer related App rejected due to Violation of Permissions policy
I had submitted my SMS Transfer app on Google Play Store and I had added READ_SMS and WRITE_SMS permission in the manifest. I had selected "Cross-device synchronization or transfer of SMS or calls" from Declare permissions for your app but Google rejected the app with the below information: Apps with a declared core functionality for Cross-device synchronization or transfer of SMS or calls can only access these permissions: READ_SMS, RECEIVE_MMS, RECEIVE_SMS, RECEIVE_WAP_PUSH, SEND_SMS, READ_CALL_LOG. Please remove the permission(s) WRITE_SMS. Based on our review, we found your app’s expressed user experience did not match your declared core functionality Cross-device synchronization or transfer of SMS or calls. Please remove these permissions from your app. Your app has default handler capability, which was not disclosed in the declaration form. Please remove the unnecessary capability and / or submit a revised declaration form.
[ "It is due to Google's restriction on SMS or Call log permission.\nIf you really need these permissions to fulfil certain functionalities, you should be filling 6-page Permission Declaration Form and submitting to Google Play for review.\n", "Try to use this app\nit allows to send received SMS to other device or slack\nhttps://play.google.com/store/apps/details?id=com.sms.pipe\n" ]
[ 1, 0 ]
[]
[]
[ "android", "android_permissions", "google_play", "sms" ]
stackoverflow_0056852176_android_android_permissions_google_play_sms.txt
Q: How to generate arbitrary high dimensional connectivity structures for scipy.ndimage.label I have some high dimensional boolean data, in this example an array with 4 dimensions, but this is arbitrary: X.shape (3, 2, 66, 241) I want to group the dataset into connected regions of True values, which can be done with scipy.ndimage.label, with the aid of a connectivity structure which says which points in the array should be considered to touch. The default 2-D structure is a cross: [[0,1,0], [1,1,1], [0,1,0]] Which can be easily extended to high dimensions if all those dimensions are connected. However I want to programmatically generate such a structure where I have a list of which dims are connected to which: #We want to find connections across dims 2 and 3 across each slice of dims 0 and 1: dim_connections=[[0],[1],[2,3]] #Now we want two separate connected subspaces in our data: dim_connections=[[0,1],[2,3]] For individual cases I can work out with hard-thinking how to generate the correct structuring element, but I am struggling to work out the general rule! For clarity I want something like: mystructure=construct_arbitrary_structure(ndim, dim_connections) the_correct_result=scipy.ndimage.label(X,structure=my_structure) A: The key to constructing an arbitrary structure for scipy.ndimage.label is to understand the concept of a neighborhood. A neighborhood is a set of points in the data that are considered to be connected. For example, in a 2D array, the neighborhood of a point (x,y) is the set of points {(x-1,y-1), (x-1,y), (x-1,y+1), (x,y-1), (x,y), (x,y+1), (x+1,y-1), (x+1,y), (x+1,y+1)}. In order to construct an arbitrary structure for scipy.ndimage.label, we need to define a neighborhood for each point in the data. To do this, we need to define a set of connections between the dimensions of the data. For example, if we have a 4D array, and we want to connect dimensions 0 and 1, and dimensions 2 and 3, then our set of connections would be [[0,1],[2,3]]. Once we have defined our set of connections, we can construct our structure tensor. The structure tensor is a 3D array, where the first two dimensions correspond to the dimensions of the data, and the third dimension corresponds to the connections between the dimensions. For example, if we have a 4D array, and we want to connect dimensions 0 and 1, and dimensions 2 and 3, then our structure tensor would be of size (4,4,2). The structure tensor is constructed by setting the elements of the third dimension to 1 if the corresponding dimensions are connected, and 0 otherwise. For example, if we have a 4D array, and we want to connect dimensions 0 and 1, and dimensions 2 and 3, then our structure tensor would be: [[[1, 0], [0, 0], [0, 1], [0, 0]], [[0, 0], [1, 0], [0, 1], [0, 0]], [[0, 1], [0, 0], [1, 0], [0, 0]], [[0, 0], [0, 0], [0, 1], [1, 0]]] Once we have constructed our structure tensor, we can pass it to scipy.ndimage.label to generate the connected regions of our data. A: This should work for you def construct_arbitrary_structure(ndim, dim_connections): #Create structure array structure = np.zeros([3] * ndim, dtype=int) #Fill structure array for d in dim_connections: if len(d) > 1: # Set the connection between multiple dimensions for i in range(ndim): # Create a unit vector u = np.zeros(ndim, dtype=int) u[i] = 1 # Create a mask by adding the connection between multiple dimensions M = np.zeros([3] * ndim, dtype=int) for j in d: M += np.roll(u, j) structure += M else: # Set the connection for one dimension u = np.zeros(ndim, dtype=int) u[d[0]] = 1 structure += u #Make sure it's symmetric for i in range(ndim): structure += np.roll(structure, 1, axis=i) return structure A: o construct the arbitrary structure with the desired connectivity, you can use a loop to iterate over the dimensions and create a 3-D structure that is the default 2-D structure in the dimensions that need to be connected, and a 1-D structure (i.e. a line) in the other dimensions. For example: import numpy as np from scipy import ndimage # Create the default 2-D structure default_structure = ndimage.generate_binary_structure(2, 1) def construct_arbitrary_structure(ndim, dim_connections): # Create an empty structure structure = np.zeros((3,)*ndim, dtype=np.int8) for dims in dim_connections: # Loop over the dimensions that need to be connected for d in dims: # If the dimension is the first or last in the list, use a 1-D line # Otherwise, use the default 2-D structure if d == dims[0]: structure[(slice(None),)*d + (1,)] = 1 elif d == dims[-1]: structure[(slice(None),)*d + (1,)] = 1 else: structure[(slice(None),)*d + (slice(None),)] = default_structure return structure Example usage dim_connections = [[0],[1],[2,3]] my_structure = construct_arbitrary_structure(4, dim_connections) print(my_structure) To use the structure with scipy.ndimage.label to find connected regions in your data, you can use the structure parameter to specify the structure you want to use for the labeling. For example: import numpy as np from scipy import ndimage # Generate some random 4-dimensional boolean data X = np.random.random((3, 2, 66, 241)) > 0.5 # Define the structure you want to use dim_connections = [[0, 1], [2, 3]] my_structure = construct_arbitrary_structure(X.ndim, dim_connections) # Use scipy.ndimage.label to find connected regions in your data labeled_regions, num_labels = ndimage.label(X, structure=my_structure)
How to generate arbitrary high dimensional connectivity structures for scipy.ndimage.label
I have some high dimensional boolean data, in this example an array with 4 dimensions, but this is arbitrary: X.shape (3, 2, 66, 241) I want to group the dataset into connected regions of True values, which can be done with scipy.ndimage.label, with the aid of a connectivity structure which says which points in the array should be considered to touch. The default 2-D structure is a cross: [[0,1,0], [1,1,1], [0,1,0]] Which can be easily extended to high dimensions if all those dimensions are connected. However I want to programmatically generate such a structure where I have a list of which dims are connected to which: #We want to find connections across dims 2 and 3 across each slice of dims 0 and 1: dim_connections=[[0],[1],[2,3]] #Now we want two separate connected subspaces in our data: dim_connections=[[0,1],[2,3]] For individual cases I can work out with hard-thinking how to generate the correct structuring element, but I am struggling to work out the general rule! For clarity I want something like: mystructure=construct_arbitrary_structure(ndim, dim_connections) the_correct_result=scipy.ndimage.label(X,structure=my_structure)
[ "The key to constructing an arbitrary structure for scipy.ndimage.label is to understand the concept of a neighborhood. A neighborhood is a set of points in the data that are considered to be connected. For example, in a 2D array, the neighborhood of a point (x,y) is the set of points {(x-1,y-1), (x-1,y), (x-1,y+1), (x,y-1), (x,y), (x,y+1), (x+1,y-1), (x+1,y), (x+1,y+1)}.\nIn order to construct an arbitrary structure for scipy.ndimage.label, we need to define a neighborhood for each point in the data. To do this, we need to define a set of connections between the dimensions of the data. For example, if we have a 4D array, and we want to connect dimensions 0 and 1, and dimensions 2 and 3, then our set of connections would be [[0,1],[2,3]].\nOnce we have defined our set of connections, we can construct our structure tensor. The structure tensor is a 3D array, where the first two dimensions correspond to the dimensions of the data, and the third dimension corresponds to the connections between the dimensions. For example, if we have a 4D array, and we want to connect dimensions 0 and 1, and dimensions 2 and 3, then our structure tensor would be of size (4,4,2).\nThe structure tensor is constructed by setting the elements of the third dimension to 1 if the corresponding dimensions are connected, and 0 otherwise. For example, if we have a 4D array, and we want to connect dimensions 0 and 1, and dimensions 2 and 3, then our structure tensor would be:\n[[[1, 0],\n [0, 0],\n [0, 1],\n [0, 0]],\n \n [[0, 0],\n [1, 0],\n [0, 1],\n [0, 0]],\n \n [[0, 1],\n [0, 0],\n [1, 0],\n [0, 0]],\n \n [[0, 0],\n [0, 0],\n [0, 1],\n [1, 0]]]\n\nOnce we have constructed our structure tensor, we can pass it to scipy.ndimage.label to generate the connected regions of our data.\n", "This should work for you\n\ndef construct_arbitrary_structure(ndim, dim_connections):\n #Create structure array\n structure = np.zeros([3] * ndim, dtype=int)\n\n #Fill structure array\n for d in dim_connections:\n if len(d) > 1:\n # Set the connection between multiple dimensions\n for i in range(ndim):\n # Create a unit vector\n u = np.zeros(ndim, dtype=int)\n u[i] = 1\n\n # Create a mask by adding the connection between multiple dimensions\n M = np.zeros([3] * ndim, dtype=int)\n for j in d:\n M += np.roll(u, j)\n structure += M\n else:\n # Set the connection for one dimension\n u = np.zeros(ndim, dtype=int)\n u[d[0]] = 1\n structure += u\n\n #Make sure it's symmetric\n for i in range(ndim):\n structure += np.roll(structure, 1, axis=i)\n\n return structure\n\n", "o construct the arbitrary structure with the desired connectivity, you can use a loop to iterate over the dimensions and create a 3-D structure that is the default 2-D structure in the dimensions that need to be connected, and a 1-D structure (i.e. a line) in the other dimensions. For example:\nimport numpy as np\nfrom scipy import ndimage\n\n# Create the default 2-D structure\ndefault_structure = ndimage.generate_binary_structure(2, 1)\n\ndef construct_arbitrary_structure(ndim, dim_connections):\n# Create an empty structure\n structure = np.zeros((3,)*ndim, dtype=np.int8)\n for dims in dim_connections:\n # Loop over the dimensions that need to be connected\n for d in dims:\n # If the dimension is the first or last in the list, use a 1-D line\n # Otherwise, use the default 2-D structure\n if d == dims[0]:\n structure[(slice(None),)*d + (1,)] = 1\n elif d == dims[-1]:\n structure[(slice(None),)*d + (1,)] = 1\n else:\n structure[(slice(None),)*d + (slice(None),)] = default_structure\n return structure\n\nExample usage\ndim_connections = [[0],[1],[2,3]]\nmy_structure = construct_arbitrary_structure(4, dim_connections)\nprint(my_structure)\n\nTo use the structure with scipy.ndimage.label to find connected regions in your data, you can use the structure parameter to specify the structure you want to use for the labeling. For example:\nimport numpy as np\nfrom scipy import ndimage\n\n# Generate some random 4-dimensional boolean data\nX = np.random.random((3, 2, 66, 241)) > 0.5\n\n# Define the structure you want to use\ndim_connections = [[0, 1], [2, 3]]\nmy_structure = construct_arbitrary_structure(X.ndim, dim_connections)\n\n# Use scipy.ndimage.label to find connected regions in your data\nlabeled_regions, num_labels = ndimage.label(X, structure=my_structure)\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "image_processing", "ndimage", "python", "scipy" ]
stackoverflow_0074564292_image_processing_ndimage_python_scipy.txt
Q: regex query that searches multiple words I have a query that finds a word in a string, but its only a single word, is it possible to search for list of words? this is my current regex: (?i)(?<=\b|\\n)cat\b A: Yes, it is possible to search for a list of words in a string using a regular expression. To do this, you can use the | (or) operator to combine multiple regular expressions into a single expression. The | operator will match any of the expressions that come before or after it, so you can use it to create a regular expression that will match any of the words in your list. For example, if you have a list of words ["cat", "dog", "bird"], you could use the following regular expression to search for any of those words in a string: # Use the | operator to combine multiple regular expressions (?i)(?<=\b|\\n)(cat|dog|bird)\b A: Yes, it is possible to search for a list of words in a string using regex. You can use the | character to specify multiple words to search for, like this: (?i)(?<=\b|\\n)(cat|dog|bird)\b This regex will match the words cat, dog, or bird, regardless of their case (thanks to the (?i) flag), and will require that they appear as whole words (thanks to the \b character class). Note that the (?<=\b|\n) part of the regex is called a lookbehind assertion. It specifies that the word must be preceded by either a word boundary (\b) or a newline character (\n). This is useful to ensure that the word is not part of a longer word, but you can omit this part if you don't need it. You can also use a character class to search for a list of words, like this: (?i)\b[catdogbird]\b This regex will match the words cat, dog, or bird, regardless of their case, but only if they appear as whole words. The [] characters specify a character class, which will match any of the characters within it.
regex query that searches multiple words
I have a query that finds a word in a string, but its only a single word, is it possible to search for list of words? this is my current regex: (?i)(?<=\b|\\n)cat\b
[ "Yes, it is possible to search for a list of words in a string using a regular expression. To do this, you can use the | (or) operator to combine multiple regular expressions into a single expression. The | operator will match any of the expressions that come before or after it, so you can use it to create a regular expression that will match any of the words in your list.\nFor example, if you have a list of words [\"cat\", \"dog\", \"bird\"], you could use the following regular expression to search for any of those words in a string:\n# Use the | operator to combine multiple regular expressions\n(?i)(?<=\\b|\\\\n)(cat|dog|bird)\\b\n\n", "Yes, it is possible to search for a list of words in a string using regex. You can use the | character to specify multiple words to search for, like this:\n(?i)(?<=\\b|\\\\n)(cat|dog|bird)\\b\n\nThis regex will match the words cat, dog, or bird, regardless of their case (thanks to the (?i) flag), and will require that they appear as whole words (thanks to the \\b character class).\nNote that the (?<=\\b|\\n) part of the regex is called a lookbehind assertion. It specifies that the word must be preceded by either a word boundary (\\b) or a newline character (\\n). This is useful to ensure that the word is not part of a longer word, but you can omit this part if you don't need it.\nYou can also use a character class to search for a list of words, like this:\n(?i)\\b[catdogbird]\\b\n\nThis regex will match the words cat, dog, or bird, regardless of their case, but only if they appear as whole words. The [] characters specify a character class, which will match any of the characters within it.\n" ]
[ 0, 0 ]
[]
[]
[ "regex" ]
stackoverflow_0074678927_regex.txt
Q: How to create a gravity effect with Javascript? Google gravity and gravity script are two nice demonstrations. but no source code or tutorials are available. and the original JS files are very big. How can I create a Gravity effect with Drag & drop(specially being "Throw able" and "rotatable" like google gravity) on a certain element? A: You will want to start with a physics engine, the one Google Gravity uses is Box2Djs which is a javascript port of Box2D. You can read the manual for Box2D to learn how to use it, though the manual itself states that you will have little idea what you are doing without some knowledge of rigid body physics (force, impulse, torque, etc), though these examples may help you get started. If you want to write the physics engine yourself you will have to at least implement 2D rigid body dynamics and collision detection for it to look like the examples you gave. A tutorial for doing that would be called a computer simulation class and would have a linear algebra and physics I prerequisite, it's not a trivial task. Afterwards, you will have to learn about javascript animation techniques. I recommend learning about window.requestAnimationFrame. Using setInterval(stepFunction, time) will work but it won't be as efficient as it could be in modern browsers. A: Look a this jquery plugin on github JQuery.throwable just do $("Selector").throwable() and the object will be under gravity A: One other framework to consider: Matter.js — Demo: Easy Physics Sandbox in JavaScript. The Physics Gravity is hard. That's because gravity is curved spacetime, and we can only make 2d representations of this warping that happens in the third dimension. On the other hand -- moving an element at a consistent 9.8 m/s^2 in a linear direction towards one direction, that's actually not too hard to implement. The CSS Solution All we really need is transition: all 1s linear; to control the speed of the animation, margin-top to animate the element moving downward, and transition-timing-function with a cubic-bezier that's fairly representative of 9.8 m/s^2. The Demo document.addEventListener('DOMContentLoaded', function(event) { document.getElementById('drop').addEventListener('click', function(ev) { div = document.createElement('div'); div.classList.add('gravity-affected-object'); image = document.createElement('img'); image.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Red_Apple.jpg/640px-Red_Apple.jpg'; image.width = 100; image.classList.add('gravity-affected-object'); div.style.position = 'absolute'; div.style.left = '50%'; div.appendChild(image); document.getElementById('page-top').appendChild(div); setTimeout(function() { div.style.marginTop = '1000px'; }, 100); }); }); .gravity-affected-object { transition: all 1s linear; transition-timing-function: cubic-bezier(0.33333, 0, 0.66667, 0.33333); z-index: -5000; } <div id="page-top"></div> <button id="drop">Drop</button>
How to create a gravity effect with Javascript?
Google gravity and gravity script are two nice demonstrations. but no source code or tutorials are available. and the original JS files are very big. How can I create a Gravity effect with Drag & drop(specially being "Throw able" and "rotatable" like google gravity) on a certain element?
[ "You will want to start with a physics engine, the one Google Gravity uses is Box2Djs which is a javascript port of Box2D. You can read the manual for Box2D to learn how to use it, though the manual itself states that you will have little idea what you are doing without some knowledge of rigid body physics (force, impulse, torque, etc), though these examples may help you get started.\nIf you want to write the physics engine yourself you will have to at least implement 2D rigid body dynamics and collision detection for it to look like the examples you gave. A tutorial for doing that would be called a computer simulation class and would have a linear algebra and physics I prerequisite, it's not a trivial task.\nAfterwards, you will have to learn about javascript animation techniques. I recommend learning about window.requestAnimationFrame. Using setInterval(stepFunction, time) will work but it won't be as efficient as it could be in modern browsers.\n", "Look a this jquery plugin on github JQuery.throwable\njust do $(\"Selector\").throwable() and the object will be under gravity\n", "One other framework to consider: Matter.js — Demo: Easy Physics Sandbox in JavaScript.\nThe Physics\nGravity is hard. That's because gravity is curved spacetime, and we can only make 2d representations of this warping that happens in the third dimension.\nOn the other hand -- moving an element at a consistent 9.8 m/s^2 in a linear direction towards one direction, that's actually not too hard to implement.\nThe CSS Solution\nAll we really need is transition: all 1s linear; to control the speed of the animation, margin-top to animate the element moving downward, and transition-timing-function with a cubic-bezier that's fairly representative of 9.8 m/s^2.\nThe Demo\n\n\ndocument.addEventListener('DOMContentLoaded', function(event) {\n document.getElementById('drop').addEventListener('click', function(ev) {\n div = document.createElement('div');\n div.classList.add('gravity-affected-object');\n image = document.createElement('img');\n image.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Red_Apple.jpg/640px-Red_Apple.jpg';\n image.width = 100;\n image.classList.add('gravity-affected-object');\n div.style.position = 'absolute';\n div.style.left = '50%';\n \n div.appendChild(image);\n \n document.getElementById('page-top').appendChild(div);\n setTimeout(function() {\n div.style.marginTop = '1000px';\n }, 100);\n });\n});\n.gravity-affected-object {\n transition: all 1s linear;\n transition-timing-function: cubic-bezier(0.33333, 0, 0.66667, 0.33333);\n z-index: -5000;\n}\n<div id=\"page-top\"></div>\n\n<button id=\"drop\">Drop</button>\n\n\n\n" ]
[ 10, 6, 0 ]
[]
[]
[ "effects", "html", "javascript" ]
stackoverflow_0008825519_effects_html_javascript.txt
Q: Unlock on ReentrantLock without IllegalMonitorStateException I have a piece of code (simplified): if(reentrantLockObject.isLocked()) { reentrantLockObject.unlock(); } where reentrantLockObject is java.util.concurrent.locks.ReentrantLock. Sometimes I get IllegalMonitorStateException. It seams that lock was released between check and unlock() call. How can I prevent this exception? A: isLocked returns whether any thread holds the lock. I think you want isHeldByCurrentThread: if (reentrantLockObject.isHeldByCurrentThread()) { reentrantLockObject.unlock(); } Having said that, isHeldByCurrentThread is documented to be mainly for diagnostic purposes - it would be unusual for this piece of code to be the right approach. Can you explain why you think you need it? A: You need to own the lock to be able to unlock it. reentrantLockObject.isLocked() only is true if some thread owns the lock, not necessarily you. reentrantLockObject.lock(); try{ // do stuff }finally{ reentrantLockObject.unlock(); } Here the thread owns the lock so they are able to unlock it. A: ReentrantLock throws this exception according to this logic: if (Thread.currentThread() != getExclusiveOwnerThread()) { throw new IllegalMonitorStateException(); } So the solution is to check if the same thread is unlocking: if (reentrantLockObject.isHeldByCurrentThread()) { reentrantLockObject.unlock(); } A: private ReentrantLock lock = new ReentrantLock(); if (lock.tryLock()) { try { //your code } finally { lock.unlock(); } }
Unlock on ReentrantLock without IllegalMonitorStateException
I have a piece of code (simplified): if(reentrantLockObject.isLocked()) { reentrantLockObject.unlock(); } where reentrantLockObject is java.util.concurrent.locks.ReentrantLock. Sometimes I get IllegalMonitorStateException. It seams that lock was released between check and unlock() call. How can I prevent this exception?
[ "isLocked returns whether any thread holds the lock. I think you want isHeldByCurrentThread:\nif (reentrantLockObject.isHeldByCurrentThread()) {\n reentrantLockObject.unlock();\n}\n\nHaving said that, isHeldByCurrentThread is documented to be mainly for diagnostic purposes - it would be unusual for this piece of code to be the right approach. Can you explain why you think you need it?\n", "You need to own the lock to be able to unlock it. reentrantLockObject.isLocked() only is true if some thread owns the lock, not necessarily you.\n reentrantLockObject.lock();\n try{\n\n // do stuff\n }finally{\n reentrantLockObject.unlock();\n }\n\nHere the thread owns the lock so they are able to unlock it.\n", "ReentrantLock throws this exception according to this logic:\nif (Thread.currentThread() != getExclusiveOwnerThread()) {\n throw new IllegalMonitorStateException();\n}\n\nSo the solution is to check if the same thread is unlocking:\nif (reentrantLockObject.isHeldByCurrentThread()) {\n reentrantLockObject.unlock();\n}\n\n", " private ReentrantLock lock = new ReentrantLock();\nif (lock.tryLock()) {\n try {\n //your code\n } finally {\n lock.unlock();\n }\n }\n\n" ]
[ 25, 7, 7, 0 ]
[]
[]
[ "concurrency", "java", "locking" ]
stackoverflow_0002811236_concurrency_java_locking.txt
Q: Factorial calculator in c I was practising some c programms for an upcoming check up at school and wanted to build a calculator where you can put in a number and it tells you what the factorial of that number is. I programmed for a while and I am stuck at this point and I don't know what's wrong. Does somebody have any idea what is wrong? "Fakultaet" means factorial. #include<stdio.h> int main(){ int zahl; int i; int j; printf("Fakultaet Rechner\n===============\n"); printf("Von welcher Zahl soll die Fakultaet berechnet werden: "); scanf("%d", &zahl); for(i=(zahl-1); i>0; i*1){ j=zahl*i; i--; } printf("%s %d %s %d", "\nDie Fakultaet von", zahl, "ist", j); return 0; } A: I tried out your code and did not get a factorial value as the line of code where I believe you are trying to calculate it will always ultimately just multiply the user entry by a value of "1". j=zahl*i; Also, even though the program does break out of the for loop, that is not a usual way to do it. Probably, when compiled, you got a warning such as this. main.c|14|warning: statement with no effect [-Wunused-value]| With that in mind, I tweaked your code such that it utilizes a for loop in a more usual and customary manner along with evaluating a factorial. #include<stdio.h> int main() { int zahl; int i; int j = 1; printf("Fakultaet Rechner\n===============\n"); printf("Von welcher Zahl soll die Fakultaet berechnet werden: "); scanf("%d", &zahl); for(i = 1; i <= zahl; i++) /* More usual and customary way to set up and utilize a for loop */ { j = j * i; /* This will provide the factorial */ } printf("Die Fakultaet von %d ist: %d\n", zahl, j); return 0; } In testing this out, the following was the output at the terminal. @Dev:~/C_Programs/Console/Factorial/bin/Release$ ./Factorial Fakultaet Rechner =============== Von welcher Zahl soll die Fakultaet berechnet werden: 6 Die Fakultaet von 6 ist: 720 Give that a try to see if it meets the spirit of your project. Also, you might want to invest in a book or tutorial reference on C programming to get a feel for the usual way code such as for loops are used.
Factorial calculator in c
I was practising some c programms for an upcoming check up at school and wanted to build a calculator where you can put in a number and it tells you what the factorial of that number is. I programmed for a while and I am stuck at this point and I don't know what's wrong. Does somebody have any idea what is wrong? "Fakultaet" means factorial. #include<stdio.h> int main(){ int zahl; int i; int j; printf("Fakultaet Rechner\n===============\n"); printf("Von welcher Zahl soll die Fakultaet berechnet werden: "); scanf("%d", &zahl); for(i=(zahl-1); i>0; i*1){ j=zahl*i; i--; } printf("%s %d %s %d", "\nDie Fakultaet von", zahl, "ist", j); return 0; }
[ "I tried out your code and did not get a factorial value as the line of code where I believe you are trying to calculate it will always ultimately just multiply the user entry by a value of \"1\".\n j=zahl*i;\n\nAlso, even though the program does break out of the for loop, that is not a usual way to do it. Probably, when compiled, you got a warning such as this.\n main.c|14|warning: statement with no effect [-Wunused-value]|\n\nWith that in mind, I tweaked your code such that it utilizes a for loop in a more usual and customary manner along with evaluating a factorial.\n#include<stdio.h>\n\nint main()\n{\n\n int zahl;\n int i;\n int j = 1;\n\n printf(\"Fakultaet Rechner\\n===============\\n\");\n printf(\"Von welcher Zahl soll die Fakultaet berechnet werden: \");\n scanf(\"%d\", &zahl);\n\n for(i = 1; i <= zahl; i++) /* More usual and customary way to set up and utilize a for loop */\n {\n j = j * i; /* This will provide the factorial */\n }\n printf(\"Die Fakultaet von %d ist: %d\\n\", zahl, j);\n\n return 0;\n}\n\nIn testing this out, the following was the output at the terminal.\n@Dev:~/C_Programs/Console/Factorial/bin/Release$ ./Factorial \nFakultaet Rechner\n===============\nVon welcher Zahl soll die Fakultaet berechnet werden: 6\nDie Fakultaet von 6 ist: 720\n\nGive that a try to see if it meets the spirit of your project. Also, you might want to invest in a book or tutorial reference on C programming to get a feel for the usual way code such as for loops are used.\n" ]
[ 0 ]
[]
[]
[ "c", "factorial" ]
stackoverflow_0074678713_c_factorial.txt
Q: Most frequent text based on criteria from another column and ignoring blanks I have below data where I need to get the most frequent text in column A based on column B, Data Set: I used the below code but it returns #N/A as I think it's possibly due to empty cells =INDEX($A$1:$A$11,MODE(IF($B$1:$B$11=3, MATCH($A$1:$A$11,$A$1:$A$11,0)))) Expected Result: "RED" How to get the most frequent text ignoring blank cells and based on another column value? A: You can add another IF() to check and ignore blank cells. =INDEX($A$1:$A$10,MODE(IF($B$1:$B$10=3, IF(A1:A10<>"",MATCH($A$1:$A$10,$A$1:$A$10,0),"")))) You may need array entry with CTRL+SHIFT+ENTER for non 365 version of excel. With Excel365 can use =@SORTBY(A1:A10,COUNTIF(A1:A10,A1:A10),-1) A: I got the answer but it seems little lengthy..
Most frequent text based on criteria from another column and ignoring blanks
I have below data where I need to get the most frequent text in column A based on column B, Data Set: I used the below code but it returns #N/A as I think it's possibly due to empty cells =INDEX($A$1:$A$11,MODE(IF($B$1:$B$11=3, MATCH($A$1:$A$11,$A$1:$A$11,0)))) Expected Result: "RED" How to get the most frequent text ignoring blank cells and based on another column value?
[ "You can add another IF() to check and ignore blank cells.\n=INDEX($A$1:$A$10,MODE(IF($B$1:$B$10=3, IF(A1:A10<>\"\",MATCH($A$1:$A$10,$A$1:$A$10,0),\"\"))))\n\nYou may need array entry with CTRL+SHIFT+ENTER for non 365 version of excel.\nWith Excel365 can use\n=@SORTBY(A1:A10,COUNTIF(A1:A10,A1:A10),-1)\n\n\n", "I got the answer but it seems little lengthy..\n\n" ]
[ 0, 0 ]
[]
[]
[ "excel", "excel_formula", "windows" ]
stackoverflow_0068062831_excel_excel_formula_windows.txt
Q: How to make a calculator and repeat function on Trading View? Excuse me! I'm a beginner programmer from Japan. I'm not a native English user, so I'll show you my broken English! [Pine-script on Trading View] Now, I want to create a calculator works on the Trading View's charts. By clicking 3 prices(high or low price on bars) on the chart, and calculate it by using 3 prices. Plot it's result on the chart. After that, reset and repeat function for accepting new inputs by clicking. [I want to make functions, like below ↓] my image and process click bar on the chart create new labels on the point I clicked calculate and plot results on the chart reset and repeat function(keep plotted past results) It seems simple,but I confess several problems. [problems] I want only one click can get Price and Time. (In other words, get X-axis and Y-axis value at once.) But, is there any way? And, I have no good idea how to repeat function. There is a way but not smart idea (delete the indicator and add it again). I know it is not ordinary usage for a indicator, but calculator needs reset button, push it reset and function again with leaving plotted past results on the chart. //@version=5 indicator("ABC_caluculator", overlay=true) Price_A = input.price(defval=0, title = "A", group="ABC_caluculator", confirm=true) Price_B = input.price(defval=0, title = "B", group="ABC_caluculator", confirm=true) Price_C = input.price(defval=0, title = "C", group="ABC_caluculator", confirm=true) Price_N = Price_C + (Price_B - Price_A) Price_V = Price_B + (Price_B - Price_C) Price_E = Price_B + (Price_B - Price_A) Price_NT= Price_C + (Price_C - Price_A) //Table //Format tblPos = input.string(title="Position on Chart", defval="Bottom Right", options=["Top Left", "Top Right", "Bottom Left", "Bottom Right", "Middle Left", "Middle Right", "Middle Bottom" ], group = "Table Customization") tblposition = tblPos == "Top Left" ? position.top_left : tblPos == "Top Right" ? position.top_right : tblPos == "Bottom Left" ? position.bottom_left : tblPos == "Bottom Right" ? position.bottom_right : tblPos == "Middle Left" ? position.middle_left : tblPos == "Middle Right" ? position.middle_right : position.bottom_center text_halign = input.string(defval = "Center", title="Horizontal Alignment", options=["Left", "Center", "Right"], group = "Table Customization") text_halign_pos = text_halign == "Left" ? text.align_left : text_halign == "Center" ? text.align_center : text.align_right text_valign = input.string(defval = "Center", title="Vertical Alignment", options=["Top", "Center", "Bottom"], group = "Table Customization") text_valign_pos = text_valign == "Top" ? text.align_top : text_valign == "Center" ? text.align_center : text.align_bottom text_size = input.string(defval = "Auto", title="Text Size", options=["Auto", "Tiny", "Small", "Normal", "Large", "Huge"], group = "Table Customization") text_size_op = text_size == "Auto" ? size.auto : text_size == "Tiny" ? size.tiny : text_size == "Small" ? size.small : text_size == "Normal" ? size.normal : text_size == "Large" ? size.large : size.huge //Dimensions border_width = input.int(defval=1, title="Border Width", group = "Dimensions") frame_width = input.int(defval=5, title="Frame Width", group = "Dimensions") table_width = input.int(defval=5, title="Cell Width", group = "Dimensions") table_height = input.int(defval=5, title="Cell Height", group = "Dimensions") //Colors tblBorderColor = input.color(title="Border Color", defval=#636363, group = "Table Styles") celllBgColor = input.color(title="Background Color", defval=#d1d1d1, group = "Table Styles") cellTextColor = input.color(title="Text Color", defval=#000000, group = "Table Styles") resultsTable = table.new(position = tblposition, columns = 6, rows = 6, bgcolor = #ffffff, border_width = border_width,frame_color = tblBorderColor, frame_width = frame_width) //A,B,C table.cell(resultsTable, column=0, row=0, text= "A", width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=1, row=0, text= str.tostring(Price_A), width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=0, row=1, text= "B", width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=1, row=1, text= str.tostring(Price_B), width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=0, row=2, text= "C", width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=1, row=2, text= str.tostring(Price_C), width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) //N,V,E,NT table.cell(resultsTable, column=2, row=0, text= "N値", width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=3, row=0, text= str.tostring(Price_N), width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=2, row=1, text= "V値", width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=3, row=1, text= str.tostring(Price_V), width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=2, row=2, text= "E値", width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=3, row=2, text= str.tostring(Price_E), width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=2, row=3, text= "NT値", width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=3, row=3, text= str.tostring(Price_NT), width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) A: You can work with click on the chart with pinescript.
How to make a calculator and repeat function on Trading View?
Excuse me! I'm a beginner programmer from Japan. I'm not a native English user, so I'll show you my broken English! [Pine-script on Trading View] Now, I want to create a calculator works on the Trading View's charts. By clicking 3 prices(high or low price on bars) on the chart, and calculate it by using 3 prices. Plot it's result on the chart. After that, reset and repeat function for accepting new inputs by clicking. [I want to make functions, like below ↓] my image and process click bar on the chart create new labels on the point I clicked calculate and plot results on the chart reset and repeat function(keep plotted past results) It seems simple,but I confess several problems. [problems] I want only one click can get Price and Time. (In other words, get X-axis and Y-axis value at once.) But, is there any way? And, I have no good idea how to repeat function. There is a way but not smart idea (delete the indicator and add it again). I know it is not ordinary usage for a indicator, but calculator needs reset button, push it reset and function again with leaving plotted past results on the chart. //@version=5 indicator("ABC_caluculator", overlay=true) Price_A = input.price(defval=0, title = "A", group="ABC_caluculator", confirm=true) Price_B = input.price(defval=0, title = "B", group="ABC_caluculator", confirm=true) Price_C = input.price(defval=0, title = "C", group="ABC_caluculator", confirm=true) Price_N = Price_C + (Price_B - Price_A) Price_V = Price_B + (Price_B - Price_C) Price_E = Price_B + (Price_B - Price_A) Price_NT= Price_C + (Price_C - Price_A) //Table //Format tblPos = input.string(title="Position on Chart", defval="Bottom Right", options=["Top Left", "Top Right", "Bottom Left", "Bottom Right", "Middle Left", "Middle Right", "Middle Bottom" ], group = "Table Customization") tblposition = tblPos == "Top Left" ? position.top_left : tblPos == "Top Right" ? position.top_right : tblPos == "Bottom Left" ? position.bottom_left : tblPos == "Bottom Right" ? position.bottom_right : tblPos == "Middle Left" ? position.middle_left : tblPos == "Middle Right" ? position.middle_right : position.bottom_center text_halign = input.string(defval = "Center", title="Horizontal Alignment", options=["Left", "Center", "Right"], group = "Table Customization") text_halign_pos = text_halign == "Left" ? text.align_left : text_halign == "Center" ? text.align_center : text.align_right text_valign = input.string(defval = "Center", title="Vertical Alignment", options=["Top", "Center", "Bottom"], group = "Table Customization") text_valign_pos = text_valign == "Top" ? text.align_top : text_valign == "Center" ? text.align_center : text.align_bottom text_size = input.string(defval = "Auto", title="Text Size", options=["Auto", "Tiny", "Small", "Normal", "Large", "Huge"], group = "Table Customization") text_size_op = text_size == "Auto" ? size.auto : text_size == "Tiny" ? size.tiny : text_size == "Small" ? size.small : text_size == "Normal" ? size.normal : text_size == "Large" ? size.large : size.huge //Dimensions border_width = input.int(defval=1, title="Border Width", group = "Dimensions") frame_width = input.int(defval=5, title="Frame Width", group = "Dimensions") table_width = input.int(defval=5, title="Cell Width", group = "Dimensions") table_height = input.int(defval=5, title="Cell Height", group = "Dimensions") //Colors tblBorderColor = input.color(title="Border Color", defval=#636363, group = "Table Styles") celllBgColor = input.color(title="Background Color", defval=#d1d1d1, group = "Table Styles") cellTextColor = input.color(title="Text Color", defval=#000000, group = "Table Styles") resultsTable = table.new(position = tblposition, columns = 6, rows = 6, bgcolor = #ffffff, border_width = border_width,frame_color = tblBorderColor, frame_width = frame_width) //A,B,C table.cell(resultsTable, column=0, row=0, text= "A", width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=1, row=0, text= str.tostring(Price_A), width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=0, row=1, text= "B", width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=1, row=1, text= str.tostring(Price_B), width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=0, row=2, text= "C", width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=1, row=2, text= str.tostring(Price_C), width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) //N,V,E,NT table.cell(resultsTable, column=2, row=0, text= "N値", width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=3, row=0, text= str.tostring(Price_N), width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=2, row=1, text= "V値", width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=3, row=1, text= str.tostring(Price_V), width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=2, row=2, text= "E値", width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=3, row=2, text= str.tostring(Price_E), width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=2, row=3, text= "NT値", width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor) table.cell(resultsTable, column=3, row=3, text= str.tostring(Price_NT), width = table_width, height = table_height, text_size = text_size_op, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor)
[ "You can work with click on the chart with pinescript.\n" ]
[ 0 ]
[]
[]
[ "calculator", "pinescript_v5", "repeat", "tradingview_api" ]
stackoverflow_0074677677_calculator_pinescript_v5_repeat_tradingview_api.txt
Q: Using PixelCopy.request() to save a screenshot of a SurfaceView returns a black bitmap I'm developing an app where I need to save the content drawn on a SurfaceView canvas to an image file. I read that the PixelCopy API can be used to do this after API level 24, but so far my code only returns an empty, black bitmap. Here's what I tried: private CustomView my_view; //CustomView extends SurfaceView implements SurfaceHolder.Callback private void captureImage() { Bitmap bitmap = Bitmap.createBitmap(my_view.getWidth(), my_view.getHeight(), Bitmap.Config.ARGB_8888); PixelCopy.request(my_view, bitmap, new PixelCopy.OnPixelCopyFinishedListener() { @Override public void onPixelCopyFinished(int copyResult) { try { saveImageToFile(bitmap, "myfilename"); //This saved image is empty and black } catch (IOException ignored) { } } }, new Handler(Looper.getMainLooper())); } If I try the old approach of using getDrawingCache() as shown below, then everything works as expected and I get an image with all the content rendered on the SurfaceView. my_view.setDrawingCacheEnabled(true); Bitmap bitmap = my_view.getDrawingCache(); //This works try { saveImageToFile(bitmap, "myfilename"); } catch (IOException ignored) { } my_view.destroyDrawingCache(); my_view.setDrawingCacheEnabled(false); However, I would like to use the PixelCopy API since the getDrawingCache() function has been deprecated. Does anyone know what the issue might be with my PixelCopy approach above? A: Have you checked the copyResult if it is success? I recently used PixelCopy, and it worked very well! I will provide the code. First we get the view coordinates on the window as a Rect: fun getViewRect(screenshotView: View): Rect { val viewPadding = 8.toIntPixel(this) val viewLocation = IntArray(2) screenshotView.getLocationInWindow(viewLocation) return Rect( viewLocation[0] - viewPadding, viewLocation[1] - viewPadding, viewLocation[0] + screenshotView.width + viewPadding, viewLocation[1] + screenshotView.height + viewPadding ) } then we write a function to take a screenshot: fun takeScreenshot( activity: Activity, viewRect: Rect, onSuccess: (Bitmap) -> Unit ) { val bitmap = Bitmap.createBitmap(viewRect.width(), viewRect.height(), Bitmap.Config.ARGB_8888) PixelCopy.request(activity.window, viewRect, bitmap, { copyResult -> if (copyResult == PixelCopy.SUCCESS) { onSuccess(bitmap) } else { error("problem with taking a screenshot") } bitmap.recycle() }, Handler(Looper.getMainLooper()) ) } then you can call the function: takeScreenshot(activity, activity.getViewRect()) { bitmap -> saveImageToFile(bitmap, "myfilename.png") }
Using PixelCopy.request() to save a screenshot of a SurfaceView returns a black bitmap
I'm developing an app where I need to save the content drawn on a SurfaceView canvas to an image file. I read that the PixelCopy API can be used to do this after API level 24, but so far my code only returns an empty, black bitmap. Here's what I tried: private CustomView my_view; //CustomView extends SurfaceView implements SurfaceHolder.Callback private void captureImage() { Bitmap bitmap = Bitmap.createBitmap(my_view.getWidth(), my_view.getHeight(), Bitmap.Config.ARGB_8888); PixelCopy.request(my_view, bitmap, new PixelCopy.OnPixelCopyFinishedListener() { @Override public void onPixelCopyFinished(int copyResult) { try { saveImageToFile(bitmap, "myfilename"); //This saved image is empty and black } catch (IOException ignored) { } } }, new Handler(Looper.getMainLooper())); } If I try the old approach of using getDrawingCache() as shown below, then everything works as expected and I get an image with all the content rendered on the SurfaceView. my_view.setDrawingCacheEnabled(true); Bitmap bitmap = my_view.getDrawingCache(); //This works try { saveImageToFile(bitmap, "myfilename"); } catch (IOException ignored) { } my_view.destroyDrawingCache(); my_view.setDrawingCacheEnabled(false); However, I would like to use the PixelCopy API since the getDrawingCache() function has been deprecated. Does anyone know what the issue might be with my PixelCopy approach above?
[ "Have you checked the copyResult if it is success?\nI recently used PixelCopy, and it worked very well!\nI will provide the code.\nFirst we get the view coordinates on the window as a Rect:\nfun getViewRect(screenshotView: View): Rect {\n val viewPadding = 8.toIntPixel(this)\n\n val viewLocation = IntArray(2)\n screenshotView.getLocationInWindow(viewLocation)\n\n return Rect(\n viewLocation[0] - viewPadding,\n viewLocation[1] - viewPadding,\n viewLocation[0] + screenshotView.width + viewPadding,\n viewLocation[1] + screenshotView.height + viewPadding\n )\n}\n\nthen we write a function to take a screenshot:\nfun takeScreenshot(\n activity: Activity,\n viewRect: Rect,\n onSuccess: (Bitmap) -> Unit\n) {\n val bitmap = Bitmap.createBitmap(viewRect.width(), viewRect.height(), Bitmap.Config.ARGB_8888)\n PixelCopy.request(activity.window, viewRect, bitmap, \n { copyResult ->\n if (copyResult == PixelCopy.SUCCESS) {\n onSuccess(bitmap)\n } else {\n error(\"problem with taking a screenshot\")\n }\n bitmap.recycle()\n },\n Handler(Looper.getMainLooper())\n )\n}\n\nthen you can call the function:\ntakeScreenshot(activity, activity.getViewRect()) { bitmap ->\n saveImageToFile(bitmap, \"myfilename.png\")\n}\n\n" ]
[ 0 ]
[]
[]
[ "android", "java" ]
stackoverflow_0070552323_android_java.txt
Q: SQL Select Minimum Value And Add Back To Table TABLE1 STUDENT SUBJECT DATE WANT 1 HISTORY 1/1/2020 11/3/2019 1 HISTORY 11/3/2019 11/3/2019 1 HISTORY 12/1/2021 11/3/2019 2 HISTORY 3/4/2019 3/4/2019 2 HISTORY 2/6/2021 3/4/2019 3 HISTORY 1/8/2022 1/8/2022 I Have TABLE1 which has STUDENT SUBJECT and DATE and I wish to add COLUMN, WANT which takes the MINIMUM(DATE) for each STUDENT. I can do: SELECT STUDENT, SUBJECT, MIN(DATE) AS WANT FROM TABLE1 GROUP BY STUDENT which gives me STUDENT MIN(DATE) 1 11/3/2019 2 3/4/2019 2 1/8/2022 but How I add it back to get the desire output? A: If you want to update your existing table, you could run the following UPDATE statement where you JOIN the source table with your SELECT query: UPDATE TABLE1 t1 JOIN ( SELECT STUDENT, SUBJECT, MIN(DATE) AS WANT FROM TABLE1 GROUP BY STUDENT ) t2 ON t1.STUDENT = t2.STUDENT SET t1.DATE = t2.WANT If instead you want to insert your query into a new table instead of updating, you could run the following query: INSERT INTO NEWTABLE SELECT STUDENT, SUBJECT, MIN(DATE) AS WANT FROM TABLE1 GROUP BY STUDENT Note NEWTABLE would need to be created first before running the above query. A: WITH YOUR_TABLE(STUDENT, SUBJECT, DATE) AS ( SELECT 1, 'HISTORY', '2020-01-01' UNION ALL SELECT 1, 'HISTORY', '2019-11-04'UNION ALL SELECT 1, 'HISTORY', '2021-12-01' UNION ALL SELECT 2, 'HISTORY', '2019-03-04' UNION ALL SELECT 2, 'HISTORY','2019-02-06' UNION ALL SELECT 3, 'HISTORY', '2022-01-08' ) SELECT T.STUDENT,T.SUBJECT,T.DATE, MIN(T.DATE)OVER(PARTITION BY T.STUDENT ORDER BY T.DATE ASC)AS WANT FROM YOUR_TABLE AS T I guess, you can use something like this. And please specify DATE always in ISO-format "YYYYMMDD" or "YYYY-MM-DD" A: You can use the window function with MIN statement. SELECT STUDENT, SUBJECT, DATE, MIN(DATE) OVER (PARTITION BY STUDENT) AS WANT FROM TABLE1
SQL Select Minimum Value And Add Back To Table
TABLE1 STUDENT SUBJECT DATE WANT 1 HISTORY 1/1/2020 11/3/2019 1 HISTORY 11/3/2019 11/3/2019 1 HISTORY 12/1/2021 11/3/2019 2 HISTORY 3/4/2019 3/4/2019 2 HISTORY 2/6/2021 3/4/2019 3 HISTORY 1/8/2022 1/8/2022 I Have TABLE1 which has STUDENT SUBJECT and DATE and I wish to add COLUMN, WANT which takes the MINIMUM(DATE) for each STUDENT. I can do: SELECT STUDENT, SUBJECT, MIN(DATE) AS WANT FROM TABLE1 GROUP BY STUDENT which gives me STUDENT MIN(DATE) 1 11/3/2019 2 3/4/2019 2 1/8/2022 but How I add it back to get the desire output?
[ "If you want to update your existing table, you could run the following UPDATE statement where you JOIN the source table with your SELECT query:\nUPDATE TABLE1 t1\nJOIN (\n SELECT STUDENT, SUBJECT, MIN(DATE) AS WANT\n FROM TABLE1\n GROUP BY STUDENT\n) t2\nON t1.STUDENT = t2.STUDENT\n\nSET t1.DATE = t2.WANT\n\nIf instead you want to insert your query into a new table instead of updating, you could run the following query:\nINSERT INTO NEWTABLE\nSELECT STUDENT, SUBJECT, MIN(DATE) AS WANT\nFROM TABLE1\nGROUP BY STUDENT\n\nNote NEWTABLE would need to be created first before running the above query.\n", "WITH YOUR_TABLE(STUDENT, SUBJECT, DATE) AS\n(\n SELECT 1, 'HISTORY', '2020-01-01' UNION ALL\n SELECT 1, 'HISTORY', '2019-11-04'UNION ALL\n SELECT 1, 'HISTORY', '2021-12-01' UNION ALL\n SELECT 2, 'HISTORY', '2019-03-04' UNION ALL \n SELECT 2, 'HISTORY','2019-02-06' UNION ALL \n SELECT 3, 'HISTORY', '2022-01-08' \n)\nSELECT T.STUDENT,T.SUBJECT,T.DATE,\n MIN(T.DATE)OVER(PARTITION BY T.STUDENT ORDER BY T.DATE ASC)AS WANT\n FROM YOUR_TABLE AS T\n\nI guess, you can use something like this. And please specify DATE always in ISO-format \"YYYYMMDD\" or \"YYYY-MM-DD\"\n", "You can use the window function with MIN statement.\nSELECT STUDENT, \n SUBJECT, \n DATE,\n MIN(DATE) OVER (PARTITION BY STUDENT) AS WANT\nFROM TABLE1\n\n" ]
[ 1, 0, 0 ]
[]
[]
[ "group_by", "min", "sql" ]
stackoverflow_0074678784_group_by_min_sql.txt
Q: Optimistic Updates with React-Query (TRPC) I am not sure how I would do optimistic updates with trpc? Is this "built-in" or do I have to use react-query's useQuery hook? So far, I am trying it like so, but it's not working: const queryClient = useQueryClient(); const updateWord = trpc.word.update.useMutation({ onMutate: async newTodo => { // Cancel any outgoing refetches (so they don't overwrite our optimistic update) await queryClient.cancelQueries({ queryKey: ['text', 'getOne'] }) // Snapshot the previous value const previousText = queryClient.getQueryData(['text', 'getOne']) // Optimistically update to the new value queryClient.setQueryData(['text', 'getOne'], old => old ? {...old, { title: "Hello" }} : undefined) // Return a context object with the snapshotted value return { previousText } }, //... Does this look like it should make sense? It's updating the value, but not optimistically. A: trpc v10 offers type-safe variants of most functions from the queryClient via their own useContext hook: const utils = trpc.useContext() then, you should be able to do: utils.text.getOne.cancel() utils.text.getOne.getData() utils.text.getOne.setData() see: https://trpc.io/docs/useContext
Optimistic Updates with React-Query (TRPC)
I am not sure how I would do optimistic updates with trpc? Is this "built-in" or do I have to use react-query's useQuery hook? So far, I am trying it like so, but it's not working: const queryClient = useQueryClient(); const updateWord = trpc.word.update.useMutation({ onMutate: async newTodo => { // Cancel any outgoing refetches (so they don't overwrite our optimistic update) await queryClient.cancelQueries({ queryKey: ['text', 'getOne'] }) // Snapshot the previous value const previousText = queryClient.getQueryData(['text', 'getOne']) // Optimistically update to the new value queryClient.setQueryData(['text', 'getOne'], old => old ? {...old, { title: "Hello" }} : undefined) // Return a context object with the snapshotted value return { previousText } }, //... Does this look like it should make sense? It's updating the value, but not optimistically.
[ "trpc v10 offers type-safe variants of most functions from the queryClient via their own useContext hook:\nconst utils = trpc.useContext()\n\nthen, you should be able to do:\nutils.text.getOne.cancel()\nutils.text.getOne.getData()\nutils.text.getOne.setData()\n\nsee: https://trpc.io/docs/useContext\n" ]
[ 1 ]
[]
[]
[ "javascript", "react_query", "reactjs", "trpc.io" ]
stackoverflow_0074671735_javascript_react_query_reactjs_trpc.io.txt
Q: PyQt5: How to install/run Qt Designer Feeling really stupid, right now, but the title says it all: How do you start the QtDesigner? I've installed PyQt5 via pip and I believe to have identified the directory it's been installed in as C:\Users\%username%\AppData\Local\Programs\Python\Python36\Lib\site-packages\PyQt5 Now what? There are a lot of .pyd files, some .dll's, too, but nothing executable (well, except a QtWebEngineProcess.exe in ...\site-packages\PyQt5\Qt\bin, but that doesn't sound like what I'm looking for. A: I struggled with this as well. The pyqt5-tools approach is cumbersome so I created a standalone installer for Qt Designer. It's only 40 MB. Maybe you will find it useful! A: If you are working in python virtual environment, in the command window >>qt5-tools designer can open designer window. A: The Qt designer is not installed with the pip installation. You can either download the full download from sourceforge (probably won't be the last pyqt release, and might be buggy on presence of another installation, like yours) or install it with another (unofficial) pypi package - pyqt5-tools (pip install pyqt5-tools), then run the designer from the following subpath of your python directory - ...\Python36\Lib\site-packages\pyqt5-tools\designer\designer.exe A: The latest PyQt5 wheels (which can be installed via pip) only contain what's necessary for running applications, and don't include the dev tools. This applies to PyQt versions 5.7 and later. For PyQt versions 5.6 and earlier, there are binary packages for Windows that also include the dev tools, and these are still available at sourceforge. The maintainer of PyQt does not plan on making any further releases of such binary packages, though - only the runtime wheels will now be made available, and there will be no official wheels for the dev tools. In light of this, someone has created an unofficial pyqt5-tools wheel (for Windows only). This appears to be in it's early stages, though, and so may not keep up with recent PyQt5 releases. This means that it may not always be possible to install it via pip. If that is the case, as a work-around, the wheel files can be treated as zip files and the contents extracted to a suitable location. This should then allow you to run the designer.exe file that is in the pyqt5-tools/designer folder. Finally, note that you will also see some zip and tar.gz files at sourceforge for PyQt5. These only contain the source code, though, so will be no use to you unless you intend to compile PyQt5 yourself. And just to be clear: compiling from source still would not give you all the Qt dev tools. If you go down that route, you would need to install the whole Qt development kit separately as well (which would then get you the dev tools). A: pip install pyqt5-tools Then restart the cmd, just type "designer" and press enter. A: If you cannot see the Designer , just look into this path "Lib\site-packages\qt5_applications\Qt\bin" for designer.exe and run it. A: pip install pyqt5-tools working in python 3.7.4 wont work in python 3.8.0 A: PyQt5 works after pip install PyQt5Designer A: You can also install Qt Designer the following way: Install latest Qt (I'm using 5.8) from Qt main site Make sure you include "Qt 5.8 MinGW" component Qt Designer will be installed in C:\Qt\5.8\mingw53_32\bin\designer.exe Note that the executable is named "designer.exe" A: Download the module using pip: pip install PyQt5Designer Then, for anaconda users, open: C:\ProgramData\AnacondaX\Lib\site-packages\QtDesigner\designer.exe For python users: 64-bit: C:\Program Files\PythonXX\Lib\site-packages\QtDesigner\designer.exe 32-bit: C:\Program Files (x86)\PythonXX\Lib\site-packages\QtDesigner\designer.exe A: For anyone stumbling across this post in 2021+ and finding the answers outdated: QT Designer is now in the qt5-applications package, under Qt\bin\. On Windows this means the default path, for CPython 3.9 using the Python.org installer, is %APPDATA%\Python\Python39\site-packages\qt5_applications\Qt\bin\designer.exe. A: Try using: pip install pyqt5-tools Now you'd find the designer in site-packages/pyqt5-tools. A: If you are installing the pyqt5-tools then you can find the designer.exe file inside: <python_installation>\Lib\site-packages\Qt If you cannot locate the file or have any issues opening this directly, then open a command prompt and type: <python_installation>\Scripts\pyqt5designer.exe A: For Qt Designer 6 this worked for me thanks for that protip from @Bhaskar pip install pyqt6-tools Then started: qt6-tools designer End up with nice working lightweight Qt Designer 6.0.1 version @ pip install pyqt6-tools Collecting pyqt6-tools Using cached pyqt6_tools-6.1.0.3.2-py3-none-any.whl (29 kB) Collecting pyqt6-plugins<6.1.0.3,>=6.1.0.2.2 Downloading pyqt6_plugins-6.1.0.2.2-cp39-cp39-manylinux2014_x86_64.whl (77 kB) |████████████████████████████████| 77 kB 492 kB/s Collecting python-dotenv Using cached python_dotenv-0.19.2-py2.py3-none-any.whl (17 kB) Collecting pyqt6==6.1.0 Downloading PyQt6-6.1.0-cp36.cp37.cp38.cp39-abi3-manylinux_2_28_x86_64.whl (6.8 MB) |████████████████████████████████| 6.8 MB 1.0 MB/s Requirement already satisfied: click in ./.pyenv/versions/3.9.6/lib/python3.9/site-packages (from pyqt6-tools) (8.0.1) Collecting PyQt6-sip<14,>=13.1 Downloading PyQt6_sip-13.2.0-cp39-cp39-manylinux1_x86_64.whl (307 kB) |████████████████████████████████| 307 kB 898 kB/s Collecting PyQt6-Qt6>=6.1.0 Using cached PyQt6_Qt6-6.2.2-py3-none-manylinux_2_28_x86_64.whl (50.0 MB) Collecting qt6-tools<6.1.0.2,>=6.1.0.1.2 Downloading qt6_tools-6.1.0.1.2-py3-none-any.whl (13 kB) Collecting click Downloading click-7.1.2-py2.py3-none-any.whl (82 kB) |████████████████████████████████| 82 kB 381 kB/s Collecting qt6-applications<6.1.0.3,>=6.1.0.2.2 Downloading qt6_applications-6.1.0.2.2-py3-none-manylinux2014_x86_64.whl (80.5 MB) |████████████████████████████████| 80.5 MB 245 kB/s Installing collected packages: qt6-applications, PyQt6-sip, PyQt6-Qt6, click, qt6-tools, pyqt6, python-dotenv, pyqt6-plugins, pyqt6-tools Attempting uninstall: click Found existing installation: click 8.0.1 Uninstalling click-8.0.1: Successfully uninstalled click-8.0.1 Successfully installed PyQt6-Qt6-6.2.2 PyQt6-sip-13.2.0 click-7.1.2 pyqt6-6.1.0 pyqt6-plugins-6.1.0.2.2 pyqt6-tools-6.1.0.3.2 python-dotenv-0.19.2 qt6-applications-6.1.0.2.2 qt6-tools-6.1.0.1.2 A: I was having the same problem, however I was able to install using the Pygame module installation code, changing some information: pygame: py -m pip install -U pygame --user PyQt5: py -m pip install -U pyqt5-tools --user A: you should find it here if your using anaconda C:\Users\%username%\anaconda3\envs\untitled\Lib\site-packages\qt5_applications\Qt\bin A: By far the easiest way to do this is to use this installer: https://build-system.fman.io/qt-designer-download It seems as though the other answers here are now out of date, not to mention confusing for someone who is just starting out with this. Sourceforge no longer has this package, I installed the tools as suggested but nothing appeared in the scripts folder, and none of the pip commands above worked either. A: In a Windows' terminal, activate your virtual env where you have installed PyQt5 then just type designer. You can create a shortcut by finding its path with where designer
PyQt5: How to install/run Qt Designer
Feeling really stupid, right now, but the title says it all: How do you start the QtDesigner? I've installed PyQt5 via pip and I believe to have identified the directory it's been installed in as C:\Users\%username%\AppData\Local\Programs\Python\Python36\Lib\site-packages\PyQt5 Now what? There are a lot of .pyd files, some .dll's, too, but nothing executable (well, except a QtWebEngineProcess.exe in ...\site-packages\PyQt5\Qt\bin, but that doesn't sound like what I'm looking for.
[ "I struggled with this as well. The pyqt5-tools approach is cumbersome so I created a standalone installer for Qt Designer. It's only 40 MB. Maybe you will find it useful!\n", "If you are working in python virtual environment, in the command window\n>>qt5-tools designer\n\ncan open designer window.\n", "The Qt designer is not installed with the pip installation.\nYou can either download the full download from sourceforge (probably won't be the last pyqt release, and might be buggy on presence of another installation, like yours) or install it with another (unofficial) pypi package - pyqt5-tools (pip install pyqt5-tools), then run the designer from the following subpath of your python directory - \n...\\Python36\\Lib\\site-packages\\pyqt5-tools\\designer\\designer.exe\n\n", "The latest PyQt5 wheels (which can be installed via pip) only contain what's necessary for running applications, and don't include the dev tools. This applies to PyQt versions 5.7 and later. For PyQt versions 5.6 and earlier, there are binary packages for Windows that also include the dev tools, and these are still available at sourceforge. The maintainer of PyQt does not plan on making any further releases of such binary packages, though - only the runtime wheels will now be made available, and there will be no official wheels for the dev tools.\nIn light of this, someone has created an unofficial pyqt5-tools wheel (for Windows only). This appears to be in it's early stages, though, and so may not keep up with recent PyQt5 releases. This means that it may not always be possible to install it via pip. If that is the case, as a work-around, the wheel files can be treated as zip files and the contents extracted to a suitable location. This should then allow you to run the designer.exe file that is in the pyqt5-tools/designer folder.\nFinally, note that you will also see some zip and tar.gz files at sourceforge for PyQt5. These only contain the source code, though, so will be no use to you unless you intend to compile PyQt5 yourself. And just to be clear: compiling from source still would not give you all the Qt dev tools. If you go down that route, you would need to install the whole Qt development kit separately as well (which would then get you the dev tools).\n", "pip install pyqt5-tools\n\nThen restart the cmd, just type \"designer\" and press enter.\n", "If you cannot see the Designer , just look into this path \"Lib\\site-packages\\qt5_applications\\Qt\\bin\" for designer.exe and run it.\n", "\npip install pyqt5-tools \n\nworking in python 3.7.4\nwont work in python 3.8.0 \n", "PyQt5 works after pip install PyQt5Designer\n", "You can also install Qt Designer the following way:\n\nInstall latest Qt (I'm using 5.8) from Qt main site\nMake sure you include \"Qt 5.8 MinGW\" component\nQt Designer will be installed in C:\\Qt\\5.8\\mingw53_32\\bin\\designer.exe\nNote that the executable is named \"designer.exe\"\n\n", "Download the module using pip:\npip install PyQt5Designer\n\nThen, for anaconda users, open:\nC:\\ProgramData\\AnacondaX\\Lib\\site-packages\\QtDesigner\\designer.exe\n\nFor python users:\n\n64-bit:\nC:\\Program Files\\PythonXX\\Lib\\site-packages\\QtDesigner\\designer.exe\n\n\n32-bit:\nC:\\Program Files (x86)\\PythonXX\\Lib\\site-packages\\QtDesigner\\designer.exe\n\n\n\n", "For anyone stumbling across this post in 2021+ and finding the answers outdated: QT Designer is now in the qt5-applications package, under Qt\\bin\\. On Windows this means the default path, for CPython 3.9 using the Python.org installer, is %APPDATA%\\Python\\Python39\\site-packages\\qt5_applications\\Qt\\bin\\designer.exe.\n", "Try using:\npip install pyqt5-tools\n\nNow you'd find the designer in site-packages/pyqt5-tools.\n", "If you are installing the pyqt5-tools then you can find the designer.exe file inside:\n<python_installation>\\Lib\\site-packages\\Qt\n\nIf you cannot locate the file or have any issues opening this directly, then open a command prompt and type:\n<python_installation>\\Scripts\\pyqt5designer.exe\n\n", "For Qt Designer 6 this worked for me thanks for that protip from @Bhaskar\npip install pyqt6-tools\n\nThen started:\nqt6-tools designer\n\nEnd up with nice working lightweight Qt Designer 6.0.1 version\n\n@ pip install pyqt6-tools\nCollecting pyqt6-tools\n Using cached pyqt6_tools-6.1.0.3.2-py3-none-any.whl (29 kB)\nCollecting pyqt6-plugins<6.1.0.3,>=6.1.0.2.2\n Downloading pyqt6_plugins-6.1.0.2.2-cp39-cp39-manylinux2014_x86_64.whl (77 kB)\n |████████████████████████████████| 77 kB 492 kB/s \nCollecting python-dotenv\n Using cached python_dotenv-0.19.2-py2.py3-none-any.whl (17 kB)\nCollecting pyqt6==6.1.0\n Downloading PyQt6-6.1.0-cp36.cp37.cp38.cp39-abi3-manylinux_2_28_x86_64.whl (6.8 MB)\n |████████████████████████████████| 6.8 MB 1.0 MB/s \nRequirement already satisfied: click in ./.pyenv/versions/3.9.6/lib/python3.9/site-packages (from pyqt6-tools) (8.0.1)\nCollecting PyQt6-sip<14,>=13.1\n Downloading PyQt6_sip-13.2.0-cp39-cp39-manylinux1_x86_64.whl (307 kB)\n |████████████████████████████████| 307 kB 898 kB/s \nCollecting PyQt6-Qt6>=6.1.0\n Using cached PyQt6_Qt6-6.2.2-py3-none-manylinux_2_28_x86_64.whl (50.0 MB)\nCollecting qt6-tools<6.1.0.2,>=6.1.0.1.2\n Downloading qt6_tools-6.1.0.1.2-py3-none-any.whl (13 kB)\nCollecting click\n Downloading click-7.1.2-py2.py3-none-any.whl (82 kB)\n |████████████████████████████████| 82 kB 381 kB/s \nCollecting qt6-applications<6.1.0.3,>=6.1.0.2.2\n Downloading qt6_applications-6.1.0.2.2-py3-none-manylinux2014_x86_64.whl (80.5 MB)\n |████████████████████████████████| 80.5 MB 245 kB/s \nInstalling collected packages: qt6-applications, PyQt6-sip, PyQt6-Qt6, click, qt6-tools, pyqt6, python-dotenv, pyqt6-plugins, pyqt6-tools\n Attempting uninstall: click\n Found existing installation: click 8.0.1\n Uninstalling click-8.0.1:\n Successfully uninstalled click-8.0.1\nSuccessfully installed PyQt6-Qt6-6.2.2 PyQt6-sip-13.2.0 click-7.1.2 pyqt6-6.1.0 pyqt6-plugins-6.1.0.2.2 pyqt6-tools-6.1.0.3.2 python-dotenv-0.19.2 qt6-applications-6.1.0.2.2 qt6-tools-6.1.0.1.2\n\n\n", "I was having the same problem, however I was able to install using the Pygame module installation code, changing some information:\npygame:\npy -m pip install -U pygame --user\n\nPyQt5:\npy -m pip install -U pyqt5-tools --user\n\n", "you should find it here if your using anaconda\nC:\\Users\\%username%\\anaconda3\\envs\\untitled\\Lib\\site-packages\\qt5_applications\\Qt\\bin\n\n", "By far the easiest way to do this is to use this installer:\nhttps://build-system.fman.io/qt-designer-download\nIt seems as though the other answers here are now out of date, not to mention confusing for someone who is just starting out with this. Sourceforge no longer has this package, I installed the tools as suggested but nothing appeared in the scripts folder, and none of the pip commands above worked either.\n", "In a Windows' terminal, activate your virtual env where you have installed PyQt5 then just type designer.\nYou can create a shortcut by finding its path with where designer\n" ]
[ 36, 32, 22, 20, 19, 7, 5, 5, 4, 4, 4, 2, 2, 2, 0, 0, 0, 0 ]
[]
[]
[ "pyqt5", "python", "qt", "qt_designer" ]
stackoverflow_0042090739_pyqt5_python_qt_qt_designer.txt
Q: How do you create a workflow in which you calculate the prevalences for topics (LDA)? lda_dtm <- cast_dtm(data = gruppierte_texte, document = "id", term = "lemma", #in der Zeile stehen die Tokens value = "anzahl") Themen <- seq(5,50,5) for(k in Themen){ print(paste("aktuell bei Thema:", k)) set.seed (42) # Zufall steuern, Startpunkt einstellen, immer gleiche Ergebnisse res <- LDA(x = lda_dtm, k = k) # es geht um die häufigsten Themen # res steht für results praevalenzen_mit_metadaten <- make.dt(res, meta = corpus$meta) praevalenzen_mit_metadaten <- as_tibble(praevalenzen_mit_metadaten) %>% rename_all(~sub("Topic","Topic_",.)) %>% gather("Topic", "praevalenz", starts_with("Topic")) %>% mutate(K = k) %>% select(K, Topic, praevalenz, artist, title, record.name, lyrics, year) } This is my script, in which I want to make a LDA for a dataframe with german songs. I want to calculate the prevalence of themes within the texts across all models. But I got this Error: Error in model$theta : $ operator not defined for this S4 class Can anybody help? A: Since you don't provide your data, I will use the example data included in the topicmodels package. The function topics returns the most probable topic for each document, so you just need to put them in a table. library(topicmodels) data("AssociatedPress", package = "topicmodels") lda <- LDA(AssociatedPress[1:40,], control = list(alpha = 0.1), k = 3) table(topics(lda)) 1 2 3 15 13 12
How do you create a workflow in which you calculate the prevalences for topics (LDA)?
lda_dtm <- cast_dtm(data = gruppierte_texte, document = "id", term = "lemma", #in der Zeile stehen die Tokens value = "anzahl") Themen <- seq(5,50,5) for(k in Themen){ print(paste("aktuell bei Thema:", k)) set.seed (42) # Zufall steuern, Startpunkt einstellen, immer gleiche Ergebnisse res <- LDA(x = lda_dtm, k = k) # es geht um die häufigsten Themen # res steht für results praevalenzen_mit_metadaten <- make.dt(res, meta = corpus$meta) praevalenzen_mit_metadaten <- as_tibble(praevalenzen_mit_metadaten) %>% rename_all(~sub("Topic","Topic_",.)) %>% gather("Topic", "praevalenz", starts_with("Topic")) %>% mutate(K = k) %>% select(K, Topic, praevalenz, artist, title, record.name, lyrics, year) } This is my script, in which I want to make a LDA for a dataframe with german songs. I want to calculate the prevalence of themes within the texts across all models. But I got this Error: Error in model$theta : $ operator not defined for this S4 class Can anybody help?
[ "Since you don't provide your data, I will use the example data included in the topicmodels package. The function topics returns the most probable topic for each document, so you just need to put them in a table.\nlibrary(topicmodels)\n\ndata(\"AssociatedPress\", package = \"topicmodels\")\nlda <- LDA(AssociatedPress[1:40,], control = list(alpha = 0.1), k = 3)\n\ntable(topics(lda))\n\n 1 2 3 \n15 13 12 \n\n" ]
[ 0 ]
[]
[]
[ "lda", "r" ]
stackoverflow_0074678304_lda_r.txt
Q: Best way to ask for data from server React Native I have a react native application that needs to display the same info from the server almost in real time when there is a change. How I'm doing it now: I created a setInterval() with a fetch inside that runs every 10 seconds. The problem is that sometimes there is no change in the server for hours and the app keep asking the serve for info that its already there creating a lot of unnecessary traffic. Is there any way to do the other way around? Like, the serve asks the react native app to check for updates? What would be a better solution? A: There are a few ways you can improve your current approach to get real-time updates from the server in your React Native app. One way is to use a technology called websockets, which allows for full-duplex communication between the server and the client. With websockets, the server can push data to the client in real time, without the need for the client to continually poll the server for updates. This can reduce the amount of unnecessary traffic and improve the responsiveness of your app. Another way to get real-time updates from the server is to use a technology called long polling. With long polling, the client sends a request to the server, but the server holds the request open until there is new data to send back to the client. Once new data is available, the server sends a response to the client and the client immediately sends another request to the server. This process continues until the client no longer needs updates, at which point the client can cancel the long polling request. You can also consider using a third-party service that specializes in real-time data synchronization, such as Firebase or Pusher. These services provide APIs that you can use in your React Native app to get real-time updates from the server without having to implement websockets or long polling yourself. Overall, there is no one-size-fits-all solution for getting real-time updates from the server in a React Native app, so you will need to choose the approach that best fits your specific needs.
Best way to ask for data from server React Native
I have a react native application that needs to display the same info from the server almost in real time when there is a change. How I'm doing it now: I created a setInterval() with a fetch inside that runs every 10 seconds. The problem is that sometimes there is no change in the server for hours and the app keep asking the serve for info that its already there creating a lot of unnecessary traffic. Is there any way to do the other way around? Like, the serve asks the react native app to check for updates? What would be a better solution?
[ "There are a few ways you can improve your current approach to get real-time updates from the server in your React Native app. One way is to use a technology called websockets, which allows for full-duplex communication between the server and the client. With websockets, the server can push data to the client in real time, without the need for the client to continually poll the server for updates. This can reduce the amount of unnecessary traffic and improve the responsiveness of your app.\nAnother way to get real-time updates from the server is to use a technology called long polling. With long polling, the client sends a request to the server, but the server holds the request open until there is new data to send back to the client. Once new data is available, the server sends a response to the client and the client immediately sends another request to the server. This process continues until the client no longer needs updates, at which point the client can cancel the long polling request.\nYou can also consider using a third-party service that specializes in real-time data synchronization, such as Firebase or Pusher. These services provide APIs that you can use in your React Native app to get real-time updates from the server without having to implement websockets or long polling yourself.\nOverall, there is no one-size-fits-all solution for getting real-time updates from the server in a React Native app, so you will need to choose the approach that best fits your specific needs.\n" ]
[ 5 ]
[]
[]
[ "fetch", "react_native", "server", "setinterval" ]
stackoverflow_0074678959_fetch_react_native_server_setinterval.txt
Q: How to install Delphi 4 Python ? ImportError: DLL load failed while importing DelphiVCL: The specified module could not be found I tried to follow the steps as per embarcadero tutorial like that: pip install delphivcl Collecting delphivcl Using cached delphivcl-0.1.24-cp311-cp311-win_amd64.whl Installing collected packages: delphivcl Successfully installed delphivcl-0.1.24 Python 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from delphivcl import * Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Program Files\Python311\Lib\site-packages\delphivcl\__init__.py", line 22, in <module> package = new_import() ^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\delphivcl\__init__.py", line 15, in new_import ld = loader.create_module(spec) ^^^^^^^^^^^^^^^^^^^^^^^^^^ ImportError: DLL load failed while importing DelphiVCL: The specified module could not be found. What is the problem ? A: Python 3.11.0 not supported last one supported as of this date is Python 3.10.8
How to install Delphi 4 Python ? ImportError: DLL load failed while importing DelphiVCL: The specified module could not be found
I tried to follow the steps as per embarcadero tutorial like that: pip install delphivcl Collecting delphivcl Using cached delphivcl-0.1.24-cp311-cp311-win_amd64.whl Installing collected packages: delphivcl Successfully installed delphivcl-0.1.24 Python 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from delphivcl import * Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Program Files\Python311\Lib\site-packages\delphivcl\__init__.py", line 22, in <module> package = new_import() ^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\delphivcl\__init__.py", line 15, in new_import ld = loader.create_module(spec) ^^^^^^^^^^^^^^^^^^^^^^^^^^ ImportError: DLL load failed while importing DelphiVCL: The specified module could not be found. What is the problem ?
[ "Python 3.11.0 not supported last one supported as of this date is Python 3.10.8\n" ]
[ 0 ]
[]
[]
[ "delphi" ]
stackoverflow_0074671881_delphi.txt
Q: Selenium (Python) (Firefox) is unable to write Firefox profile. Permission denied (os error 13) When I run my Python code using Selenium to open (and scrape) a website, using a profile parameter, I get the following error message: selenium.common.exceptions.SessionNotCreatedException: Message: Failed to set preferences: Unable to write Firefox profile: Permission denied (os error 13) I use the following code: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time from selenium.webdriver.firefox.options import Options from datetime import datetime f = open("/home/username/Documents/AH/log2.txt", "a") f.write('gestart') f.close() # I use the below code when I use crontab, read below.. #from pyvirtualdisplay import Display #display = Display(visible=0, size=(2880, 1800)).start() website = "https://www.ah.nl/" options=Options() options.add_argument('-profile') options.add_argument(r'/home/username/.mozilla/firefox/n2n9yy4r.default-release') driver = webdriver.Firefox(options=options, service_log_path="/home/username/geckodriver.log") driver.implicitly_wait(20) driver.get(website) tijd = WebDriverWait(driver,40).until(EC.presence_of_element_located((By.XPATH,"//*[@id='navigation-header']/div[1]/div[1]/div/div/p/a"))) tijdbezorging = tijd.text driver.close() driver.quit() f = open("/home/username/Documents/AH/testlog.txt", "a") f.write(tijdbezorging) f.close() The full error message when I run this code using python3 filenamecode.py: SendAHStatus.py:46: DeprecationWarning: service_log_path has been deprecated, please pass in a Service object driver = webdriver.Firefox(options=options, service_log_path="/home/username/geckodriver.log") /usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.12) or chardet (3.0.4) doesn't match a supported version! warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported " Traceback (most recent call last): File "SendAHStatus.py", line 46, in <module> driver = webdriver.Firefox(options=options, service_log_path="/home/username/geckodriver.log") File "/usr/local/lib/python3.8/dist-packages/selenium/webdriver/firefox/webdriver.py", line 197, in __init__ super().__init__(command_executor=executor, options=options, keep_alive=True) File "/usr/local/lib/python3.8/dist-packages/selenium/webdriver/remote/webdriver.py", line 288, in __init__ self.start_session(capabilities, browser_profile) File "/usr/local/lib/python3.8/dist-packages/selenium/webdriver/remote/webdriver.py", line 381, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/local/lib/python3.8/dist-packages/selenium/webdriver/remote/webdriver.py", line 444, in execute self.error_handler.check_response(response) File "/usr/local/lib/python3.8/dist-packages/selenium/webdriver/remote/errorhandler.py", line 249, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.SessionNotCreatedException: Message: Failed to set preferences: Unable to write Firefox profile: Permission denied (os error 13) The code DOES work when I schedule it using sudo crontab -e. Yes, using sudo. See code below: SHELL=/bin/bash PATH=/usr/local/bin/:usr/bin: and some paths 01 01 * * * python3 myscriptname.py And, the code also works (via my command line) without the profile parameter. I also tried using a different profile path like, /home/username/profiledir. This also works via sudo crontab, but not via my regular command line. Btw, I uncomment the virtual display when using cron. I could run my code using sudo python3 myscript.py. But then I get this message: Running Firefox as root in a regular user's session is not supported. ($XAUTHORITY is /home/username/.Xauthority which is owned by username.) When changing ownership of XAUTHORITY to root, I can run my script, but I don't want to go down that path. What I can derive from all of this: The webdriver is working, Its a permission issue since the code runs using elevated permission, using cron. Please help me with this, its getting frustrating. My environment: Selenium 4.6.0 Python 3.8 Firefox 107.0 Ubuntu 20.04.5 LTS Your help is much appreciated! A: This error message is telling you that your Python script is unable to write to the Firefox profile that you specified. This could be because the permissions on the profile directory are not set correctly, or because your script is running as a different user than the one who owns the Firefox profile. One way to fix this would be to make sure that your script has the correct permissions to write to the Firefox profile directory. You can do this by changing the ownership of the profile directory to the user that your script is running as, or by changing the permissions on the directory to allow writing by other users. Another option would be to specify the path to a different Firefox profile that your script has permission to write to, or to create a new Firefox profile and use that instead. You may also want to update your code to handle this error more gracefully, by catching the SessionNotCreatedException and either retrying the operation or handling the error in some other way. Here is an example of how you could modify your code to handle this error: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time from selenium.webdriver.firefox.options import Options from datetime import datetime from selenium.common.exceptions import SessionNotCreatedException # Open the log file for writing f = open("/home/username/Documents/AH/log2.txt", "a") f.write('gestart') f.close() # Set the URL of the website to scrape website = "https://www.ah.nl/" # Create the Firefox options object options = Options() # Set the Firefox profile to use options.add_argument('-profile') options.add_argument(r'/home/username/.mozilla/firefox/n2n9yy4r.default-release') # Try to create a new Firefox session using the specified options try: # Create a new Firefox webdriver driver = webdriver.Firefox(options=options, service_log_path="/home/username/geckodriver.log") # Set the implicit wait timeout to 20 seconds driver.implicitly_wait(20) # Navigate to the website driver.get(website) # Wait for the element with the specified XPath to be present on the page tijd = WebDriverWait(driver,40).until(EC.presence_of_element_located((By.XPATH,"//*[@id='navigation-header']/div[1]/div[1]/div/div/p/a"))) # Get the text of the element tijdbezorging = tijd.text except SessionNotCreatedException: # Handle the error by retrying the operation or logging the error # You could also try using a different Firefox profile or creating a new one print("Failed to create Firefox session. Retrying...") # Retry the operation here finally: # Close the Firefox session driver.close() driver.quit() # Open the log file for writing f = open("/home/username/Documents/AH/testlog.txt", "a") # Write the element text to the log file f.write(tijdbezorging) # Close the log file f.close() In this example, the code is enclosed in a try block, and the SessionNotCreatedException is caught in the except block. You can then handle the error by retrying the operation or logging the error, and then close the Firefox session and write to the log file in the finally block.
Selenium (Python) (Firefox) is unable to write Firefox profile. Permission denied (os error 13)
When I run my Python code using Selenium to open (and scrape) a website, using a profile parameter, I get the following error message: selenium.common.exceptions.SessionNotCreatedException: Message: Failed to set preferences: Unable to write Firefox profile: Permission denied (os error 13) I use the following code: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time from selenium.webdriver.firefox.options import Options from datetime import datetime f = open("/home/username/Documents/AH/log2.txt", "a") f.write('gestart') f.close() # I use the below code when I use crontab, read below.. #from pyvirtualdisplay import Display #display = Display(visible=0, size=(2880, 1800)).start() website = "https://www.ah.nl/" options=Options() options.add_argument('-profile') options.add_argument(r'/home/username/.mozilla/firefox/n2n9yy4r.default-release') driver = webdriver.Firefox(options=options, service_log_path="/home/username/geckodriver.log") driver.implicitly_wait(20) driver.get(website) tijd = WebDriverWait(driver,40).until(EC.presence_of_element_located((By.XPATH,"//*[@id='navigation-header']/div[1]/div[1]/div/div/p/a"))) tijdbezorging = tijd.text driver.close() driver.quit() f = open("/home/username/Documents/AH/testlog.txt", "a") f.write(tijdbezorging) f.close() The full error message when I run this code using python3 filenamecode.py: SendAHStatus.py:46: DeprecationWarning: service_log_path has been deprecated, please pass in a Service object driver = webdriver.Firefox(options=options, service_log_path="/home/username/geckodriver.log") /usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.12) or chardet (3.0.4) doesn't match a supported version! warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported " Traceback (most recent call last): File "SendAHStatus.py", line 46, in <module> driver = webdriver.Firefox(options=options, service_log_path="/home/username/geckodriver.log") File "/usr/local/lib/python3.8/dist-packages/selenium/webdriver/firefox/webdriver.py", line 197, in __init__ super().__init__(command_executor=executor, options=options, keep_alive=True) File "/usr/local/lib/python3.8/dist-packages/selenium/webdriver/remote/webdriver.py", line 288, in __init__ self.start_session(capabilities, browser_profile) File "/usr/local/lib/python3.8/dist-packages/selenium/webdriver/remote/webdriver.py", line 381, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/local/lib/python3.8/dist-packages/selenium/webdriver/remote/webdriver.py", line 444, in execute self.error_handler.check_response(response) File "/usr/local/lib/python3.8/dist-packages/selenium/webdriver/remote/errorhandler.py", line 249, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.SessionNotCreatedException: Message: Failed to set preferences: Unable to write Firefox profile: Permission denied (os error 13) The code DOES work when I schedule it using sudo crontab -e. Yes, using sudo. See code below: SHELL=/bin/bash PATH=/usr/local/bin/:usr/bin: and some paths 01 01 * * * python3 myscriptname.py And, the code also works (via my command line) without the profile parameter. I also tried using a different profile path like, /home/username/profiledir. This also works via sudo crontab, but not via my regular command line. Btw, I uncomment the virtual display when using cron. I could run my code using sudo python3 myscript.py. But then I get this message: Running Firefox as root in a regular user's session is not supported. ($XAUTHORITY is /home/username/.Xauthority which is owned by username.) When changing ownership of XAUTHORITY to root, I can run my script, but I don't want to go down that path. What I can derive from all of this: The webdriver is working, Its a permission issue since the code runs using elevated permission, using cron. Please help me with this, its getting frustrating. My environment: Selenium 4.6.0 Python 3.8 Firefox 107.0 Ubuntu 20.04.5 LTS Your help is much appreciated!
[ "This error message is telling you that your Python script is unable to write to the Firefox profile that you specified. This could be because the permissions on the profile directory are not set correctly, or because your script is running as a different user than the one who owns the Firefox profile.\nOne way to fix this would be to make sure that your script has the correct permissions to write to the Firefox profile directory. You can do this by changing the ownership of the profile directory to the user that your script is running as, or by changing the permissions on the directory to allow writing by other users.\nAnother option would be to specify the path to a different Firefox profile that your script has permission to write to, or to create a new Firefox profile and use that instead.\nYou may also want to update your code to handle this error more gracefully, by catching the SessionNotCreatedException and either retrying the operation or handling the error in some other way.\nHere is an example of how you could modify your code to handle this error:\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\nfrom selenium.webdriver.firefox.options import Options\nfrom datetime import datetime\nfrom selenium.common.exceptions import SessionNotCreatedException\n\n# Open the log file for writing\nf = open(\"/home/username/Documents/AH/log2.txt\", \"a\")\nf.write('gestart')\nf.close()\n\n# Set the URL of the website to scrape\nwebsite = \"https://www.ah.nl/\"\n\n# Create the Firefox options object\noptions = Options()\n# Set the Firefox profile to use\noptions.add_argument('-profile')\noptions.add_argument(r'/home/username/.mozilla/firefox/n2n9yy4r.default-release') \n\n# Try to create a new Firefox session using the specified options\ntry:\n # Create a new Firefox webdriver\n driver = webdriver.Firefox(options=options, service_log_path=\"/home/username/geckodriver.log\")\n # Set the implicit wait timeout to 20 seconds\n driver.implicitly_wait(20)\n # Navigate to the website\n driver.get(website)\n\n # Wait for the element with the specified XPath to be present on the page\n tijd = WebDriverWait(driver,40).until(EC.presence_of_element_located((By.XPATH,\"//*[@id='navigation-header']/div[1]/div[1]/div/div/p/a\")))\n # Get the text of the element\n tijdbezorging = tijd.text\nexcept SessionNotCreatedException:\n # Handle the error by retrying the operation or logging the error\n # You could also try using a different Firefox profile or creating a new one\n print(\"Failed to create Firefox session. Retrying...\")\n # Retry the operation here\nfinally:\n # Close the Firefox session\n driver.close()\n driver.quit()\n\n # Open the log file for writing\n f = open(\"/home/username/Documents/AH/testlog.txt\", \"a\")\n # Write the element text to the log file\n f.write(tijdbezorging)\n # Close the log file\n f.close()\n\nIn this example, the code is enclosed in a try block, and the SessionNotCreatedException is caught in the except block. You can then handle the error by retrying the operation or logging the error, and then close the Firefox session and write to the log file in the finally block.\n" ]
[ 0 ]
[]
[]
[ "firefox", "linux", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074651572_firefox_linux_python_selenium_selenium_webdriver.txt
Q: AttributeErrors: undesired interaction between @property and __getattr__ I have a problem with AttributeErrors raised in a @property in combination with __getattr__() in python: Example code: >>> def deeply_nested_factory_fn(): ... a = 2 ... return a.invalid_attr ... >>> class Test(object): ... def __getattr__(self, name): ... if name == 'abc': ... return 'abc' ... raise AttributeError("'Test' object has no attribute '%s'" % name) ... @property ... def my_prop(self): ... return deeply_nested_factory_fn() ... >>> test = Test() >>> test.my_prop Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in __getattr__ AttributeError: 'Test' object has no attribute 'my_prop' In my case, this is a highly misleading error message, because it hides the fact that deeply_nested_factory_fn() has a mistake. Based on the idea in Tadhg McDonald-Jensen's answer, my currently best solution is the following. Any hints on how to get rid of the __main__. prefix to AttributeError and the reference to attributeErrorCatcher in the traceback would be much appreciated. >>> def catchAttributeErrors(func): ... AttributeError_org = AttributeError ... def attributeErrorCatcher(*args, **kwargs): ... try: ... return func(*args, **kwargs) ... except AttributeError_org as e: ... import sys ... class AttributeError(Exception): ... pass ... etype, value, tb = sys.exc_info() ... raise AttributeError(e).with_traceback(tb.tb_next) from None ... return attributeErrorCatcher ... >>> def deeply_nested_factory_fn(): ... a = 2 ... return a.invalid_attr ... >>> class Test(object): ... def __getattr__(self, name): ... if name == 'abc': ... # computing come other attributes ... return 'abc' ... raise AttributeError("'Test' object has no attribute '%s'" % name) ... @property ... @catchAttributeErrors ... def my_prop(self): ... return deeply_nested_factory_fn() ... >>> class Test1(object): ... def __init__(self): ... test = Test() ... test.my_prop ... >>> test1 = Test1() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 4, in __init__ File "<stdin>", line 11, in attributeErrorCatcher File "<stdin>", line 10, in my_prop File "<stdin>", line 3, in deeply_nested_factory_fn __main__.AttributeError: 'int' object has no attribute 'invalid_attr' A: If you're willing to exclusively use new-style classes, you could overload __getattribute__ instead of __getattr__: class Test(object): def __getattribute__(self, name): if name == 'abc': return 'abc' else: return object.__getattribute__(self, name) @property def my_prop(self): return deeply_nested_factory_fn() Now your stack trace will properly mention deeply_nested_factory_fn. Traceback (most recent call last): File "C:\python\myprogram.py", line 16, in <module> test.my_prop File "C:\python\myprogram.py", line 10, in __getattribute__ return object.__getattribute__(self, name) File "C:\python\myprogram.py", line 13, in my_prop return deeply_nested_factory_fn() File "C:\python\myprogram.py", line 3, in deeply_nested_factory_fn return a.invalid_attr AttributeError: 'int' object has no attribute 'invalid_attr' A: You can create a custom Exception that appears to be an AttributeError but will not trigger __getattr__ since it is not actually an AttributeError. UPDATED: the traceback message is greatly improved by reassigning the .__traceback__ attribute before re-raising the error: class AttributeError_alt(Exception): @classmethod def wrapper(err_type, f): """wraps a function to reraise an AttributeError as the alternate type""" @functools.wraps(f) def alt_AttrError_wrapper(*args,**kw): try: return f(*args,**kw) except AttributeError as e: new_err = err_type(e) new_err.__traceback__ = e.__traceback__.tb_next raise new_err from None return alt_AttrError_wrapper Then when you define your property as: @property @AttributeError_alt.wrapper def my_prop(self): return deeply_nested_factory_fn() and the error message you will get will look like this: Traceback (most recent call last): File ".../test.py", line 34, in <module> test.my_prop File ".../test.py", line 14, in alt_AttrError_wrapper raise new_err from None File ".../test.py", line 30, in my_prop return deeply_nested_factory_fn() File ".../test.py", line 20, in deeply_nested_factory_fn return a.invalid_attr AttributeError_alt: 'int' object has no attribute 'invalid_attr' notice there is a line for raise new_err from None but it is above the lines from within the property call. There would also be a line for return f(*args,**kw) but that is omitted with .tb_next. I am fairly sure the best solution to your problem has already been suggested and you can see the previous revision of my answer for why I think it is the best option. Although honestly if there is an error that is incorrectly being suppressed then raise a bloody RuntimeError chained to the one that would be hidden otherwise: def assert_no_AttributeError(f): @functools.wraps(f) def assert_no_AttrError_wrapper(*args,**kw): try: return f(*args,**kw) except AttributeError as e: e.__traceback__ = e.__traceback__.tb_next raise RuntimeError("AttributeError was incorrectly raised") from e return assert_no_AttrError_wrapper then if you decorate your property with this you will get an error like this: Traceback (most recent call last): File ".../test.py", line 27, in my_prop return deeply_nested_factory_fn() File ".../test.py", line 17, in deeply_nested_factory_fn return a.invalid_attr AttributeError: 'int' object has no attribute 'invalid_attr' The above exception was the direct cause of the following exception: Traceback (most recent call last): File ".../test.py", line 32, in <module> x.my_prop File ".../test.py", line 11, in assert_no_AttrError_wrapper raise RuntimeError("AttributeError was incorrectly raised") from e RuntimeError: AttributeError was incorrectly raised Although if you expect more then just one thing to raise an AttributeError then you might want to just overload __getattribute__ to check for any peculiar error for all lookups: def __getattribute__(self,attr): try: return object.__getattribute__(self,attr) except AttributeError as e: if str(e) == "{0.__class__.__name__!r} object has no attribute {1!r}".format(self,attr): raise #normal case of "attribute not found" else: #if the error message was anything else then it *causes* a RuntimeError raise RuntimeError("Unexpected AttributeError") from e This way when something goes wrong that you are not expecting you will know it right away! A: Just in case others find this: the problem with the example on top is that an AttributeError is raised inside __getattr__. Instead, one should call self.__getattribute__(attr) to let that raise. Example def deeply_nested_factory_fn(): a = 2 return a.invalid_attr class Test(object): def __getattr__(self, name): if name == 'abc': return 'abc' return self.__getattribute__(name) @property def my_prop(self): return deeply_nested_factory_fn() test = Test() test.my_prop This yields AttributeError Traceback (most recent call last) Cell In [1], line 15 12 return deeply_nested_factory_fn() 14 test = Test() ---> 15 test.my_prop Cell In [1], line 9, in Test.__getattr__(self, name) 7 if name == 'abc': 8 return 'abc' ----> 9 return self.__getattribute__(name) Cell In [1], line 12, in Test.my_prop(self) 10 @property 11 def my_prop(self): ---> 12 return deeply_nested_factory_fn() Cell In [1], line 3, in deeply_nested_factory_fn() 1 def deeply_nested_factory_fn(): 2 a = 2 ----> 3 return a.invalid_attr AttributeError: 'int' object has no attribute 'invalid_attr'
AttributeErrors: undesired interaction between @property and __getattr__
I have a problem with AttributeErrors raised in a @property in combination with __getattr__() in python: Example code: >>> def deeply_nested_factory_fn(): ... a = 2 ... return a.invalid_attr ... >>> class Test(object): ... def __getattr__(self, name): ... if name == 'abc': ... return 'abc' ... raise AttributeError("'Test' object has no attribute '%s'" % name) ... @property ... def my_prop(self): ... return deeply_nested_factory_fn() ... >>> test = Test() >>> test.my_prop Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in __getattr__ AttributeError: 'Test' object has no attribute 'my_prop' In my case, this is a highly misleading error message, because it hides the fact that deeply_nested_factory_fn() has a mistake. Based on the idea in Tadhg McDonald-Jensen's answer, my currently best solution is the following. Any hints on how to get rid of the __main__. prefix to AttributeError and the reference to attributeErrorCatcher in the traceback would be much appreciated. >>> def catchAttributeErrors(func): ... AttributeError_org = AttributeError ... def attributeErrorCatcher(*args, **kwargs): ... try: ... return func(*args, **kwargs) ... except AttributeError_org as e: ... import sys ... class AttributeError(Exception): ... pass ... etype, value, tb = sys.exc_info() ... raise AttributeError(e).with_traceback(tb.tb_next) from None ... return attributeErrorCatcher ... >>> def deeply_nested_factory_fn(): ... a = 2 ... return a.invalid_attr ... >>> class Test(object): ... def __getattr__(self, name): ... if name == 'abc': ... # computing come other attributes ... return 'abc' ... raise AttributeError("'Test' object has no attribute '%s'" % name) ... @property ... @catchAttributeErrors ... def my_prop(self): ... return deeply_nested_factory_fn() ... >>> class Test1(object): ... def __init__(self): ... test = Test() ... test.my_prop ... >>> test1 = Test1() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 4, in __init__ File "<stdin>", line 11, in attributeErrorCatcher File "<stdin>", line 10, in my_prop File "<stdin>", line 3, in deeply_nested_factory_fn __main__.AttributeError: 'int' object has no attribute 'invalid_attr'
[ "If you're willing to exclusively use new-style classes, you could overload __getattribute__ instead of __getattr__:\nclass Test(object):\n def __getattribute__(self, name):\n if name == 'abc':\n return 'abc'\n else:\n return object.__getattribute__(self, name)\n @property\n def my_prop(self):\n return deeply_nested_factory_fn()\n\nNow your stack trace will properly mention deeply_nested_factory_fn.\nTraceback (most recent call last):\n File \"C:\\python\\myprogram.py\", line 16, in <module>\n test.my_prop\n File \"C:\\python\\myprogram.py\", line 10, in __getattribute__\n return object.__getattribute__(self, name)\n File \"C:\\python\\myprogram.py\", line 13, in my_prop\n return deeply_nested_factory_fn()\n File \"C:\\python\\myprogram.py\", line 3, in deeply_nested_factory_fn\n return a.invalid_attr\nAttributeError: 'int' object has no attribute 'invalid_attr'\n\n", "You can create a custom Exception that appears to be an AttributeError but will not trigger __getattr__ since it is not actually an AttributeError.\nUPDATED: the traceback message is greatly improved by reassigning the .__traceback__ attribute before re-raising the error:\nclass AttributeError_alt(Exception):\n @classmethod\n def wrapper(err_type, f):\n \"\"\"wraps a function to reraise an AttributeError as the alternate type\"\"\"\n @functools.wraps(f)\n def alt_AttrError_wrapper(*args,**kw):\n try:\n return f(*args,**kw)\n except AttributeError as e:\n new_err = err_type(e)\n new_err.__traceback__ = e.__traceback__.tb_next\n raise new_err from None\n return alt_AttrError_wrapper\n\nThen when you define your property as:\n@property\n@AttributeError_alt.wrapper\ndef my_prop(self):\n return deeply_nested_factory_fn()\n\nand the error message you will get will look like this:\nTraceback (most recent call last):\n File \".../test.py\", line 34, in <module>\n test.my_prop\n File \".../test.py\", line 14, in alt_AttrError_wrapper\n raise new_err from None\n File \".../test.py\", line 30, in my_prop\n return deeply_nested_factory_fn()\n File \".../test.py\", line 20, in deeply_nested_factory_fn\n return a.invalid_attr\nAttributeError_alt: 'int' object has no attribute 'invalid_attr'\n\nnotice there is a line for raise new_err from None but it is above the lines from within the property call. There would also be a line for return f(*args,**kw) but that is omitted with .tb_next.\n\nI am fairly sure the best solution to your problem has already been suggested and you can see the previous revision of my answer for why I think it is the best option. Although honestly if there is an error that is incorrectly being suppressed then raise a bloody RuntimeError chained to the one that would be hidden otherwise:\ndef assert_no_AttributeError(f):\n @functools.wraps(f)\n def assert_no_AttrError_wrapper(*args,**kw):\n try:\n return f(*args,**kw)\n except AttributeError as e:\n e.__traceback__ = e.__traceback__.tb_next\n raise RuntimeError(\"AttributeError was incorrectly raised\") from e\n return assert_no_AttrError_wrapper\n\nthen if you decorate your property with this you will get an error like this:\nTraceback (most recent call last):\n File \".../test.py\", line 27, in my_prop\n return deeply_nested_factory_fn()\n File \".../test.py\", line 17, in deeply_nested_factory_fn\n return a.invalid_attr\nAttributeError: 'int' object has no attribute 'invalid_attr'\n\nThe above exception was the direct cause of the following exception:\n\nTraceback (most recent call last):\n File \".../test.py\", line 32, in <module>\n x.my_prop\n File \".../test.py\", line 11, in assert_no_AttrError_wrapper\n raise RuntimeError(\"AttributeError was incorrectly raised\") from e\nRuntimeError: AttributeError was incorrectly raised\n\nAlthough if you expect more then just one thing to raise an AttributeError then you might want to just overload __getattribute__ to check for any peculiar error for all lookups:\ndef __getattribute__(self,attr):\n try:\n return object.__getattribute__(self,attr)\n except AttributeError as e:\n if str(e) == \"{0.__class__.__name__!r} object has no attribute {1!r}\".format(self,attr):\n raise #normal case of \"attribute not found\"\n else: #if the error message was anything else then it *causes* a RuntimeError\n raise RuntimeError(\"Unexpected AttributeError\") from e\n\nThis way when something goes wrong that you are not expecting you will know it right away!\n", "Just in case others find this: the problem with the example on top is that an AttributeError is raised inside __getattr__. Instead, one should call self.__getattribute__(attr) to let that raise.\nExample\ndef deeply_nested_factory_fn():\n a = 2\n return a.invalid_attr\n\nclass Test(object):\n def __getattr__(self, name):\n if name == 'abc':\n return 'abc'\n return self.__getattribute__(name)\n @property\n def my_prop(self):\n return deeply_nested_factory_fn()\n\ntest = Test()\ntest.my_prop\n\nThis yields\nAttributeError Traceback (most recent call last)\nCell In [1], line 15\n 12 return deeply_nested_factory_fn()\n 14 test = Test()\n---> 15 test.my_prop\n\nCell In [1], line 9, in Test.__getattr__(self, name)\n 7 if name == 'abc':\n 8 return 'abc'\n----> 9 return self.__getattribute__(name)\n\nCell In [1], line 12, in Test.my_prop(self)\n 10 @property\n 11 def my_prop(self):\n---> 12 return deeply_nested_factory_fn()\n\nCell In [1], line 3, in deeply_nested_factory_fn()\n 1 def deeply_nested_factory_fn():\n 2 a = 2\n----> 3 return a.invalid_attr\n\nAttributeError: 'int' object has no attribute 'invalid_attr'\n\n" ]
[ 3, 1, 0 ]
[]
[]
[ "attributeerror", "getattr", "properties", "python" ]
stackoverflow_0036575068_attributeerror_getattr_properties_python.txt
Q: Allow for only 1 of multiple text input fields to submit I run a Shopify store that offers custom text prints with custom fonts. I was able to set up a form for when a visitor selects a font, a text input field appears where they type their text in and they can see a preview of how the text will appear with current selected font. I also got the form to show the input field per selected font while hiding the others, my problem is this: text entered into 1 field for a specific font doesn't clear when selecting another font to view. So if a customer tests 1 font and selects another to test, both text input fields are pushed to the cart with the text that was entered. I need the text field to clear when selecting another font option from the dropdown. I can fix this by setting 1 general text input field but I need name="properties[Block]" name="properties[Century]" etc so it can push the selected font & text to the cart & order. I hope this makes sense. Here is the code (i'm sure it's pretty rookie-ish, sorry this is not my strong suit): $('#noengraving').hide(); $('#block').hide(); $('#century').hide(); $('#clarendon').hide(); $('#cursive').hide(); $('#interlockingmonogram').hide(); $('#oldenglish').hide(); $('#roman').hide(); $('#script').hide(); $('#university').hide(); $('#cases').change(function() { var value = this.value; $('#noengraving').hide(); $('#block').hide(); $('#century').hide(); $('#clarendon').hide(); $('#cursive').hide(); $('#interlockingmonogram').hide(); $('#oldenglish').hide(); $('#roman').hide(); $('#script').hide(); $('#university').hide(); $('#' + this.value).show(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label>Font <select name="cases" id="cases"> <option value="select" selected="selected"title="">------</option> <option style="font-family: block" value="block">Block</option> <option style="font-family: century" value="century">Century</option> <option style="font-family: clarendon" value="clarendon">Clarendon</option> <option style="font-family: sursive" value="cursive">Cursive</option> <option style="font-family: interlockingmonogram" value="interlockingmonogram">Interlocking Monogram</option> <option style="font-family: oldenglish" value="oldenglish">Old English</option> <option style="font-family: roman" value="roman">Roman</option> <option style="font-family: script" value="script">Script</option> <option style="font-family: university" value="university">University</option> <option value="noengraving">No Engraving</option> </select></label> <div class="noengraving" id="noengraving"> <label> <input id="noengraving" type="text" style='font-family: block; font-size:20pt;' name="properties[No Engraving]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="block" id="block"> <label>Enter Text <input id="block" type="text" style='font-family: block; font-size:20pt;' name="properties[Block]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="century" id="century"> <label>Enter Text <input id="century" type="text" style='font-family: century; font-size:20pt;' name="properties[Century]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="clarendon" id="clarendon"> <label>Enter Text <input id="calrendon" type="text" style='font-family: clarendon; font-size:20pt;' name="properties[Clarendon]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="cursive" id="cursive"> <label>Enter Text <input id="cursive" type="text" style='font-family: cursive; font-size:20pt;' name="properties[Cursive]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="interlockingmonogram" id="interlockingmonogram"> <label>Enter Text <input id="interlockmonogram" type="text" style='font-family: interlockingmonogram; font-size:20pt;' name="properties[Interlock Monogram]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="oldenglish" id="oldenglish"> <label>Enter Text <input id="oldenglish" type="text" style='font-family: oldenglish; font-size:20pt;' name="properties[Old English]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="roman" id="roman"> <label>Enter Text <input id="roman" type="text" style='font-family: roman; font-size:20pt;' name="properties[Roman]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="script" id="script"> <label>Enter Text <input id="script" type="text" style='font-family: script; font-size:20pt;' name="properties[Script]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="university" id="university"> <label>Enter Text <input id="university" type="text" style='font-family: university; font-size:20pt;' name="properties[University]" required minlength="4" maxlength="8" size="10"> </label></div> I tried part of this code: http://jsfiddle.net/bhimubgm/mj5Cm/ it partially worked but still left me without a solution A: The following demonstrates what I meant with my comment: $('#cases').change(function() { $('#usertext').css("font-family",this.value).prop("name",`properties[${this.value}]`); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label>Font <select name="cases" id="cases"> <option value="select" selected="selected" value="">------</option> <option style="font-family: block" value="block">Block</option> <option style="font-family: century" value="century">Century</option> <option style="font-family: clarendon" value="clarendon">Clarendon</option> <option style="font-family: sursive" value="cursive">Cursive</option> <option style="font-family: interlockingmonogram" value="interlockingmonogram">Interlocking Monogram</option> <option style="font-family: oldenglish" value="oldenglish">Old English</option> <option style="font-family: roman" value="roman">Roman</option> <option style="font-family: script" value="script">Script</option> <option style="font-family: university" value="university">University</option> <option value="noengraving">No Engraving</option> </select></label> <div><label>Enter Text <input id="usertext" type="text" style='font-size:20pt;' name="usertext" required minlength="4" maxlength="8" size="10"> </label></div> There is only one user input field that will be formatted dynamically.
Allow for only 1 of multiple text input fields to submit
I run a Shopify store that offers custom text prints with custom fonts. I was able to set up a form for when a visitor selects a font, a text input field appears where they type their text in and they can see a preview of how the text will appear with current selected font. I also got the form to show the input field per selected font while hiding the others, my problem is this: text entered into 1 field for a specific font doesn't clear when selecting another font to view. So if a customer tests 1 font and selects another to test, both text input fields are pushed to the cart with the text that was entered. I need the text field to clear when selecting another font option from the dropdown. I can fix this by setting 1 general text input field but I need name="properties[Block]" name="properties[Century]" etc so it can push the selected font & text to the cart & order. I hope this makes sense. Here is the code (i'm sure it's pretty rookie-ish, sorry this is not my strong suit): $('#noengraving').hide(); $('#block').hide(); $('#century').hide(); $('#clarendon').hide(); $('#cursive').hide(); $('#interlockingmonogram').hide(); $('#oldenglish').hide(); $('#roman').hide(); $('#script').hide(); $('#university').hide(); $('#cases').change(function() { var value = this.value; $('#noengraving').hide(); $('#block').hide(); $('#century').hide(); $('#clarendon').hide(); $('#cursive').hide(); $('#interlockingmonogram').hide(); $('#oldenglish').hide(); $('#roman').hide(); $('#script').hide(); $('#university').hide(); $('#' + this.value).show(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label>Font <select name="cases" id="cases"> <option value="select" selected="selected"title="">------</option> <option style="font-family: block" value="block">Block</option> <option style="font-family: century" value="century">Century</option> <option style="font-family: clarendon" value="clarendon">Clarendon</option> <option style="font-family: sursive" value="cursive">Cursive</option> <option style="font-family: interlockingmonogram" value="interlockingmonogram">Interlocking Monogram</option> <option style="font-family: oldenglish" value="oldenglish">Old English</option> <option style="font-family: roman" value="roman">Roman</option> <option style="font-family: script" value="script">Script</option> <option style="font-family: university" value="university">University</option> <option value="noengraving">No Engraving</option> </select></label> <div class="noengraving" id="noengraving"> <label> <input id="noengraving" type="text" style='font-family: block; font-size:20pt;' name="properties[No Engraving]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="block" id="block"> <label>Enter Text <input id="block" type="text" style='font-family: block; font-size:20pt;' name="properties[Block]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="century" id="century"> <label>Enter Text <input id="century" type="text" style='font-family: century; font-size:20pt;' name="properties[Century]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="clarendon" id="clarendon"> <label>Enter Text <input id="calrendon" type="text" style='font-family: clarendon; font-size:20pt;' name="properties[Clarendon]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="cursive" id="cursive"> <label>Enter Text <input id="cursive" type="text" style='font-family: cursive; font-size:20pt;' name="properties[Cursive]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="interlockingmonogram" id="interlockingmonogram"> <label>Enter Text <input id="interlockmonogram" type="text" style='font-family: interlockingmonogram; font-size:20pt;' name="properties[Interlock Monogram]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="oldenglish" id="oldenglish"> <label>Enter Text <input id="oldenglish" type="text" style='font-family: oldenglish; font-size:20pt;' name="properties[Old English]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="roman" id="roman"> <label>Enter Text <input id="roman" type="text" style='font-family: roman; font-size:20pt;' name="properties[Roman]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="script" id="script"> <label>Enter Text <input id="script" type="text" style='font-family: script; font-size:20pt;' name="properties[Script]" required minlength="4" maxlength="8" size="10"> </label></div> <div class="university" id="university"> <label>Enter Text <input id="university" type="text" style='font-family: university; font-size:20pt;' name="properties[University]" required minlength="4" maxlength="8" size="10"> </label></div> I tried part of this code: http://jsfiddle.net/bhimubgm/mj5Cm/ it partially worked but still left me without a solution
[ "The following demonstrates what I meant with my comment:\n\n\n$('#cases').change(function() {\n $('#usertext').css(\"font-family\",this.value).prop(\"name\",`properties[${this.value}]`);\n});\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<label>Font\n<select name=\"cases\" id=\"cases\">\n <option value=\"select\" selected=\"selected\" value=\"\">------</option>\n <option style=\"font-family: block\" value=\"block\">Block</option>\n <option style=\"font-family: century\" value=\"century\">Century</option>\n <option style=\"font-family: clarendon\" value=\"clarendon\">Clarendon</option>\n <option style=\"font-family: sursive\" value=\"cursive\">Cursive</option>\n <option style=\"font-family: interlockingmonogram\" value=\"interlockingmonogram\">Interlocking Monogram</option>\n <option style=\"font-family: oldenglish\" value=\"oldenglish\">Old English</option>\n <option style=\"font-family: roman\" value=\"roman\">Roman</option>\n <option style=\"font-family: script\" value=\"script\">Script</option>\n <option style=\"font-family: university\" value=\"university\">University</option>\n <option value=\"noengraving\">No Engraving</option> \n </select></label>\n\n<div><label>Enter Text\n<input id=\"usertext\" type=\"text\" style='font-size:20pt;' name=\"usertext\" required minlength=\"4\" maxlength=\"8\" size=\"10\">\n</label></div>\n\n\n\nThere is only one user input field that will be formatted dynamically.\n" ]
[ 0 ]
[]
[]
[ "forms", "html", "jquery" ]
stackoverflow_0074678752_forms_html_jquery.txt
Q: How to convert Hex to RGB? I am trying to use this to figure out if a color is light or dark Evaluate whether a HEX value is dark or light Now. It takes in a int float calcLuminance(int rgb) { int r = (rgb & 0xff0000) >> 16; int g = (rgb & 0xff00) >> 8; int b = (rgb & 0xff); return (r*0.299f + g*0.587f + b*0.114f) / 256; } I have a hex color though. I tried to do this var color = System.Drawing.ColorTranslator.FromHtml("#FFFFFF"); int rgb = color.R + color.G + color.B; var a = calcLuminance(rgb); I got 0.11725 I thought it would have to be in the range of 0-256 or something like that. What am I doing wrong? Do I have to covert R to an int? Or am I just way off? A: Just convert the hex string to an integer: int color = Convert.ToInt32("FFFFFF", 16); A: You can use: public string GenerateRgba(string backgroundColor, decimal backgroundOpacity) { Color color = ColorTranslator.FromHtml(hexBackgroundColor); int r = Convert.ToInt16(color.R); int g = Convert.ToInt16(color.G); int b = Convert.ToInt16(color.B); return string.Format("rgba({0}, {1}, {2}, {3});", r, g, b, backgroundOpacity); } Link To original Post by jeremy clifton on git A: I am trying to use this to figure out if a color is light or dark Just use Color.GetBrightness() [Edit] I want to determine if I should use white or black for my text. So anything ≤ .5 I should use white and > .5 black? There are a number of ways to determine what color to use on a given background, none of which are perfect. That last link actually recommends using black/white only, but choosing a cutoff point of 0.73 instead of 0.5. I think you should just go with that, and change it if you find it doesn't work for you. A: A little of topic, but here is an extension method to the Color struct I've created to calculate Luminance with different algorithms. Hope it helps you. public static class ColorExtensions { /// <summary> /// Gets the luminance of the color. A value between 0 (black) and 1 (white) /// </summary> /// <param name="color">The color.</param> /// <param name="algorithm">The type of luminance alg to use.</param> /// <returns>A value between 0 (black) and 1 (white)</returns> public static double GetLuminance(this Color color, LuminanceAlgorithm algorithm = LuminanceAlgorithm.Photometric) { switch (algorithm) { case LuminanceAlgorithm.CCIR601: return (0.2126 * color.R + 0.7152 * color.G + 0.0722 * color.B) / 255; case LuminanceAlgorithm.Perceived: return (Math.Sqrt(0.241 * Math.Pow(color.R, 2) + 0.691 * Math.Pow(color.G, 2) + 0.068 * Math.Pow(color.B, 2)) / 255); case LuminanceAlgorithm.Photometric: return (0.299 * color.R + 0.587 * color.G + 0.114 * color.B) / 255; } } /// <summary> /// The luminances /// </summary> public enum LuminanceAlgorithm { /// <summary> /// Photometric/digital ITU-R /// </summary> Photometric, /// <summary> /// Digital CCIR601 (gives more weight to the R and B components, as preciev by the human eye) /// </summary> CCIR601, /// <summary> /// A perceived luminance /// </summary> Perceived } } A: The problem, as I see it, is your calculation of rgb. You add the values together which gives you a number between 0 and 3*255 which clearly isn't the value your method expect. You will have to calculate it like this int rgb = (int)color.R << 16 + (int)color.G << 8 + color.B; which should be equivalent to this (except for the alpha-value you don't use) int rgb = color.ToArgb(); Lastly, as you can see in Chris Haas answer, you can skip this step by converting directly to an int. A: Your idea is OK, but your function is wrong, correct one is here: int rgb = Convert.ToInt32("#FFFFFF", 16); var a = calcLuminance(rgb); float calcLuminance(int rgb) { int r = (rgb & 0xff0000) >> 16; int g = (rgb & 0xff00) >> 8; int b = (rgb & 0xff); return (r*0.299f + g*0.587f + b*0.114f) / 256; } A: The ranges of the R, G and B from the Color struct are 0-255. To get the rgb value you expect in your function, you will need to left shift accordingly: int rgb = (int)color.R << 16 + (int)color.G << 8 + color.B; A: calcLuminance only returns a percentage. A: You can also convert HEX to RGB without using System.Drawing with this : int RGBint = Convert.ToInt32("FFD700", 16); byte Red = (byte)((RGBint >> 16) & 255); byte Green = (byte)((RGBint >> 8) & 255); byte Blue = (byte)(RGBint & 255); //Color.FromRgb(Red, Green, Blue);
How to convert Hex to RGB?
I am trying to use this to figure out if a color is light or dark Evaluate whether a HEX value is dark or light Now. It takes in a int float calcLuminance(int rgb) { int r = (rgb & 0xff0000) >> 16; int g = (rgb & 0xff00) >> 8; int b = (rgb & 0xff); return (r*0.299f + g*0.587f + b*0.114f) / 256; } I have a hex color though. I tried to do this var color = System.Drawing.ColorTranslator.FromHtml("#FFFFFF"); int rgb = color.R + color.G + color.B; var a = calcLuminance(rgb); I got 0.11725 I thought it would have to be in the range of 0-256 or something like that. What am I doing wrong? Do I have to covert R to an int? Or am I just way off?
[ "Just convert the hex string to an integer:\nint color = Convert.ToInt32(\"FFFFFF\", 16);\n\n", "You can use:\npublic string GenerateRgba(string backgroundColor, decimal backgroundOpacity)\n{\n Color color = ColorTranslator.FromHtml(hexBackgroundColor);\n int r = Convert.ToInt16(color.R);\n int g = Convert.ToInt16(color.G);\n int b = Convert.ToInt16(color.B);\n return string.Format(\"rgba({0}, {1}, {2}, {3});\", r, g, b, backgroundOpacity);\n}\n\nLink To original Post by jeremy clifton on git\n", "\nI am trying to use this to figure out if a color is light or dark\n\nJust use Color.GetBrightness()\n\n[Edit]\n\nI want to determine if I should use white or black for my text. So anything ≤ .5 I should use white and > .5 black?\n\nThere are a number of ways to determine what color to use on a given background, none of which are perfect.\nThat last link actually recommends using black/white only, but choosing a cutoff point of 0.73 instead of 0.5. I think you should just go with that, and change it if you find it doesn't work for you.\n", "A little of topic, but here is an extension method to the Color struct I've created to calculate Luminance with different algorithms. Hope it helps you.\npublic static class ColorExtensions\n{\n /// <summary>\n /// Gets the luminance of the color. A value between 0 (black) and 1 (white)\n /// </summary>\n /// <param name=\"color\">The color.</param>\n /// <param name=\"algorithm\">The type of luminance alg to use.</param>\n /// <returns>A value between 0 (black) and 1 (white)</returns>\n public static double GetLuminance(this Color color, LuminanceAlgorithm algorithm = LuminanceAlgorithm.Photometric)\n {\n switch (algorithm)\n {\n case LuminanceAlgorithm.CCIR601:\n return (0.2126 * color.R + 0.7152 * color.G + 0.0722 * color.B) / 255;\n\n case LuminanceAlgorithm.Perceived:\n return (Math.Sqrt(0.241 * Math.Pow(color.R, 2) + 0.691 * Math.Pow(color.G, 2) + 0.068 * Math.Pow(color.B, 2)) / 255);\n\n case LuminanceAlgorithm.Photometric:\n return (0.299 * color.R + 0.587 * color.G + 0.114 * color.B) / 255;\n }\n\n }\n\n /// <summary>\n /// The luminances\n /// </summary>\n public enum LuminanceAlgorithm\n {\n /// <summary>\n /// Photometric/digital ITU-R\n /// </summary>\n Photometric,\n\n /// <summary>\n /// Digital CCIR601 (gives more weight to the R and B components, as preciev by the human eye)\n /// </summary>\n CCIR601,\n\n /// <summary>\n /// A perceived luminance\n /// </summary>\n Perceived\n }\n}\n\n", "The problem, as I see it, is your calculation of rgb. You add the values together which gives you a number between 0 and 3*255 which clearly isn't the value your method expect. You will have to calculate it like this\nint rgb = (int)color.R << 16 + (int)color.G << 8 + color.B;\n\nwhich should be equivalent to this (except for the alpha-value you don't use)\nint rgb = color.ToArgb();\n\nLastly, as you can see in Chris Haas answer, you can skip this step by converting directly to an int.\n", "Your idea is OK, but your function is wrong, correct one is here:\nint rgb = Convert.ToInt32(\"#FFFFFF\", 16);\nvar a = calcLuminance(rgb);\n\nfloat calcLuminance(int rgb)\n{\n int r = (rgb & 0xff0000) >> 16;\n int g = (rgb & 0xff00) >> 8;\n int b = (rgb & 0xff);\n return (r*0.299f + g*0.587f + b*0.114f) / 256;\n}\n\n", "The ranges of the R, G and B from the Color struct are 0-255.\nTo get the rgb value you expect in your function, you will need to left shift accordingly:\nint rgb = (int)color.R << 16 + (int)color.G << 8 + color.B;\n\n", "calcLuminance only returns a percentage.\n", "You can also convert HEX to RGB without using System.Drawing with this :\n int RGBint = Convert.ToInt32(\"FFD700\", 16);\n byte Red = (byte)((RGBint >> 16) & 255);\n byte Green = (byte)((RGBint >> 8) & 255);\n byte Blue = (byte)(RGBint & 255);\n //Color.FromRgb(Red, Green, Blue);\n\n" ]
[ 27, 18, 9, 4, 2, 2, 1, 1, 0 ]
[]
[]
[ ".net", "c#", "colors", "hex", "rgb" ]
stackoverflow_0005735886_.net_c#_colors_hex_rgb.txt
Q: Doing operations inside millions of csv files with python script csv format screenshot of my csv So, as shown in the attached file (one among the millions of csv files I have), they are in one line with 13890 columns. I had to convert them into two columns only with several lines instead the actual form in order to have the date and its parameter only. The applied operations to convert each file can be done but when I have to convert the 3 to 4 millions of files, even though the script is working well, the execution is taking forever and approximately will finish after 2 years. I need to convert all the files ASAP how to do it? If someone could propose a fast script to convert or just a method to speed up th script it would be so nice. Thanks in advance. I even though about using pyarow also splitting csv files in different folders but nothing has changed the converting speed still too slow (the machine I am using is a 2TB SSD with 16 gb RAM). I have also tried the script in another pc with less performance the speed of the script execution still same!!! Here is my script for those who asked it. import os, sys, csv op = 1 df_list_old = [] path_old_files = "D:/Pycharm/" for file in os.listdir(path_old_files): df_list_old.append(file) for file in df_list_old: fileExist = os.path.exists(file) if fileExist is True: print("File number " already converted") op = op + 1 else: print("File number ",op," name ",file) with open(path_old_files+file, 'r') as file_to_convert: reader = csv.reader(file_to_convert) for item in reader: for i in item: if item.index(i) == 5: print("Start of conversion operation") data = int((item[5])[53:61]), float((item[5])[64:]) elif (item.index(i) > 5) and (item.index(i) < len(item)-14): data = int((item[item.index(i)])[2:10]), float((item[item.index(i)])[13:]) elif item.index(i) == len(item)-14: data = int((item[len(item)-14])[2:10]), float((item[len(item)-14])[13:17]) print("End of conversion operation") with open(file, 'a', newline='') as csv_file: if item.index(i) >= 5: writer = csv.writer(csv_file) writer.writerow(data) op = op + 1 A: So, there are a couple of ways to parse the file better: First up you can use enumerate when you want access to the index as well as the value in an array. Second there's no need to check every index because you already know which ones contain the data you need. And for optimisation the biggest mistake was opening and closing the write_file for every line you wanted to write. Imagine writing a book but after every line you closed it just to open it again. with open(path_old_files+file, 'r') as file_to_convert: # create an array, we will store the lines in here data = [] reader = csv.reader(file_to_convert) for item in reader: # rather than checking each line, only check the lines we are going to use [start_index, end_index] # use enumerate to get the index as well as the value for index, value in enumerate(item[5: -14]): if index == 0: print("Start of conversion operation") # add the line to the data array data.append((int(value[53:61]), float(value[64:]))) elif index == len(item)-14: # add the line to the data array data.append((int(item[index][2:10]), float(item[index][13:17]))) print("End of conversion operation") else: # add the line to the data array data.append((int(item[index][2:10]), float(item[index][13:]))) # because we have made an array of the lines we only have to open the file to write once, before you were # opening and closing the file for each line, this was probably the biggest inefficiency with open(file, 'a', newline='') as csv_file: for line in data: writer = csv.writer(csv_file) writer.writerow(line) I'm not entirely sure how you want the data to be outputted so mess around with the data.append. I have put the values in as tuple.
Doing operations inside millions of csv files with python script
csv format screenshot of my csv So, as shown in the attached file (one among the millions of csv files I have), they are in one line with 13890 columns. I had to convert them into two columns only with several lines instead the actual form in order to have the date and its parameter only. The applied operations to convert each file can be done but when I have to convert the 3 to 4 millions of files, even though the script is working well, the execution is taking forever and approximately will finish after 2 years. I need to convert all the files ASAP how to do it? If someone could propose a fast script to convert or just a method to speed up th script it would be so nice. Thanks in advance. I even though about using pyarow also splitting csv files in different folders but nothing has changed the converting speed still too slow (the machine I am using is a 2TB SSD with 16 gb RAM). I have also tried the script in another pc with less performance the speed of the script execution still same!!! Here is my script for those who asked it. import os, sys, csv op = 1 df_list_old = [] path_old_files = "D:/Pycharm/" for file in os.listdir(path_old_files): df_list_old.append(file) for file in df_list_old: fileExist = os.path.exists(file) if fileExist is True: print("File number " already converted") op = op + 1 else: print("File number ",op," name ",file) with open(path_old_files+file, 'r') as file_to_convert: reader = csv.reader(file_to_convert) for item in reader: for i in item: if item.index(i) == 5: print("Start of conversion operation") data = int((item[5])[53:61]), float((item[5])[64:]) elif (item.index(i) > 5) and (item.index(i) < len(item)-14): data = int((item[item.index(i)])[2:10]), float((item[item.index(i)])[13:]) elif item.index(i) == len(item)-14: data = int((item[len(item)-14])[2:10]), float((item[len(item)-14])[13:17]) print("End of conversion operation") with open(file, 'a', newline='') as csv_file: if item.index(i) >= 5: writer = csv.writer(csv_file) writer.writerow(data) op = op + 1
[ "So, there are a couple of ways to parse the file better:\nFirst up you can use enumerate when you want access to the index as well as the value in an array.\nSecond there's no need to check every index because you already know which ones contain the data you need.\nAnd for optimisation the biggest mistake was opening and closing the write_file for every line you wanted to write. Imagine writing a book but after every line you closed it just to open it again.\n with open(path_old_files+file, 'r') as file_to_convert:\n # create an array, we will store the lines in here\n data = []\n reader = csv.reader(file_to_convert)\n for item in reader:\n # rather than checking each line, only check the lines we are going to use [start_index, end_index]\n # use enumerate to get the index as well as the value\n for index, value in enumerate(item[5: -14]):\n if index == 0:\n print(\"Start of conversion operation\")\n # add the line to the data array\n data.append((int(value[53:61]), float(value[64:])))\n elif index == len(item)-14:\n # add the line to the data array\n data.append((int(item[index][2:10]), float(item[index][13:17])))\n print(\"End of conversion operation\")\n else:\n # add the line to the data array\n data.append((int(item[index][2:10]), float(item[index][13:])))\n # because we have made an array of the lines we only have to open the file to write once, before you were\n # opening and closing the file for each line, this was probably the biggest inefficiency\n with open(file, 'a', newline='') as csv_file:\n for line in data:\n writer = csv.writer(csv_file)\n writer.writerow(line)\n\nI'm not entirely sure how you want the data to be outputted so mess around with the data.append. I have put the values in as tuple.\n" ]
[ 1 ]
[]
[]
[ "csv", "database", "pyarrow", "pycharm", "python" ]
stackoverflow_0074678238_csv_database_pyarrow_pycharm_python.txt
Q: Discord.py | How do I detect if an argument is empty? (with a if statement) My bot is supposed to send a error message if no arguments are passed. @bot.command(pass_context = True , aliases=['sl']) async def slow (ctx, arg): if arg > '21600': await ctx.send("You are restricted to ``21600 seconds``") else: if arg == None: await ctx.send(f"Error 00: Please specify slowmode time. e.g: !slow 2") else: await ctx.channel.edit(slowmode_delay=arg) await ctx.send(f"Slowmode set to ``{arg}`` seconds.") It isn't responding with the error message if no arguments are passed. A: 2 things; 1, check if the arg is None first. 2, if arg is None, it will show up in the console as an error instead, so make the arg optional @client.command(pass_context = True , aliases=['sl']) async def slow (ctx, duration: int=None): #=None makes it optional or you can use Optional[int] and import Optional from typing if duration == None: await ctx.send(f"Error 00: Please specify slowmode time. e.g: !slow 2") if duration > 21600: await ctx.send("You are restricted to ``21600 seconds``") else: await ctx.channel.edit(slowmode_delay=duration) await ctx.send(f"Slowmode set to ``{duration}`` seconds.") btw, I changed arg=None to duration: int=None because it's easier to read
Discord.py | How do I detect if an argument is empty? (with a if statement)
My bot is supposed to send a error message if no arguments are passed. @bot.command(pass_context = True , aliases=['sl']) async def slow (ctx, arg): if arg > '21600': await ctx.send("You are restricted to ``21600 seconds``") else: if arg == None: await ctx.send(f"Error 00: Please specify slowmode time. e.g: !slow 2") else: await ctx.channel.edit(slowmode_delay=arg) await ctx.send(f"Slowmode set to ``{arg}`` seconds.") It isn't responding with the error message if no arguments are passed.
[ "2 things; 1, check if the arg is None first. 2, if arg is None, it will show up in the console as an error instead, so make the arg optional\n@client.command(pass_context = True , aliases=['sl'])\nasync def slow (ctx, duration: int=None): #=None makes it optional or you can use Optional[int] and import Optional from typing\n if duration == None:\n await ctx.send(f\"Error 00: Please specify slowmode time. e.g: !slow 2\")\n if duration > 21600:\n await ctx.send(\"You are restricted to ``21600 seconds``\")\n else:\n await ctx.channel.edit(slowmode_delay=duration)\n await ctx.send(f\"Slowmode set to ``{duration}`` seconds.\")\n\nbtw, I changed arg=None to duration: int=None because it's easier to read\n" ]
[ 0 ]
[]
[]
[ "discord.py" ]
stackoverflow_0074675102_discord.py.txt
Q: Outer minimum vectorization in numpy Given an NxM matrix A, I want to efficiently obtain the NxMxN tensor whose ith layer is the application of np.minimum between A and the ith row of A. Using a for loop: > A = np.array([[1, 2], [3, 4], [5,6]]) > output = np.zeros(shape=(A.shape[0], A.shape[1], A.shape[0])) > for i in range(a.shape[0]): output[:, :, i] = np.minimum(A, A[i]) > output array([[[1., 1., 1.], [2., 2., 2.]], [[1., 3., 3.], [2., 4., 4.]], [[1., 3., 5.], [2., 4., 6.]]]) This is very slow so I would like to get rid of the for loop and vectorize it. I feel like there should be a general method that works with any function of a matrix and a vector not just, minimum. Using np.minimum.outer does not work as it outputs an order 4 tensor. A: With broadcasting we can make a (3,3,2) result: In [153]: np.minimum(A[:,None,:],A[None,:,:]) Out[153]: array([[[1, 2], [1, 2], [1, 2]], [[1, 2], [3, 4], [3, 4]], [[1, 2], [3, 4], [5, 6]]]) and then switch the last 2 dimensions to get the (3,2,3) you want: In [154]: np.minimum(A[:,None,:],A[None,:,:]).transpose(0,2,1) Out[154]: array([[[1, 1, 1], [2, 2, 2]], [[1, 3, 3], [2, 4, 4]], [[1, 3, 5], [2, 4, 6]]]) Or do the transpose first In [155]: np.minimum(A[:,:,None],A.T[None,:,:]) # (3,2,1) (1,2,3)=>(3,2,3) Out[155]: array([[[1, 1, 1], [2, 2, 2]], [[1, 3, 3], [2, 4, 4]], [[1, 3, 5], [2, 4, 6]]]) edit Adding the sum is trivial: In [157]: np.minimum(A[:,:,None],A.T[None,:,:]).sum(axis=1) Out[157]: array([[ 3, 3, 3], [ 3, 7, 7], [ 3, 7, 11]]) A: To efficiently obtain the tensor you described without using a for loop, you can use the np.einsum function. This function allows you to specify a summation operation using a simple string notation, which can be much faster than using a for loop. import numpy as np A = np.array([[1, 2], [3, 4], [5,6]]) output = np.einsum('ij,ik->ijk', A, A) print(output) This code will produce the same output as your original code, but without using a for loop. The key to using np.einsum in this case is the string 'ij,ik->ijk'. This string specifies the summation operation that np.einsum will perform. The first two letters 'ij' specify the indices of the first operand (in this case, A), and the second two letters 'ik' specify the indices of the second operand (also A). Finally, the last three letters 'ijk' specify the indices of the output tensor. In this case, the np.einsum function will compute the tensor by applying the minimum operator element-wise to the two operands. This is equivalent to your original code, but it is much faster because it uses a vectorized operation instead of a for loop.
Outer minimum vectorization in numpy
Given an NxM matrix A, I want to efficiently obtain the NxMxN tensor whose ith layer is the application of np.minimum between A and the ith row of A. Using a for loop: > A = np.array([[1, 2], [3, 4], [5,6]]) > output = np.zeros(shape=(A.shape[0], A.shape[1], A.shape[0])) > for i in range(a.shape[0]): output[:, :, i] = np.minimum(A, A[i]) > output array([[[1., 1., 1.], [2., 2., 2.]], [[1., 3., 3.], [2., 4., 4.]], [[1., 3., 5.], [2., 4., 6.]]]) This is very slow so I would like to get rid of the for loop and vectorize it. I feel like there should be a general method that works with any function of a matrix and a vector not just, minimum. Using np.minimum.outer does not work as it outputs an order 4 tensor.
[ "With broadcasting we can make a (3,3,2) result:\nIn [153]: np.minimum(A[:,None,:],A[None,:,:])\nOut[153]: \narray([[[1, 2],\n [1, 2],\n [1, 2]],\n\n [[1, 2],\n [3, 4],\n [3, 4]],\n\n [[1, 2],\n [3, 4],\n [5, 6]]])\n\nand then switch the last 2 dimensions to get the (3,2,3) you want:\nIn [154]: np.minimum(A[:,None,:],A[None,:,:]).transpose(0,2,1)\nOut[154]: \narray([[[1, 1, 1],\n [2, 2, 2]],\n\n [[1, 3, 3],\n [2, 4, 4]],\n\n [[1, 3, 5],\n [2, 4, 6]]])\n\nOr do the transpose first\nIn [155]: np.minimum(A[:,:,None],A.T[None,:,:]) # (3,2,1) (1,2,3)=>(3,2,3)\nOut[155]: \narray([[[1, 1, 1],\n [2, 2, 2]],\n\n [[1, 3, 3],\n [2, 4, 4]],\n\n [[1, 3, 5],\n [2, 4, 6]]])\n\nedit\nAdding the sum is trivial:\nIn [157]: np.minimum(A[:,:,None],A.T[None,:,:]).sum(axis=1)\nOut[157]: \narray([[ 3, 3, 3],\n [ 3, 7, 7],\n [ 3, 7, 11]])\n\n", "To efficiently obtain the tensor you described without using a for loop, you can use the np.einsum function. This function allows you to specify a summation operation using a simple string notation, which can be much faster than using a for loop.\nimport numpy as np\n\n\nA = np.array([[1, 2], [3, 4], [5,6]])\n\n\noutput = np.einsum('ij,ik->ijk', A, A)\n\n\nprint(output)\n\nThis code will produce the same output as your original code, but without using a for loop.\nThe key to using np.einsum in this case is the string 'ij,ik->ijk'. This string specifies the summation operation that np.einsum will perform. The first two letters 'ij' specify the indices of the first operand (in this case, A), and the second two letters 'ik' specify the indices of the second operand (also A). Finally, the last three letters 'ijk' specify the indices of the output tensor.\nIn this case, the np.einsum function will compute the tensor by applying the minimum operator element-wise to the two operands. This is equivalent to your original code, but it is much faster because it uses a vectorized operation instead of a for loop.\n" ]
[ 1, 0 ]
[]
[]
[ "numpy", "python", "vectorization" ]
stackoverflow_0074678481_numpy_python_vectorization.txt
Q: Covert iff from v4 to Pinescript v5 I'm trying my best to understand how to convert code form v4 to v5 and I have some successful attempts on some easy scripts, but I don't have any code skills, I'm trying to learn by myself the thing I need, but and I miss the basic to understand well what I'm doing really. So I'm asking you if you can help me with this, so I can learn from this too. Thank you ///.... xATRTrailingStop = 0.0 xATRTrailingStop := iff(src > nz(xATRTrailingStop[1], 0) and src[1] > nz(xATRTrailingStop[1], 0), max(nz(xATRTrailingStop[1]), src - nLoss), iff(src < nz(xATRTrailingStop[1], 0) and src[1] < nz(xATRTrailingStop[1], 0), min(nz(xATRTrailingStop[1]), src + nLoss), iff(src > nz(xATRTrailingStop[1], 0), src - nLoss, src + nLoss))) pos = 0 pos := iff(src[1] < nz(xATRTrailingStop[1], 0) and src > nz(xATRTrailingStop[1], 0), 1, iff(src[1] > nz(xATRTrailingStop[1], 0) and src < nz(xATRTrailingStop[1], 0), -1, nz(pos[1], 0))) ///... I tried to convert "iff" to a ternary operator, I'm sorry if that's a mess :/ xATRTrailingStop = 0.0 xATRTrailingStop := (src > nz(xATRTrailingStop[1]) and src[1] > nz(xATRTrailingStop[1]) ? math.max(nz(xATRTrailingStop[1]), src - nLoss) : (src < nz(xATRTrailingStop[1], 0) and src[1] < nz(xATRTrailingStop[1], 0) ? min(nz(xATRTrailingStop[1]), src + nLoss) : (src > nz(xATRTrailingStop[1], 0), src - nLoss, src + nLoss)) A: You can convert to v5 by clicking on the left of the pinescript editor : The code of the v5 will be like this : xATRTrailingStop = 0.0 iff_1 = src > nz(xATRTrailingStop[1], 0) ? src - nLoss : src + nLoss iff_2 = src < nz(xATRTrailingStop[1], 0) and src[1] < nz(xATRTrailingStop[1], 0) ? math.min(nz(xATRTrailingStop[1]), src + nLoss) : iff_1 xATRTrailingStop := src > nz(xATRTrailingStop[1], 0) and src[1] > nz(xATRTrailingStop[1], 0) ? math.max(nz(xATRTrailingStop[1]), src - nLoss) : iff_2 pos = 0 iff_3 = src[1] > nz(xATRTrailingStop[1], 0) and src < nz(xATRTrailingStop[1], 0) ? -1 : nz(pos[1], 0) pos := src[1] < nz(xATRTrailingStop[1], 0) and src > nz(xATRTrailingStop[1], 0) ? 1 : iff_3
Covert iff from v4 to Pinescript v5
I'm trying my best to understand how to convert code form v4 to v5 and I have some successful attempts on some easy scripts, but I don't have any code skills, I'm trying to learn by myself the thing I need, but and I miss the basic to understand well what I'm doing really. So I'm asking you if you can help me with this, so I can learn from this too. Thank you ///.... xATRTrailingStop = 0.0 xATRTrailingStop := iff(src > nz(xATRTrailingStop[1], 0) and src[1] > nz(xATRTrailingStop[1], 0), max(nz(xATRTrailingStop[1]), src - nLoss), iff(src < nz(xATRTrailingStop[1], 0) and src[1] < nz(xATRTrailingStop[1], 0), min(nz(xATRTrailingStop[1]), src + nLoss), iff(src > nz(xATRTrailingStop[1], 0), src - nLoss, src + nLoss))) pos = 0 pos := iff(src[1] < nz(xATRTrailingStop[1], 0) and src > nz(xATRTrailingStop[1], 0), 1, iff(src[1] > nz(xATRTrailingStop[1], 0) and src < nz(xATRTrailingStop[1], 0), -1, nz(pos[1], 0))) ///... I tried to convert "iff" to a ternary operator, I'm sorry if that's a mess :/ xATRTrailingStop = 0.0 xATRTrailingStop := (src > nz(xATRTrailingStop[1]) and src[1] > nz(xATRTrailingStop[1]) ? math.max(nz(xATRTrailingStop[1]), src - nLoss) : (src < nz(xATRTrailingStop[1], 0) and src[1] < nz(xATRTrailingStop[1], 0) ? min(nz(xATRTrailingStop[1]), src + nLoss) : (src > nz(xATRTrailingStop[1], 0), src - nLoss, src + nLoss))
[ "You can convert to v5 by clicking on the left of the pinescript editor :\n\n\nThe code of the v5 will be like this : \nxATRTrailingStop = 0.0\niff_1 = src > nz(xATRTrailingStop[1], 0) ? src - nLoss : src + nLoss\niff_2 = src < nz(xATRTrailingStop[1], 0) and src[1] < nz(xATRTrailingStop[1], 0) ? math.min(nz(xATRTrailingStop[1]), src + nLoss) : iff_1\nxATRTrailingStop := src > nz(xATRTrailingStop[1], 0) and src[1] > nz(xATRTrailingStop[1], 0) ? math.max(nz(xATRTrailingStop[1]), src - nLoss) : iff_2\n\npos = 0\niff_3 = src[1] > nz(xATRTrailingStop[1], 0) and src < nz(xATRTrailingStop[1], 0) ? -1 : nz(pos[1], 0)\npos := src[1] < nz(xATRTrailingStop[1], 0) and src > nz(xATRTrailingStop[1], 0) ? 1 : iff_3\n\n" ]
[ 0 ]
[]
[]
[ "pinescript_v5", "type_conversion" ]
stackoverflow_0074674347_pinescript_v5_type_conversion.txt
Q: Full Calander with Line breaks Any help would be amazing I'm been stuck for ages trying to get this to work I've got a textarea named notes this data is pulled via full calendar event. <textarea style="white-space: pre-wrap; text-indent: 50px;" name="notes" id="notes" cols="30" rows="10" class="form-control"></textarea> The issue is that when I add a new line in the textarea using enter it's then causes the full calendar to break! I'm trying to work out how I can keep new lines in a text area so it can be saved saved in the DB without any line spaces! I've tried nl2br() it's still creating new lines! <script> $(document).ready(function() { $('#calendar').fullCalendar({ events : [ @foreach($bookings as $booking) { bookingId : '{{ $booking->id }}', title : '{{ $booking->booking_contact }}', start : '{{ $booking->booking_start }}', end: '{{ $booking->booking_end }}', content : '{{ $booking->notes }}', }, @endforeach ], eventClick: function(calEvent, jsEvent, view, event) { $('#bookingId').val(calEvent.bookingId); $('#booking_start').val(moment(calEvent.start).format('YYYY-MM-DD')); $('#booking_end').val(moment(calEvent.end).format('YYYY-MM-DD')); $('#title').val(calEvent.title); $('#notes').val(calEvent.content); $('#editModal').modal(); } }); }); </script> The error is: Uncaught SyntaxError: Invalid or unexpected token (at 5:223:31) Sources in chrome this is the db row notes content : 'Arriving at 19.20pm Departing at 20.05pm 1075 euros cash on arrival....', }, A: Try to use @json directive ... events: @json($bookings->map(function ($booking) { return [ 'bookingId' => $booking->id, 'title' => $booking->booking_contact, 'start' => $booking->booking_start, 'end' => $booking->booking_end, 'content' => $booking->notes, ]; }))
Full Calander with Line breaks
Any help would be amazing I'm been stuck for ages trying to get this to work I've got a textarea named notes this data is pulled via full calendar event. <textarea style="white-space: pre-wrap; text-indent: 50px;" name="notes" id="notes" cols="30" rows="10" class="form-control"></textarea> The issue is that when I add a new line in the textarea using enter it's then causes the full calendar to break! I'm trying to work out how I can keep new lines in a text area so it can be saved saved in the DB without any line spaces! I've tried nl2br() it's still creating new lines! <script> $(document).ready(function() { $('#calendar').fullCalendar({ events : [ @foreach($bookings as $booking) { bookingId : '{{ $booking->id }}', title : '{{ $booking->booking_contact }}', start : '{{ $booking->booking_start }}', end: '{{ $booking->booking_end }}', content : '{{ $booking->notes }}', }, @endforeach ], eventClick: function(calEvent, jsEvent, view, event) { $('#bookingId').val(calEvent.bookingId); $('#booking_start').val(moment(calEvent.start).format('YYYY-MM-DD')); $('#booking_end').val(moment(calEvent.end).format('YYYY-MM-DD')); $('#title').val(calEvent.title); $('#notes').val(calEvent.content); $('#editModal').modal(); } }); }); </script> The error is: Uncaught SyntaxError: Invalid or unexpected token (at 5:223:31) Sources in chrome this is the db row notes content : 'Arriving at 19.20pm Departing at 20.05pm 1075 euros cash on arrival....', },
[ "Try to use @json directive\n ... \n\n events: @json($bookings->map(function ($booking) {\n return [\n 'bookingId' => $booking->id,\n 'title' => $booking->booking_contact,\n 'start' => $booking->booking_start,\n 'end' => $booking->booking_end,\n 'content' => $booking->notes,\n ];\n }))\n\n" ]
[ 0 ]
[]
[]
[ "javascript", "jquery", "laravel", "laravel_blade", "php" ]
stackoverflow_0074502356_javascript_jquery_laravel_laravel_blade_php.txt
Q: Error while mering 2 groups (Im a beginner) So I have a MusicBand Class and I want to create a method that merges members of 2 different groups into one and clears the empty one. public class MusicBand { private int year; private String name; private List<String> members; public MusicBand(String name, int year, List<String> members) { this.name = name; this.year = year; this.members = members; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getMembers() { return members; } public void setMembers(List<String> members) { this.members = members; } public static void transferMembers(MusicBand a, MusicBand b) { for (String members : a.getMembers()) { b.getMembers().add(members); a.getMembers().clear(); } } public void printMembers(){ System.out.println(this.members); } } public class Test4 { public static void main(String[] args) { List<String> members1 = new ArrayList<>(); members1.add("a"); members1.add("b"); members1.add("c"); List<String>members2 = new ArrayList<>(); members2.add("a2"); members2.add("b2"); members2.add("c2"); MusicBand group1 = new MusicBand("aaa",1990,members1); MusicBand group2 = new MusicBand("bbb",2010,members2); group1.printMembers(); group2.printMembers(); MusicBand.transferMembers(group1,group2); } } So it prints out 2 groups and then instead of merging this happens "Exception in thread "main" java.util.ConcurrentModificationException" What can I do to fix this? Thanks in advance. A: Move your a.getMembers().clear(); method outside your for loop. In fact your transferMembers() method could look like the following: public static void transferMembers(MusicBand a, MusicBand b) { b.getMembers().add(members); a.getMembers().clear(); } There is no need for a for loop at all.
Error while mering 2 groups (Im a beginner)
So I have a MusicBand Class and I want to create a method that merges members of 2 different groups into one and clears the empty one. public class MusicBand { private int year; private String name; private List<String> members; public MusicBand(String name, int year, List<String> members) { this.name = name; this.year = year; this.members = members; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getMembers() { return members; } public void setMembers(List<String> members) { this.members = members; } public static void transferMembers(MusicBand a, MusicBand b) { for (String members : a.getMembers()) { b.getMembers().add(members); a.getMembers().clear(); } } public void printMembers(){ System.out.println(this.members); } } public class Test4 { public static void main(String[] args) { List<String> members1 = new ArrayList<>(); members1.add("a"); members1.add("b"); members1.add("c"); List<String>members2 = new ArrayList<>(); members2.add("a2"); members2.add("b2"); members2.add("c2"); MusicBand group1 = new MusicBand("aaa",1990,members1); MusicBand group2 = new MusicBand("bbb",2010,members2); group1.printMembers(); group2.printMembers(); MusicBand.transferMembers(group1,group2); } } So it prints out 2 groups and then instead of merging this happens "Exception in thread "main" java.util.ConcurrentModificationException" What can I do to fix this? Thanks in advance.
[ "Move your a.getMembers().clear(); method outside your for loop.\nIn fact your transferMembers() method could look like the following:\npublic static void transferMembers(MusicBand a, MusicBand b) {\n b.getMembers().add(members);\n a.getMembers().clear();\n}\n\nThere is no need for a for loop at all.\n" ]
[ 1 ]
[]
[]
[ "java" ]
stackoverflow_0074679015_java.txt
Q: How to fast insert new 'pipe operator' in Rstudio? I have been using the ctrl + shift + m shortcut to insert well known %>% pipe operator. Since the release of R version 4.1.0 and adding a new |> to base, I wonder is the corresponding shortcut available in Rstudio? A: It's the same shortcut. If you install the latest version of the IDE, and go to the Global Options window, select "Code" and you'll see an option for "use native pipe operator, |>". Select that for the shortcut to take effect. A: one option that works okay is to add a snippet to your code snippets if you're an rstudio user. You'd then need to hit the snippet name and then tab complete it. The ${0} then drops your cursor one whitespace away from the pipe so you save a keystroke there: snippet p |> ${0}
How to fast insert new 'pipe operator' in Rstudio?
I have been using the ctrl + shift + m shortcut to insert well known %>% pipe operator. Since the release of R version 4.1.0 and adding a new |> to base, I wonder is the corresponding shortcut available in Rstudio?
[ "It's the same shortcut. If you install the latest version of the IDE, and go to the Global Options window, select \"Code\" and you'll see an option for \"use native pipe operator, |>\". Select that for the shortcut to take effect.\n\n", "one option that works okay is to add a snippet to your code snippets if you're an rstudio user. You'd then need to hit the snippet name and then tab complete it. The ${0} then drops your cursor one whitespace away from the pipe so you save a keystroke there:\nsnippet p\n |> ${0}\n\n" ]
[ 29, 0 ]
[]
[]
[ "keyboard_shortcuts", "r", "rstudio" ]
stackoverflow_0068667933_keyboard_shortcuts_r_rstudio.txt
Q: Android webView - Intercept all request - Url filtering based on api response I'm trying to intercept webview requests and filter them based on an API response. I'm using a viewModel who has a public onFilter method that calls the API via a repository: private val _filterResult = MutableLiveData<WebFilterModel>() val filterResult: LiveData<WebFilterModel> = _filterResult fun onFilter(url: String) { viewModelScope.launch(Dispatchers.Main) { val result = filterUseCase.invoke(url) if (result.isSuccessful) { Log.d("filter", "result onFilter: " + result.body()!!.result) _filterResult.value = result.body() } } } The viewModel has a variable of type LiveData which is observed in the private method for my custom webView client, this method called filterRequest is used in the web client's overridden method, shouldInterceptRequest. At time, the shouldOverrideLoading method returns false: @OptIn(DelicateCoroutinesApi::class) private fun filterRequest(view: WebView, request: WebResourceRequest?) { GlobalScope.launch(Dispatchers.Main) { viewModel.onFilter(request!!.url.toString()) viewModel.filterResult.observe(activity, Observer{ if (it.result == "ok") { shouldBlock = false view.loadUrl(it.loadFilterUrl) Log.d("filter", "filterRequest ok") } else { view.post(Runnable { view.stopLoading() }) val url = "https://www.google.com" shouldBlock = true view.post(Runnable { view.loadUrl(url) }) Log.d("filter", "filterRequest no") } }) } } override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { return false } override fun shouldInterceptRequest( view: WebView?, request: WebResourceRequest? ): WebResourceResponse? { var webResourceResponse: WebResourceResponse? = null filterRequest(view!!, request) if (shouldBlock) { Log.d("filtro", "interceptRequest NULL") webResourceResponse = WebResourceResponse("text/javascript", "UTF-8", null) } if (!shouldBlock) { view!!.post(Runnable { view.loadUrl(BrowserAPIProvider.filter.loadFilterUrl) webResourceResponse = null }) } return webResourceResponse } The main problem I'm having is that the calls are produced in an infinite loop, the web doesn't load and many requests are made per second. This is the current state of the code, however some lines of code come from changes and tests, I don't know how to develop the asynchrony with the api in the webview overridden methods, this is the biggest problem. I would appreciate any kind of help and if you need more code I'll edit the question and copy it. Thank you very much in advance for your help. A: I have come to this solution I think its not the best but it works for the purpose The custom web client stops loading and calls the api: var shouldBlock: Boolean? = null private var yetFilter = false private fun filterRequest(view: WebView, request: WebResourceRequest?) { view.post(Runnable { view.stopLoading() }) viewModel.onFilter(request!!.url.toString()) yetFilter = true } override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { yetFilter = false return false } override fun shouldInterceptRequest( view: WebView?, request: WebResourceRequest? ): WebResourceResponse? { var webResourceResponse: WebResourceResponse? = null if (!yetFilter) { filterRequest(view!!, request) } if (shouldBlock != null) { if (shouldBlock == true) { Log.d("filter", "interceptRequest NULL") webResourceResponse = null } else { webResourceResponse = super.shouldInterceptRequest(view, request) Log.d("filter", "interceptRequest LOAD OK") } } return webResourceResponse } when the fragment that stores the webview receives the response from the api through the LiveData observer, it loads according to the response: viewModel.filterResult.observe(viewLifecycleOwner, Observer { if (it.result == "ok") { objectWebClient.shouldBlock = false binding.webView.loadUrl(it.loadFilterUrl) Log.d("filter", "filterRequest ok") } else { val url = "https://www.google.com" objectWebClient.shouldBlock = true binding.webView.loadUrl(url) Log.d("filter", "filterRequest no") } objectWebClient.shouldBlock = null }) When a web request is started again the variable is set again to allow a single call in the shouldOverrideUrlLoading method. I know it's not the best solution but it seems to work. Any help to improve the logic of the code is welcome!
Android webView - Intercept all request - Url filtering based on api response
I'm trying to intercept webview requests and filter them based on an API response. I'm using a viewModel who has a public onFilter method that calls the API via a repository: private val _filterResult = MutableLiveData<WebFilterModel>() val filterResult: LiveData<WebFilterModel> = _filterResult fun onFilter(url: String) { viewModelScope.launch(Dispatchers.Main) { val result = filterUseCase.invoke(url) if (result.isSuccessful) { Log.d("filter", "result onFilter: " + result.body()!!.result) _filterResult.value = result.body() } } } The viewModel has a variable of type LiveData which is observed in the private method for my custom webView client, this method called filterRequest is used in the web client's overridden method, shouldInterceptRequest. At time, the shouldOverrideLoading method returns false: @OptIn(DelicateCoroutinesApi::class) private fun filterRequest(view: WebView, request: WebResourceRequest?) { GlobalScope.launch(Dispatchers.Main) { viewModel.onFilter(request!!.url.toString()) viewModel.filterResult.observe(activity, Observer{ if (it.result == "ok") { shouldBlock = false view.loadUrl(it.loadFilterUrl) Log.d("filter", "filterRequest ok") } else { view.post(Runnable { view.stopLoading() }) val url = "https://www.google.com" shouldBlock = true view.post(Runnable { view.loadUrl(url) }) Log.d("filter", "filterRequest no") } }) } } override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { return false } override fun shouldInterceptRequest( view: WebView?, request: WebResourceRequest? ): WebResourceResponse? { var webResourceResponse: WebResourceResponse? = null filterRequest(view!!, request) if (shouldBlock) { Log.d("filtro", "interceptRequest NULL") webResourceResponse = WebResourceResponse("text/javascript", "UTF-8", null) } if (!shouldBlock) { view!!.post(Runnable { view.loadUrl(BrowserAPIProvider.filter.loadFilterUrl) webResourceResponse = null }) } return webResourceResponse } The main problem I'm having is that the calls are produced in an infinite loop, the web doesn't load and many requests are made per second. This is the current state of the code, however some lines of code come from changes and tests, I don't know how to develop the asynchrony with the api in the webview overridden methods, this is the biggest problem. I would appreciate any kind of help and if you need more code I'll edit the question and copy it. Thank you very much in advance for your help.
[ "I have come to this solution I think its not the best but it works for the purpose\nThe custom web client stops loading and calls the api:\n var shouldBlock: Boolean? = null\n private var yetFilter = false\n\n\n private fun filterRequest(view: WebView, request: WebResourceRequest?) {\n view.post(Runnable {\n view.stopLoading()\n })\n viewModel.onFilter(request!!.url.toString())\n yetFilter = true\n }\n\n override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {\n yetFilter = false\n return false\n }\n\n override fun shouldInterceptRequest(\n view: WebView?,\n request: WebResourceRequest?\n ): WebResourceResponse? {\n var webResourceResponse: WebResourceResponse? = null\n\n if (!yetFilter) {\n filterRequest(view!!, request)\n }\n if (shouldBlock != null) {\n if (shouldBlock == true) {\n Log.d(\"filter\", \"interceptRequest NULL\")\n webResourceResponse = null\n } else {\n webResourceResponse = super.shouldInterceptRequest(view, request)\n Log.d(\"filter\", \"interceptRequest LOAD OK\")\n }\n }\n return webResourceResponse\n }\n\nwhen the fragment that stores the webview receives the response from the api through the LiveData observer, it loads according to the response:\n viewModel.filterResult.observe(viewLifecycleOwner, Observer {\n if (it.result == \"ok\") {\n objectWebClient.shouldBlock = false\n binding.webView.loadUrl(it.loadFilterUrl)\n Log.d(\"filter\", \"filterRequest ok\")\n } else {\n val url = \"https://www.google.com\"\n objectWebClient.shouldBlock = true\n binding.webView.loadUrl(url)\n Log.d(\"filter\", \"filterRequest no\")\n }\n objectWebClient.shouldBlock = null\n }) \n\nWhen a web request is started again the variable is set again to allow a single call in the shouldOverrideUrlLoading method. I know it's not the best solution but it seems to work.\nAny help to improve the logic of the code is welcome!\n" ]
[ 0 ]
[]
[]
[ "android", "kotlin", "kotlin_coroutines", "retrofit2", "webview" ]
stackoverflow_0074667969_android_kotlin_kotlin_coroutines_retrofit2_webview.txt
Q: Generate pdf from HTML in div using Javascript I have the following html code: <!DOCTYPE html> <html> <body> <p>don't print this to pdf</p> <div id="pdf"> <p><font size="3" color="red">print this to pdf</font></p> </div> </body> </html> All I want to do is to print to pdf whatever is found in the div with an id of "pdf". This must be done using JavaScript. The "pdf" document should then be automatically downloaded with a filename of "foobar.pdf" I've been using jspdf to do this, but the only function it has is "text" which accepts only string values. I want to submit HTML to jspdf, not text. A: jsPDF is able to use plugins. In order to enable it to print HTML, you have to include certain plugins and therefore have to do the following: Go to https://github.com/MrRio/jsPDF and download the latest Version. Include the following Scripts in your project: jspdf.js jspdf.plugin.from_html.js jspdf.plugin.split_text_to_size.js jspdf.plugin.standard_fonts_metrics.js If you want to ignore certain elements, you have to mark them with an ID, which you can then ignore in a special element handler of jsPDF. Therefore your HTML should look like this: <!DOCTYPE html> <html> <body> <p id="ignorePDF">don't print this to pdf</p> <div> <p><font size="3" color="red">print this to pdf</font></p> </div> </body> </html> Then you use the following JavaScript code to open the created PDF in a PopUp: var doc = new jsPDF(); var elementHandler = { '#ignorePDF': function (element, renderer) { return true; } }; var source = window.document.getElementsByTagName("body")[0]; doc.fromHTML( source, 15, 15, { 'width': 180,'elementHandlers': elementHandler }); doc.output("dataurlnewwindow"); For me this created a nice and tidy PDF that only included the line 'print this to pdf'. Please note that the special element handlers only deal with IDs in the current version, which is also stated in a GitHub Issue. It states: Because the matching is done against every element in the node tree, my desire was to make it as fast as possible. In that case, it meant "Only element IDs are matched" The element IDs are still done in jQuery style "#id", but it does not mean that all jQuery selectors are supported. Therefore replacing '#ignorePDF' with class selectors like '.ignorePDF' did not work for me. Instead you will have to add the same handler for each and every element, which you want to ignore like: var elementHandler = { '#ignoreElement': function (element, renderer) { return true; }, '#anotherIdToBeIgnored': function (element, renderer) { return true; } }; From the examples it is also stated that it is possible to select tags like 'a' or 'li'. That might be a little bit to unrestrictive for the most usecases though: We support special element handlers. Register them with jQuery-style ID selector for either ID or node name. ("#iAmID", "div", "span" etc.) There is no support for any other type of selectors (class, of compound) at this time. One very important thing to add is that you lose all your style information (CSS). Luckily jsPDF is able to nicely format h1, h2, h3 etc., which was enough for my purposes. Additionally it will only print text within text nodes, which means that it will not print the values of textareas and the like. Example: <body> <ul> <!-- This is printed as the element contains a textnode --> <li>Print me!</li> </ul> <div> <!-- This is not printed because jsPDF doesn't deal with the value attribute --> <input type="textarea" value="Please print me, too!"> </div> </body> A: This is the simple solution. This works for me. You can use the javascript print concept and simple save this as pdf. <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> $("#btnPrint").live("click", function () { var divContents = $("#dvContainer").html(); var printWindow = window.open('', '', 'height=400,width=800'); printWindow.document.write('<html><head><title>DIV Contents</title>'); printWindow.document.write('</head><body >'); printWindow.document.write(divContents); printWindow.document.write('</body></html>'); printWindow.document.close(); printWindow.print(); }); </script> </head> <body> <form id="form1"> <div id="dvContainer"> This content needs to be printed. </div> <input type="button" value="Print Div Contents" id="btnPrint" /> </form> </body> </html> A: No depenencies, pure JS To add CSS or images - do not use relative URLs, use full URLs http://...domain.../path.css or so. It creates separate HTML document and it has no context of main thing. you can also embed images as base64 This served me for years now: export default function printDiv({divId, title}) { let mywindow = window.open('', 'PRINT', 'height=650,width=900,top=100,left=150'); mywindow.document.write(`<html><head><title>${title}</title>`); mywindow.document.write('</head><body >'); mywindow.document.write(document.getElementById(divId).innerHTML); mywindow.document.write('</body></html>'); mywindow.document.close(); // necessary for IE >= 10 mywindow.focus(); // necessary for IE >= 10*/ mywindow.print(); mywindow.close(); return true; } Of course this will open print dialog and user will have to know she/he can select print to pdf option, to get pdf. There may be printer pre-selected and if user confirms may get this document actually printed. To avoid such situation and to provide PDF without any extras, you need to make PDF file. Probably on the server side. You could have tiny html page with invoice only and convert it to PDF file with headless chrome. It's super easy with puppeteer. No need to install/config chrome, just install npm package puppeteer (managed by chrome team) and run it. Keep in mind this will actually launch real chrome just w/o GUI, so you need to have some RAM & CPU for this. Most servers will be fine with low enough traffic. Here is code sample but this must run on the BACKEND. Nodejs. Also it's slow call, it's resources intensive call. You should run it NOT on api call but e.g. after invoice was created - create pdf for it and store, if pdf was not generated yet, just show message to try again in couple minutes. const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://your-domain.com/path-to-invoice', { waitUntil: 'networkidle2', }); await page.pdf({ path: 'invoice-file-path.pdf', format: 'a4' }); await browser.close(); })(); Learn more here: https://pptr.dev/ A: if you need to downloadable pdf of a specific page just add button like this <h4 onclick="window.print();"> Print </h4> use window.print() to print your all page not just a div A: You can use autoPrint() and set output to 'dataurlnewwindow' like this: function printPDF() { var printDoc = new jsPDF(); printDoc.fromHTML($('#pdf').get(0), 10, 10, {'width': 180}); printDoc.autoPrint(); printDoc.output("dataurlnewwindow"); // this opens a new popup, after this the PDF opens the print window view but there are browser inconsistencies with how this is handled } A: As mentioned, you should use jsPDF and html2canvas. I've also found a function inside issues of jsPDF which splits automatically your pdf into multiple pages (sources) function makePDF() { var quotes = document.getElementById('container-fluid'); html2canvas(quotes, { onrendered: function(canvas) { //! MAKE YOUR PDF var pdf = new jsPDF('p', 'pt', 'letter'); for (var i = 0; i <= quotes.clientHeight/980; i++) { //! This is all just html2canvas stuff var srcImg = canvas; var sX = 0; var sY = 980*i; // start 980 pixels down for every new page var sWidth = 900; var sHeight = 980; var dX = 0; var dY = 0; var dWidth = 900; var dHeight = 980; window.onePageCanvas = document.createElement("canvas"); onePageCanvas.setAttribute('width', 900); onePageCanvas.setAttribute('height', 980); var ctx = onePageCanvas.getContext('2d'); // details on this usage of this function: // https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images#Slicing ctx.drawImage(srcImg,sX,sY,sWidth,sHeight,dX,dY,dWidth,dHeight); // document.body.appendChild(canvas); var canvasDataURL = onePageCanvas.toDataURL("image/png", 1.0); var width = onePageCanvas.width; var height = onePageCanvas.clientHeight; //! If we're on anything other than the first page, // add another page if (i > 0) { pdf.addPage(612, 791); //8.5" x 11" in pts (in*72) } //! now we declare that we're working on that page pdf.setPage(i+1); //! now we add content to that page! pdf.addImage(canvasDataURL, 'PNG', 20, 40, (width*.62), (height*.62)); } //! after the for loop is finished running, we save the pdf. pdf.save('test.pdf'); } }); } A: i use jspdf and html2canvas for css rendering and i export content of specific div as this is my code $(document).ready(function () { let btn=$('#c-oreder-preview'); btn.text('download'); btn.on('click',()=> { $('#c-invoice').modal('show'); setTimeout(function () { html2canvas(document.querySelector("#c-print")).then(canvas => { //$("#previewBeforeDownload").html(canvas); var imgData = canvas.toDataURL("image/jpeg",1); var pdf = new jsPDF("p", "mm", "a4"); var pageWidth = pdf.internal.pageSize.getWidth(); var pageHeight = pdf.internal.pageSize.getHeight(); var imageWidth = canvas.width; var imageHeight = canvas.height; var ratio = imageWidth/imageHeight >= pageWidth/pageHeight ? pageWidth/imageWidth : pageHeight/imageHeight; //pdf = new jsPDF(this.state.orientation, undefined, format); pdf.addImage(imgData, 'JPEG', 0, 0, imageWidth * ratio, imageHeight * ratio); pdf.save("invoice.pdf"); //$("#previewBeforeDownload").hide(); $('#c-invoice').modal('hide'); }); },500); }); }); A: One way is to use window.print() function. Which does not require any library Pros 1.No external library require. 2.We can print only selected parts of body also. 3.No css conflicts and js issues. 4.Core html/js functionality ---Simply add below code CSS to @media print { body * { visibility: hidden; // part to hide at the time of print -webkit-print-color-adjust: exact !important; // not necessary use if colors not visible } #printBtn { visibility: hidden !important; // To hide } #page-wrapper * { visibility: visible; // Print only required part text-align: left; -webkit-print-color-adjust: exact !important; } } JS code - Call bewlow function on btn click $scope.printWindow = function () { window.print() } Note: Use !important in every css object Example - .legend { background: #9DD2E2 !important; } A: Use pdfMake.js and this Gist. (I found the Gist here along with a link to the package html-to-pdfmake, which I end up not using for now.) After npm install pdfmake and saving the Gist in htmlToPdf.js I use it like this: const pdfMakeX = require('pdfmake/build/pdfmake.js'); const pdfFontsX = require('pdfmake-unicode/dist/pdfmake-unicode.js'); pdfMakeX.vfs = pdfFontsX.pdfMake.vfs; import * as pdfMake from 'pdfmake/build/pdfmake'; import htmlToPdf from './htmlToPdf.js'; var docDef = htmlToPdf(`<b>Sample</b>`); pdfMake.createPdf({content:docDef}).download('sample.pdf'); Remarks: My use case is to create the relevant html from a markdown document (with markdown-it) and subsequently generating the pdf, and uploading its binary content (which I can get with pdfMake's getBuffer() function), all from the browser. The generated pdf turns out to be nicer for this kind of html than with other solutions I have tried. I am dissatisfied with the results I got from jsPDF.fromHTML() suggested in the accepted answer, as that solution gets easily confused by special characters in my HTML that apparently are interpreted as a sort of markup and totally mess up the resulting PDF. Using canvas based solutions (like the deprecated jsPDF.from_html() function, not to be confused with the one from the accepted answer) is not an option for me since I want the text in the generated PDF to be pasteable, whereas canvas based solutions generate bitmap based PDFs. Direct markdown to pdf converters like md-to-pdf are server side only and would not work for me. Using the printing functionality of the browser would not work for me as I do not want to display the generated PDF but upload its binary content. A: I was able to get jsPDF to print dynamically created tables from a div. $(document).ready(function() { $("#pdfDiv").click(function() { var pdf = new jsPDF('p','pt','letter'); var specialElementHandlers = { '#rentalListCan': function (element, renderer) { return true; } }; pdf.addHTML($('#rentalListCan').first(), function() { pdf.save("caravan.pdf"); }); }); }); Works great with Chrome and Firefox... formatting is all blown up in IE. I also included these: <script src="js/jspdf.js"></script> <script src="js/jspdf.plugin.from_html.js"></script> <script src="js/jspdf.plugin.addhtml.js"></script> <script src="//mrrio.github.io/jsPDF/dist/jspdf.debug.js"></script> <script src="http://html2canvas.hertzen.com/build/html2canvas.js"></script> <script type="text/javascript" src="./libs/FileSaver.js/FileSaver.js"></script> <script type="text/javascript" src="./libs/Blob.js/Blob.js"></script> <script type="text/javascript" src="./libs/deflate.js"></script> <script type="text/javascript" src="./libs/adler32cs.js/adler32cs.js"></script> <script type="text/javascript" src="js/jspdf.plugin.addimage.js"></script> <script type="text/javascript" src="js/jspdf.plugin.sillysvgrenderer.js"></script> <script type="text/javascript" src="js/jspdf.plugin.split_text_to_size.js"></script> <script type="text/javascript" src="js/jspdf.plugin.standard_fonts_metrics.js"></script> A: If you want to export a table, you can take a look at this export sample provided by the Shield UI Grid widget. It is done by extending the configuration like this: ... exportOptions: { proxy: "/filesaver/save", pdf: { fileName: "shieldui-export", author: "John Smith", dataSource: { data: gridData }, readDataSource: true, header: { cells: [ { field: "id", title: "ID", width: 50 }, { field: "name", title: "Person Name", width: 100 }, { field: "company", title: "Company Name", width: 100 }, { field: "email", title: "Email Address" } ] } } } ... A: This example works great. <button onclick="genPDF()">Generate PDF</button> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script> <script> function genPDF() { var doc = new jsPDF(); doc.text(20, 20, 'Hello world!'); doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.'); doc.addPage(); doc.text(20, 20, 'Do you like that?'); doc.save('Test.pdf'); } </script> A: Dissatisfied with the rendering of html2canvas and lack of modern CSS3/JS and print specific CSS support of pdfMake's outdated version of WebKit... Here's a theoretical solution, it's headless and can render pages faithfully, supports page breaks, margins, different page sizes and can be automated. You can even render WebGl to PDF. Chrome has a devtools protocol... which has a printtoPDF function Excerpt: https://gitlab.com/-/snippets/new Official 20k-SLOC spec: https://github.com/ChromeDevTools/devtools-protocol/blob/master/json/browser_protocol.json You can use node and https://github.com/GoogleChrome/chrome-launcher to run chrome headless... wait for it to render. Profit printToPDF command you'd run on chrome_devtools protocol: printToPDF({ printBackground: false, pageWidth: 8.5, pageHeight: 11, transferMode: "ReturnAsStream" // or ReturnAsBase64 }) A: 2022 Answer: To generate PDF from HTML Element and prompt to save file: import { jsPDF } from "jsPDF" function generatePDF() { const doc = new jsPDF({ unit: 'pt' }) // create jsPDF object const pdfElement = document.getElementById('pdf') // HTML element to be converted to PDF doc.html(pdfElement, { callback: (pdf) => { pdf.save('MyPdfFile.pdf') }, margin: 32, // optional: page margin // optional: other HTMLOptions }) } <button onclick="generatePDF()">Save PDF</button> ... To preview PDF without printing: doc.html(pdfElement, { callback: (pdf) => { const myPdfData = pdf.output('datauristring') } }) <embed type="application/pdf" src={myPdfData} /> ... For more HTMLOptions: https://github.com/parallax/jsPDF/blob/master/types/index.d.ts A: To capture div as PDF you can use https://grabz.it solution. It's got a JavaScript API which is easy and flexible and will allow you to capture the contents of a single HTML element such as a div or a span In order to implement it you will need to first get an app key and secret and download the (free) SDK. And now an example. Let's say you have the HTML: <div id="features"> <h4>Acme Camera</h4> <label>Price</label>$399<br /> <label>Rating</label>4.5 out of 5 </div> <p>Cras ut velit sed purus porttitor aliquam. Nulla tristique magna ac libero tempor, ac vestibulum felisvulput ate. Nam ut velit eget risus porttitor tristique at ac diam. Sed nisi risus, rutrum a metus suscipit, euismod tristique nulla. Etiam venenatis rutrum risus at blandit. In hac habitasse platea dictumst. Suspendisse potenti. Phasellus eget vehicula felis.</p> To capture what is under the features id you will need to: //add the sdk <script type="text/javascript" src="grabzit.min.js"></script> <script type="text/javascript"> //login with your key and secret. GrabzIt("KEY", "SECRET").ConvertURL("http://www.example.com/my-page.html", {"target": "#features", "format": "pdf"}).Create(); </script> Please note the target: #feature. #feature is you CSS selector, like in the previous example. Now, when the page is loaded an image screenshot will now be created in the same location as the script tag, which will contain all of the contents of the features div and nothing else. The are other configuration and customization you can do to the div-screenshot mechanism, please check them out here A: The following method works fine for my case. Hide additional parts for a page like the following example @media print{ body{ -webkit-print-color-adjust: exact; // if you want to enable graphics color-adjust: exact !important; // if you want to enable graphics print-color-adjust: exact !important; // if you want to enable graphics * { visibility: hidden; margin:0; padding:0 } .print_area, .print_area *{ visibility: visible; } .print_area{ margin: 0; align: center; } .pageBreak { page-break-before : always; // If you want to skip next page page-break-inside: avoid; // If you want to skip next page } } @page { size: A4; margin:0mm; // set page layout background-color: #fff; } } Use the javascript print function to print execution. <button onclick="window.print()">Print</button>
Generate pdf from HTML in div using Javascript
I have the following html code: <!DOCTYPE html> <html> <body> <p>don't print this to pdf</p> <div id="pdf"> <p><font size="3" color="red">print this to pdf</font></p> </div> </body> </html> All I want to do is to print to pdf whatever is found in the div with an id of "pdf". This must be done using JavaScript. The "pdf" document should then be automatically downloaded with a filename of "foobar.pdf" I've been using jspdf to do this, but the only function it has is "text" which accepts only string values. I want to submit HTML to jspdf, not text.
[ "jsPDF is able to use plugins. In order to enable it to print HTML, you have to include certain plugins and therefore have to do the following:\n\nGo to https://github.com/MrRio/jsPDF and download the latest Version.\nInclude the following Scripts in your project:\n\n\njspdf.js\njspdf.plugin.from_html.js\njspdf.plugin.split_text_to_size.js\njspdf.plugin.standard_fonts_metrics.js\n\n\nIf you want to ignore certain elements, you have to mark them with an ID, which you can then ignore in a special element handler of jsPDF. Therefore your HTML should look like this:\n<!DOCTYPE html>\n<html>\n <body>\n <p id=\"ignorePDF\">don't print this to pdf</p>\n <div>\n <p><font size=\"3\" color=\"red\">print this to pdf</font></p>\n </div>\n </body>\n</html>\n\nThen you use the following JavaScript code to open the created PDF in a PopUp:\nvar doc = new jsPDF(); \nvar elementHandler = {\n '#ignorePDF': function (element, renderer) {\n return true;\n }\n};\nvar source = window.document.getElementsByTagName(\"body\")[0];\ndoc.fromHTML(\n source,\n 15,\n 15,\n {\n 'width': 180,'elementHandlers': elementHandler\n });\n\ndoc.output(\"dataurlnewwindow\");\n\nFor me this created a nice and tidy PDF that only included the line 'print this to pdf'.\nPlease note that the special element handlers only deal with IDs in the current version, which is also stated in a GitHub Issue. It states: \n\nBecause the matching is done against every element in the node tree, my desire was to make it as fast as possible. In that case, it meant \"Only element IDs are matched\" The element IDs are still done in jQuery style \"#id\", but it does not mean that all jQuery selectors are supported.\n\nTherefore replacing '#ignorePDF' with class selectors like '.ignorePDF' did not work for me. Instead you will have to add the same handler for each and every element, which you want to ignore like:\nvar elementHandler = {\n '#ignoreElement': function (element, renderer) {\n return true;\n },\n '#anotherIdToBeIgnored': function (element, renderer) {\n return true;\n }\n};\n\nFrom the examples it is also stated that it is possible to select tags like 'a' or 'li'. That might be a little bit to unrestrictive for the most usecases though:\n\nWe support special element handlers. Register them with jQuery-style\n ID selector for either ID or node name. (\"#iAmID\", \"div\", \"span\" etc.)\n There is no support for any other type of selectors (class, of\n compound) at this time.\n\nOne very important thing to add is that you lose all your style information (CSS). Luckily jsPDF is able to nicely format h1, h2, h3 etc., which was enough for my purposes. Additionally it will only print text within text nodes, which means that it will not print the values of textareas and the like. Example:\n<body>\n <ul>\n <!-- This is printed as the element contains a textnode --> \n <li>Print me!</li>\n </ul>\n <div>\n <!-- This is not printed because jsPDF doesn't deal with the value attribute -->\n <input type=\"textarea\" value=\"Please print me, too!\">\n </div>\n</body>\n\n", "This is the simple solution. This works for me. You can use the javascript print concept and simple save this as pdf.\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n <title></title>\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js\"></script>\n <script type=\"text/javascript\">\n $(\"#btnPrint\").live(\"click\", function () {\n var divContents = $(\"#dvContainer\").html();\n var printWindow = window.open('', '', 'height=400,width=800');\n printWindow.document.write('<html><head><title>DIV Contents</title>');\n printWindow.document.write('</head><body >');\n printWindow.document.write(divContents);\n printWindow.document.write('</body></html>');\n printWindow.document.close();\n printWindow.print();\n });\n </script>\n</head>\n<body>\n <form id=\"form1\">\n <div id=\"dvContainer\">\n This content needs to be printed.\n </div>\n <input type=\"button\" value=\"Print Div Contents\" id=\"btnPrint\" />\n </form>\n</body>\n</html>\n\n", "\nNo depenencies, pure JS\nTo add CSS or images - do not use relative URLs, use full URLs http://...domain.../path.css or so. It creates separate HTML document and it has no context of main thing.\nyou can also embed images as base64\n\nThis served me for years now:\nexport default function printDiv({divId, title}) {\n let mywindow = window.open('', 'PRINT', 'height=650,width=900,top=100,left=150');\n\n mywindow.document.write(`<html><head><title>${title}</title>`);\n mywindow.document.write('</head><body >');\n mywindow.document.write(document.getElementById(divId).innerHTML);\n mywindow.document.write('</body></html>');\n\n mywindow.document.close(); // necessary for IE >= 10\n mywindow.focus(); // necessary for IE >= 10*/\n\n mywindow.print();\n mywindow.close();\n\n return true;\n}\n\nOf course this will open print dialog and user will have to know she/he can select print to pdf option, to get pdf. There may be printer pre-selected and if user confirms may get this document actually printed. To avoid such situation and to provide PDF without any extras, you need to make PDF file. Probably on the server side. You could have tiny html page with invoice only and convert it to PDF file with headless chrome. It's super easy with puppeteer. No need to install/config chrome, just install npm package puppeteer (managed by chrome team) and run it. Keep in mind this will actually launch real chrome just w/o GUI, so you need to have some RAM & CPU for this. Most servers will be fine with low enough traffic. Here is code sample but this must run on the BACKEND. Nodejs. Also it's slow call, it's resources intensive call. You should run it NOT on api call but e.g. after invoice was created - create pdf for it and store, if pdf was not generated yet, just show message to try again in couple minutes.\nconst puppeteer = require('puppeteer');\n(async () => {\n const browser = await puppeteer.launch();\n const page = await browser.newPage();\n await page.goto('https://your-domain.com/path-to-invoice', {\n waitUntil: 'networkidle2',\n });\n await page.pdf({ path: 'invoice-file-path.pdf', format: 'a4' });\n\n await browser.close();\n})();\n\nLearn more here: https://pptr.dev/\n", "if you need to downloadable pdf of a specific page just add button like this\n<h4 onclick=\"window.print();\"> Print </h4>\n\nuse window.print() to print your all page not just a div\n", "You can use autoPrint() and set output to 'dataurlnewwindow' like this:\nfunction printPDF() {\n var printDoc = new jsPDF();\n printDoc.fromHTML($('#pdf').get(0), 10, 10, {'width': 180});\n printDoc.autoPrint();\n printDoc.output(\"dataurlnewwindow\"); // this opens a new popup, after this the PDF opens the print window view but there are browser inconsistencies with how this is handled\n}\n\n", "As mentioned, you should use jsPDF and html2canvas. I've also found a function inside issues of jsPDF which splits automatically your pdf into multiple pages (sources)\nfunction makePDF() {\n\n var quotes = document.getElementById('container-fluid');\n\n html2canvas(quotes, {\n onrendered: function(canvas) {\n\n //! MAKE YOUR PDF\n var pdf = new jsPDF('p', 'pt', 'letter');\n\n for (var i = 0; i <= quotes.clientHeight/980; i++) {\n //! This is all just html2canvas stuff\n var srcImg = canvas;\n var sX = 0;\n var sY = 980*i; // start 980 pixels down for every new page\n var sWidth = 900;\n var sHeight = 980;\n var dX = 0;\n var dY = 0;\n var dWidth = 900;\n var dHeight = 980;\n\n window.onePageCanvas = document.createElement(\"canvas\");\n onePageCanvas.setAttribute('width', 900);\n onePageCanvas.setAttribute('height', 980);\n var ctx = onePageCanvas.getContext('2d');\n // details on this usage of this function: \n // https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images#Slicing\n ctx.drawImage(srcImg,sX,sY,sWidth,sHeight,dX,dY,dWidth,dHeight);\n\n // document.body.appendChild(canvas);\n var canvasDataURL = onePageCanvas.toDataURL(\"image/png\", 1.0);\n\n var width = onePageCanvas.width;\n var height = onePageCanvas.clientHeight;\n\n //! If we're on anything other than the first page,\n // add another page\n if (i > 0) {\n pdf.addPage(612, 791); //8.5\" x 11\" in pts (in*72)\n }\n //! now we declare that we're working on that page\n pdf.setPage(i+1);\n //! now we add content to that page!\n pdf.addImage(canvasDataURL, 'PNG', 20, 40, (width*.62), (height*.62));\n\n }\n //! after the for loop is finished running, we save the pdf.\n pdf.save('test.pdf');\n }\n });\n}\n\n", "i use jspdf and html2canvas for css rendering and i export content of specific div as this is my code\n$(document).ready(function () {\n let btn=$('#c-oreder-preview');\n btn.text('download');\n btn.on('click',()=> {\n\n $('#c-invoice').modal('show');\n setTimeout(function () {\n html2canvas(document.querySelector(\"#c-print\")).then(canvas => {\n //$(\"#previewBeforeDownload\").html(canvas);\n var imgData = canvas.toDataURL(\"image/jpeg\",1);\n var pdf = new jsPDF(\"p\", \"mm\", \"a4\");\n var pageWidth = pdf.internal.pageSize.getWidth();\n var pageHeight = pdf.internal.pageSize.getHeight();\n var imageWidth = canvas.width;\n var imageHeight = canvas.height;\n\n var ratio = imageWidth/imageHeight >= pageWidth/pageHeight ? pageWidth/imageWidth : pageHeight/imageHeight;\n //pdf = new jsPDF(this.state.orientation, undefined, format);\n pdf.addImage(imgData, 'JPEG', 0, 0, imageWidth * ratio, imageHeight * ratio);\n pdf.save(\"invoice.pdf\");\n //$(\"#previewBeforeDownload\").hide();\n $('#c-invoice').modal('hide');\n });\n },500);\n\n });\n});\n\n", "One way is to use window.print() function. Which does not require any library\nPros\n1.No external library require.\n2.We can print only selected parts of body also.\n3.No css conflicts and js issues.\n4.Core html/js functionality\n---Simply add below code\nCSS to \n@media print {\n body * {\n visibility: hidden; // part to hide at the time of print\n -webkit-print-color-adjust: exact !important; // not necessary use \n if colors not visible\n }\n\n #printBtn {\n visibility: hidden !important; // To hide \n }\n\n #page-wrapper * {\n visibility: visible; // Print only required part\n text-align: left;\n -webkit-print-color-adjust: exact !important;\n }\n }\n\nJS code - Call bewlow function on btn click\n$scope.printWindow = function () {\n window.print()\n}\n\nNote: Use !important in every css object\nExample - \n.legend {\n background: #9DD2E2 !important;\n}\n\n", "Use pdfMake.js and this Gist. \n(I found the Gist here along with a link to the package html-to-pdfmake, which I end up not using for now.)\nAfter npm install pdfmake and saving the Gist in htmlToPdf.js I use it like this:\nconst pdfMakeX = require('pdfmake/build/pdfmake.js');\nconst pdfFontsX = require('pdfmake-unicode/dist/pdfmake-unicode.js');\npdfMakeX.vfs = pdfFontsX.pdfMake.vfs;\nimport * as pdfMake from 'pdfmake/build/pdfmake';\nimport htmlToPdf from './htmlToPdf.js';\n\nvar docDef = htmlToPdf(`<b>Sample</b>`);\npdfMake.createPdf({content:docDef}).download('sample.pdf');\n\nRemarks: \n\nMy use case is to create the relevant html from a markdown document (with markdown-it) and subsequently generating the pdf, and uploading its binary content (which I can get with pdfMake's getBuffer() function), all from the browser. The generated pdf turns out to be nicer for this kind of html than with other solutions I have tried.\nI am dissatisfied with the results I got from jsPDF.fromHTML() suggested in the accepted answer, as that solution gets easily confused by special characters in my HTML that apparently are interpreted as a sort of markup and totally mess up the resulting PDF.\nUsing canvas based solutions (like the deprecated jsPDF.from_html() function, not to be confused with the one from the accepted answer) is not an option for me since I want the text in the generated PDF to be pasteable, whereas canvas based solutions generate bitmap based PDFs.\nDirect markdown to pdf converters like md-to-pdf are server side only and would not work for me.\nUsing the printing functionality of the browser would not work for me as I do not want to display the generated PDF but upload its binary content. \n\n", "I was able to get jsPDF to print dynamically created tables from a div.\n$(document).ready(function() {\n\n $(\"#pdfDiv\").click(function() {\n\n var pdf = new jsPDF('p','pt','letter');\n var specialElementHandlers = {\n '#rentalListCan': function (element, renderer) {\n return true;\n }\n };\n\n pdf.addHTML($('#rentalListCan').first(), function() {\n pdf.save(\"caravan.pdf\");\n });\n });\n});\n\nWorks great with Chrome and Firefox... formatting is all blown up in IE.\nI also included these:\n<script src=\"js/jspdf.js\"></script>\n <script src=\"js/jspdf.plugin.from_html.js\"></script>\n <script src=\"js/jspdf.plugin.addhtml.js\"></script>\n <script src=\"//mrrio.github.io/jsPDF/dist/jspdf.debug.js\"></script>\n <script src=\"http://html2canvas.hertzen.com/build/html2canvas.js\"></script>\n <script type=\"text/javascript\" src=\"./libs/FileSaver.js/FileSaver.js\"></script>\n <script type=\"text/javascript\" src=\"./libs/Blob.js/Blob.js\"></script>\n <script type=\"text/javascript\" src=\"./libs/deflate.js\"></script>\n <script type=\"text/javascript\" src=\"./libs/adler32cs.js/adler32cs.js\"></script>\n\n <script type=\"text/javascript\" src=\"js/jspdf.plugin.addimage.js\"></script>\n <script type=\"text/javascript\" src=\"js/jspdf.plugin.sillysvgrenderer.js\"></script>\n <script type=\"text/javascript\" src=\"js/jspdf.plugin.split_text_to_size.js\"></script>\n <script type=\"text/javascript\" src=\"js/jspdf.plugin.standard_fonts_metrics.js\"></script>\n\n", "If you want to export a table, you can take a look at this export sample provided by the Shield UI Grid widget.\nIt is done by extending the configuration like this:\n...\nexportOptions: {\n proxy: \"/filesaver/save\",\n pdf: {\n fileName: \"shieldui-export\",\n author: \"John Smith\",\n dataSource: {\n data: gridData\n },\n readDataSource: true,\n header: {\n cells: [\n { field: \"id\", title: \"ID\", width: 50 },\n { field: \"name\", title: \"Person Name\", width: 100 },\n { field: \"company\", title: \"Company Name\", width: 100 },\n { field: \"email\", title: \"Email Address\" }\n ]\n }\n }\n}\n...\n\n", "This example works great.\n<button onclick=\"genPDF()\">Generate PDF</button>\n\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js\"></script>\n<script>\n function genPDF() {\n var doc = new jsPDF();\n doc.text(20, 20, 'Hello world!');\n doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');\n doc.addPage();\n doc.text(20, 20, 'Do you like that?');\n \n doc.save('Test.pdf');\n }\n</script>\n\n", "Dissatisfied with the rendering of html2canvas and lack of modern CSS3/JS and print specific CSS support of pdfMake's outdated version of WebKit...\nHere's a theoretical solution, it's headless and can render pages faithfully, supports page breaks, margins, different page sizes and can be automated. You can even render WebGl to PDF.\n\nChrome has a devtools protocol... which has a printtoPDF function\n\nExcerpt: https://gitlab.com/-/snippets/new\nOfficial 20k-SLOC spec: https://github.com/ChromeDevTools/devtools-protocol/blob/master/json/browser_protocol.json\n\n\nYou can use node and https://github.com/GoogleChrome/chrome-launcher to run chrome headless... wait for it to render.\nProfit\n\nprintToPDF command you'd run on chrome_devtools protocol:\nprintToPDF({\n printBackground: false,\n pageWidth: 8.5,\n pageHeight: 11,\n transferMode: \"ReturnAsStream\" // or ReturnAsBase64\n})\n\n\n", "2022 Answer:\nTo generate PDF from HTML Element and prompt to save file:\nimport { jsPDF } from \"jsPDF\"\n\nfunction generatePDF() {\n const doc = new jsPDF({ unit: 'pt' }) // create jsPDF object\n const pdfElement = document.getElementById('pdf') // HTML element to be converted to PDF\n\n doc.html(pdfElement, {\n callback: (pdf) => {\n pdf.save('MyPdfFile.pdf')\n },\n margin: 32, // optional: page margin\n // optional: other HTMLOptions\n })\n}\n\n<button onclick=\"generatePDF()\">Save PDF</button>\n\n...\nTo preview PDF without printing:\ndoc.html(pdfElement, {\n callback: (pdf) => {\n const myPdfData = pdf.output('datauristring')\n }\n})\n\n<embed type=\"application/pdf\" src={myPdfData} />\n\n...\nFor more HTMLOptions:\nhttps://github.com/parallax/jsPDF/blob/master/types/index.d.ts\n", "To capture div as PDF you can use https://grabz.it solution. It's got a JavaScript API which is easy and flexible and will allow you to capture the contents of a single HTML element such as a div or a span\nIn order to implement it you will need to first get an app key and secret and download the (free) SDK. \nAnd now an example.\nLet's say you have the HTML:\n<div id=\"features\">\n <h4>Acme Camera</h4>\n <label>Price</label>$399<br />\n <label>Rating</label>4.5 out of 5\n</div>\n<p>Cras ut velit sed purus porttitor aliquam. Nulla tristique magna ac libero tempor, ac vestibulum felisvulput ate. Nam ut velit eget\nrisus porttitor tristique at ac diam. Sed nisi risus, rutrum a metus suscipit, euismod tristique nulla. Etiam venenatis rutrum risus at\nblandit. In hac habitasse platea dictumst. Suspendisse potenti. Phasellus eget vehicula felis.</p>\n\nTo capture what is under the features id you will need to:\n//add the sdk\n<script type=\"text/javascript\" src=\"grabzit.min.js\"></script>\n<script type=\"text/javascript\">\n//login with your key and secret. \nGrabzIt(\"KEY\", \"SECRET\").ConvertURL(\"http://www.example.com/my-page.html\",\n{\"target\": \"#features\", \"format\": \"pdf\"}).Create();\n</script>\n\nPlease note the target: #feature. #feature is you CSS selector, like in the previous example. Now, when the page is loaded an image screenshot will now be created in the same location as the script tag, which will contain all of the contents of the features div and nothing else.\nThe are other configuration and customization you can do to the div-screenshot mechanism, please check them out here\n", "The following method works fine for my case.\nHide additional parts for a page like the following example\n@media print{\n body{\n -webkit-print-color-adjust: exact; // if you want to enable graphics\n color-adjust: exact !important; // if you want to enable graphics\n print-color-adjust: exact !important; // if you want to enable graphics\n \n * {\n visibility: hidden;\n margin:0;\n padding:0\n }\n .print_area, .print_area *{\n visibility: visible;\n }\n .print_area{\n margin: 0;\n align: center;\n }\n .pageBreak { \n page-break-before : always; // If you want to skip next page\n page-break-inside: avoid; // If you want to skip next page\n }\n }\n @page {\n size: A4; margin:0mm; // set page layout\n background-color: #fff;\n }\n}\n\nUse the javascript print function to print execution.\n<button onclick=\"window.print()\">Print</button>\n\n" ]
[ 307, 81, 25, 20, 18, 18, 16, 11, 6, 3, 1, 1, 1, 1, 0, 0 ]
[ "any one try this\n (function () { \n var \n form = $('.form'), \n cache_width = form.width(), \n a4 = [595.28, 841.89]; // for a4 size paper width and height \n\n $('#create_pdf').on('click', function () { \n $('body').scrollTop(0); \n createPDF(); \n }); \n //create pdf \n function createPDF() { \n getCanvas().then(function (canvas) { \n var \n img = canvas.toDataURL(\"image/png\"), \n doc = new jsPDF({ \n unit: 'px', \n format: 'a4' \n }); \n doc.addImage(img, 'JPEG', 20, 20); \n doc.save('Bhavdip-html-to-pdf.pdf'); \n form.width(cache_width); \n }); \n } \n\n // create canvas object \n function getCanvas() { \n form.width((a4[0] * 1.33333) - 80).css('max-width', 'none'); \n return html2canvas(form, { \n imageTimeout: 2000, \n removeContainer: true \n }); \n } \n\n }()); \n\n" ]
[ -1 ]
[ "javascript", "jspdf" ]
stackoverflow_0018191893_javascript_jspdf.txt
Q: Python Threading vs Multiprocessing to improve REST API responsiveness "fire and forget" tasks I am somewhat new to both threading and multiprocessing in Python, as well as dealing with the concept of the GIL. I have a situation where I have time consuming fire and forget tasks that I need the server to run, but the server should immediately reply to the client and basically be like "okay, your thing was submitted" so that the client does not hang waiting for the thing to complete. An example of what one of the "things" might do is pull down some data from a database or two, compare that data, and then write the result to another database. The databases are remote, not locally on the same host as the server itself. Another example, is crunching some data and then sending a text as a result of that. The client does not care about the data, but someone will receive a text later with some information that is the result of the data crunching from the various dictionaries and database entries. However, there could be many such requests pouring in from many clients. The goal here is to spawn a thread, or process that essentially kills itself because we don't care at all about returning any data from it. At a glance, my understanding is that both multiprocessing and threading can achieve similar results for this use case. My main concerns are that I can immediately launch the function to go do its own thing and return to the client quickly so it does not hang. There are many, many requests coming in simultaneously from many, many clients in this scenario. As a result, my understanding is that multiprocessing may be better, so that these tasks would not need to be executed as sequential threads because of the GIL. However, I am unsure of how to make the processes end themselves when they are done with their task rather than needing to wait for them. An example of the problem @route('/api/example', methods=["POST"]) def example_request(self, request): request_data = request.get_json() crunch_data_and_send_text(request_data) # Takes maybe 5-10 seconds, doesn't return data return # Return to client. Would like to return to client immediately rather than waiting Would threading or multiprocessing be better here? And how can I make the process (or thread) .join() itself effectively when it is done rather than needing to join it before I can return to the client. I have also considered asyncio which I think would allow something that would also improve this, but the existing codebase I have inherited is so large that it is infeasible to rewrite in async for the time being, and library replacements may need to be found in that case, so it is not an option. #Threading from threading import Thread @route('/api/example', methods=["POST"]) def example_request(self, request): request_data = request.get_json() fire_and_forget = Thread(target = crunch_data_and_send_text, args=(request_data,)) fire_and_forget.start() return # Return to client. Would like to return to client immediately rather than waiting # Multiprocessing from multiprocessing import Process @route('/api/example', methods=["POST"]) def example_request(self, request): request_data = request.get_json() fire_and_forget = Process(target = crunch_data_and_send_text, args=(request_data,)) fire_and_forget.start() return # Return to client. Would like to return to client immediately rather than waiting Which of these is better for this use case? Is there a way I can have them .join() themselves automatically when they finish rather than needing to actually sit here in the function and wait for them to complete before returning to the client? To be clear, asyncio is unfortunately NOT an option for me. A: I suggest using Advance Python Scheduler. Instead of running your function in a thread, schedule it to run and immediately return to client. After setting up your flask app, setup Flask-APScheduler and then schedule your function to run in the background. from apscheduler.schedulers.background import BackgroundScheduler scheduler = BackgroundScheduler({ --- setup the scheduler --- }) @route('/api/example', methods=["POST"]) def example_request(self, request): request_data = request.get_json() job = scheduler.add_job(crunch_data_and_send_text, 'date', run_date=datetime.utcnow()) return "The request is being processed ..." to pass arguments to crunch_data_and_send_text you can do: lambda: crunch_data_and_send_text(request_data) here is the User Guide
Python Threading vs Multiprocessing to improve REST API responsiveness "fire and forget" tasks
I am somewhat new to both threading and multiprocessing in Python, as well as dealing with the concept of the GIL. I have a situation where I have time consuming fire and forget tasks that I need the server to run, but the server should immediately reply to the client and basically be like "okay, your thing was submitted" so that the client does not hang waiting for the thing to complete. An example of what one of the "things" might do is pull down some data from a database or two, compare that data, and then write the result to another database. The databases are remote, not locally on the same host as the server itself. Another example, is crunching some data and then sending a text as a result of that. The client does not care about the data, but someone will receive a text later with some information that is the result of the data crunching from the various dictionaries and database entries. However, there could be many such requests pouring in from many clients. The goal here is to spawn a thread, or process that essentially kills itself because we don't care at all about returning any data from it. At a glance, my understanding is that both multiprocessing and threading can achieve similar results for this use case. My main concerns are that I can immediately launch the function to go do its own thing and return to the client quickly so it does not hang. There are many, many requests coming in simultaneously from many, many clients in this scenario. As a result, my understanding is that multiprocessing may be better, so that these tasks would not need to be executed as sequential threads because of the GIL. However, I am unsure of how to make the processes end themselves when they are done with their task rather than needing to wait for them. An example of the problem @route('/api/example', methods=["POST"]) def example_request(self, request): request_data = request.get_json() crunch_data_and_send_text(request_data) # Takes maybe 5-10 seconds, doesn't return data return # Return to client. Would like to return to client immediately rather than waiting Would threading or multiprocessing be better here? And how can I make the process (or thread) .join() itself effectively when it is done rather than needing to join it before I can return to the client. I have also considered asyncio which I think would allow something that would also improve this, but the existing codebase I have inherited is so large that it is infeasible to rewrite in async for the time being, and library replacements may need to be found in that case, so it is not an option. #Threading from threading import Thread @route('/api/example', methods=["POST"]) def example_request(self, request): request_data = request.get_json() fire_and_forget = Thread(target = crunch_data_and_send_text, args=(request_data,)) fire_and_forget.start() return # Return to client. Would like to return to client immediately rather than waiting # Multiprocessing from multiprocessing import Process @route('/api/example', methods=["POST"]) def example_request(self, request): request_data = request.get_json() fire_and_forget = Process(target = crunch_data_and_send_text, args=(request_data,)) fire_and_forget.start() return # Return to client. Would like to return to client immediately rather than waiting Which of these is better for this use case? Is there a way I can have them .join() themselves automatically when they finish rather than needing to actually sit here in the function and wait for them to complete before returning to the client? To be clear, asyncio is unfortunately NOT an option for me.
[ "I suggest using Advance Python Scheduler.\nInstead of running your function in a thread, schedule it to run and immediately return to client.\nAfter setting up your flask app, setup Flask-APScheduler and then schedule your function to run in the background.\nfrom apscheduler.schedulers.background import BackgroundScheduler\nscheduler = BackgroundScheduler({\n --- setup the scheduler ---\n })\n\n@route('/api/example', methods=[\"POST\"])\ndef example_request(self, request):\n request_data = request.get_json()\n job = scheduler.add_job(crunch_data_and_send_text, 'date', run_date=datetime.utcnow())\n return \"The request is being processed ...\"\n\nto pass arguments to crunch_data_and_send_text you can do:\nlambda: crunch_data_and_send_text(request_data)\n\nhere is the User Guide\n" ]
[ 1 ]
[]
[]
[ "flask", "multiprocessing", "multithreading", "optimization", "python" ]
stackoverflow_0074663169_flask_multiprocessing_multithreading_optimization_python.txt
Q: XCUITests: Can't tap element on scrollview while views are stack on each other Sample Project This is a sample project that showing the issue. It's storyboard based, but method of building interface doesn't matter. It's UIViewController with UIScrollView for entire screen and 128 pts height view that is on top of this UIScrollView. Inside scroll view there is an UIView that has 2000 pts height and UIButton in the center. Initial State After light scroll At the bottom of UIScrollView Link here: https://github.com/JakubMazur/UITestsDemo Problem I'm trying to tap this green button with XCUITest using app.buttons["Tap Me!"].tap() XCUITest get identifiers from elements on screen for entire scroll view that works fine. According to this reply on a thread on Apple Developer Forum written by Apple Framework Engineer I shouldn't scroll manually to get to the button and yes, this is partially true. What is happening when code from (1) is executed is that button is scrolled just enough to be visible on screen but it's still not hittable, because other (purple view) is on top of UIScrollView What is working If I run a test written like this: func testThatDoWorkButItsSlow() { app.scrollViews.firstMatch.swipeUp() app.buttons[buttonLabel].tap() } that is scrolling up and then looks for a button this will work, but it's slow and so inaccurate that is hardly usable. What I cannot do Disabling userInteractions on purple view. In real example I still need touches for this (purple) view. Questions Is there a way to use precise scrolling in XCTest for this case? Or is there a way to set contentOffset scrollview to other value that will make this button more centered on a screen compared to action of tap()? Or there is a way to fast scroll to the bottom (without animations) and maybe moving only up for each element? A: My recommendation here would be to use the XCUICoordinate.press(forDuration:thenDragTo:) method to scroll. https://developer.apple.com/documentation/xctest/xcuicoordinate/1615003-press You can create a XCUICoordinate for the yellow view, then drag it slightly upwards to expose the button and make it hittable. In most cases, the automatic scroll should work, but it seems like in this case a manual scroll/drag is necessary.
XCUITests: Can't tap element on scrollview while views are stack on each other
Sample Project This is a sample project that showing the issue. It's storyboard based, but method of building interface doesn't matter. It's UIViewController with UIScrollView for entire screen and 128 pts height view that is on top of this UIScrollView. Inside scroll view there is an UIView that has 2000 pts height and UIButton in the center. Initial State After light scroll At the bottom of UIScrollView Link here: https://github.com/JakubMazur/UITestsDemo Problem I'm trying to tap this green button with XCUITest using app.buttons["Tap Me!"].tap() XCUITest get identifiers from elements on screen for entire scroll view that works fine. According to this reply on a thread on Apple Developer Forum written by Apple Framework Engineer I shouldn't scroll manually to get to the button and yes, this is partially true. What is happening when code from (1) is executed is that button is scrolled just enough to be visible on screen but it's still not hittable, because other (purple view) is on top of UIScrollView What is working If I run a test written like this: func testThatDoWorkButItsSlow() { app.scrollViews.firstMatch.swipeUp() app.buttons[buttonLabel].tap() } that is scrolling up and then looks for a button this will work, but it's slow and so inaccurate that is hardly usable. What I cannot do Disabling userInteractions on purple view. In real example I still need touches for this (purple) view. Questions Is there a way to use precise scrolling in XCTest for this case? Or is there a way to set contentOffset scrollview to other value that will make this button more centered on a screen compared to action of tap()? Or there is a way to fast scroll to the bottom (without animations) and maybe moving only up for each element?
[ "My recommendation here would be to use the XCUICoordinate.press(forDuration:thenDragTo:) method to scroll.\nhttps://developer.apple.com/documentation/xctest/xcuicoordinate/1615003-press\nYou can create a XCUICoordinate for the yellow view, then drag it slightly upwards to expose the button and make it hittable.\nIn most cases, the automatic scroll should work, but it seems like in this case a manual scroll/drag is necessary.\n" ]
[ 0 ]
[]
[]
[ "ios", "swift", "xctest", "xcuitest" ]
stackoverflow_0074221274_ios_swift_xctest_xcuitest.txt
Q: How to store Picture User Profile on Database Table AspNetUsers using mvc asp.net core 5? I working on asp.net core 5 mvc web application , I face issue I can't store Picture User on database table [dbo].[AspNetUsers]. so can you tell me how to store personal picture of user on table [dbo].[AspNetUsers]. I already add new column PictureUser on table [dbo].[AspNetUsers] to store User Picture . I need to know what I will modify on controller and view to store user picture on database table . I working on Microsoft identity membership when register user my model as public class RegisterVM { public string EmailAddress { get; set; } public string Password { get; set; } public byte[] PictureUser { get; set; } } my action controller [HttpPost] public async Task<IActionResult> Register(RegisterVM registerVM) { var newUser = new ApplicationUser() { FullName = registerVM.FullName, Email = registerVM.EmailAddress, UserName = registerVM.EmailAddress, //How to add Image upload Here }; var newUserResponse = await _userManager.CreateAsync(newUser, registerVM.Password); if (newUserResponse.Succeeded) { await _signInManager.SignInAsync(newUser, isPersistent: false); return View("RegisterCompleted"); } return View(registerVM); } on view @model RegisterVM; <form asp-action="Register"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="EmailAddress" class="control-label"></label> <input asp-for="EmailAddress" class="form-control" /> <span asp-validation-for="EmailAddress" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Password" class="control-label"></label> <input asp-for="Password" class="form-control" /> <span asp-validation-for="Password" class="text-danger"></span> </div> //How to add Image upload Here <div class="form-group"> <input class="btn btn-outline-success float-right" type="submit" value="Sign up" /> </div> </form> How to add Image Upload on View And Controller Action this is Exactly my Question ? A: Inherit from the identityUser class and add the field related to the image and It is better to save the address of the image Public class user : identityuser{ //add image property Public string imgUrl {set; get;} } A: public ActionResult GetImage(int id) { // fetch image data or address from database return File(imageData, "image/jpg"); } <img src="@Url.Action("GetImage", new { id = 1 })" />
How to store Picture User Profile on Database Table AspNetUsers using mvc asp.net core 5?
I working on asp.net core 5 mvc web application , I face issue I can't store Picture User on database table [dbo].[AspNetUsers]. so can you tell me how to store personal picture of user on table [dbo].[AspNetUsers]. I already add new column PictureUser on table [dbo].[AspNetUsers] to store User Picture . I need to know what I will modify on controller and view to store user picture on database table . I working on Microsoft identity membership when register user my model as public class RegisterVM { public string EmailAddress { get; set; } public string Password { get; set; } public byte[] PictureUser { get; set; } } my action controller [HttpPost] public async Task<IActionResult> Register(RegisterVM registerVM) { var newUser = new ApplicationUser() { FullName = registerVM.FullName, Email = registerVM.EmailAddress, UserName = registerVM.EmailAddress, //How to add Image upload Here }; var newUserResponse = await _userManager.CreateAsync(newUser, registerVM.Password); if (newUserResponse.Succeeded) { await _signInManager.SignInAsync(newUser, isPersistent: false); return View("RegisterCompleted"); } return View(registerVM); } on view @model RegisterVM; <form asp-action="Register"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="EmailAddress" class="control-label"></label> <input asp-for="EmailAddress" class="form-control" /> <span asp-validation-for="EmailAddress" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Password" class="control-label"></label> <input asp-for="Password" class="form-control" /> <span asp-validation-for="Password" class="text-danger"></span> </div> //How to add Image upload Here <div class="form-group"> <input class="btn btn-outline-success float-right" type="submit" value="Sign up" /> </div> </form> How to add Image Upload on View And Controller Action this is Exactly my Question ?
[ "Inherit from the identityUser class and add the field related to the image\nand It is better to save the address of the image\nPublic class user : identityuser{\n//add image property\nPublic string imgUrl {set; get;}\n}\n", "public ActionResult GetImage(int id)\n{\n// fetch image data or address from database\nreturn File(imageData, \"image/jpg\");\n\n}\n<img src=\"@Url.Action(\"GetImage\", new { id = 1 })\" />\n" ]
[ 0, 0 ]
[]
[]
[ "asp.net5", "asp.net_core", "asp.net_core_webapi", "asp.net_mvc", "asp.net_mvc_4" ]
stackoverflow_0074661777_asp.net5_asp.net_core_asp.net_core_webapi_asp.net_mvc_asp.net_mvc_4.txt
Q: how to tell if a button hasnt been pressed button = Button(style = discord.ButtonStyle.green, emoji = ":arrow_backward:", custom_id = "button1") view = View() view.add_item(button) async def button_callback(interaction): await message.edit(content="**response 1**") button.callback = button_callback await message.edit(content="⠀⠀:watermelon:⠀⠀⠀⠀⠀:watermelon:⠀⠀⠀⠀⠀:watermelon:", view=view) i want to be able to check if the user has pressed the button, and then do something if the button hasnt been pressed after a certain amount of time. how can i check if the button hasnt been pressed? A: Try this solution # Set a timer to check if the button has not been pressed import asyncio time_limit = 15 # Set the amount of time to wait before checking async def check_button(): await asyncio.sleep(time_limit) # Wait the designated amount of time if not button.pressed: # Check if the button has not been pressed await message.edit(content="**response 2**") # Do something if the button has not been pressed # Start the timer asyncio.create_task(check_button())
how to tell if a button hasnt been pressed
button = Button(style = discord.ButtonStyle.green, emoji = ":arrow_backward:", custom_id = "button1") view = View() view.add_item(button) async def button_callback(interaction): await message.edit(content="**response 1**") button.callback = button_callback await message.edit(content="⠀⠀:watermelon:⠀⠀⠀⠀⠀:watermelon:⠀⠀⠀⠀⠀:watermelon:", view=view) i want to be able to check if the user has pressed the button, and then do something if the button hasnt been pressed after a certain amount of time. how can i check if the button hasnt been pressed?
[ "Try this solution\n\n# Set a timer to check if the button has not been pressed\nimport asyncio\n\ntime_limit = 15 # Set the amount of time to wait before checking\n\nasync def check_button():\n await asyncio.sleep(time_limit) # Wait the designated amount of time\n if not button.pressed: # Check if the button has not been pressed\n await message.edit(content=\"**response 2**\") # Do something if the button has not been pressed\n\n# Start the timer\nasyncio.create_task(check_button())\n\n" ]
[ 0 ]
[]
[]
[ "discord", "pycord", "python" ]
stackoverflow_0074678952_discord_pycord_python.txt
Q: Loop Error [No possible multiple URL? no wait? what is the error?] Im looking to improve my skills with Playwright and I am creating this code to make an "1way-3ways-final way". error: page.goto: net::ERR_ABORTED at https://computer-database.gatling.io/computers at tests\ways1-3-1.spec.ts:25:18 Can anyone help me? test('1 way to 3 and finish in 1', async ({ page }) => { await page.goto('https://large-type.com/#starting'); await page.waitForTimeout(2000); computerData.forEach(async data => { await page.goto("https://computer-database.gatling.io/computers"); await page.click("#add"); await page.fill("#name", data.name); await page.selectOption("#company", {label: data.manufacture}); await page.click("input[type='submit']"); await expect(page.locator("div.alert-message.warning")).toContainText(`Done ! Computer ${data.name} has been created`); }); await page.goto('https://large-type.com/#finished'); await page.waitForTimeout(2000); }); A: forEach runs synchronously -- the awaits in the async callbacks apply to the function they appear in, not to the surrounding function. I guess you want each iteration to kick in only when the previous one has completed all the actions being awaited. In that case, just avoid the callback, and use a straight for loop: for (const data of computerData) { await page.goto("https://computer-database.gatling.io/computers"); await page.click("#add"); await page.fill("#name", data.name); await page.selectOption("#company", {label: data.manufacture}); await page.click("input[type='submit']"); await expect(page.locator("div.alert-message.warning")).toContainText(`Done ! Computer ${data.name} has been created`); } A: Complete Data Driven Example: import { test } from "@fixtures/myFixtures"; import { expect } from "@playwright/test"; const computerData = [{ name: "Comp A", manufacture: "Tandy Corporation" }, { name: "Comp B", manufacture: "Commodore International" }, { name: "Comp C", manufacture: "Thinking Machines" }, { name: "Comp D", manufacture: "Nokia" } ] computerData.forEach(data => { test(`Parameterized test ${data.name}`, async ({ page }) => { await page.goto("https://computer-database.gatling.io/computers"); await page.click("#add"); await page.fill("#name", data.name); await page.selectOption("#company", { label: data.manufacture }); await page.click("input[type='submit']"); expect(page.locator("div.alert-message.warning")).toContainText("Done") }) })
Loop Error [No possible multiple URL? no wait? what is the error?]
Im looking to improve my skills with Playwright and I am creating this code to make an "1way-3ways-final way". error: page.goto: net::ERR_ABORTED at https://computer-database.gatling.io/computers at tests\ways1-3-1.spec.ts:25:18 Can anyone help me? test('1 way to 3 and finish in 1', async ({ page }) => { await page.goto('https://large-type.com/#starting'); await page.waitForTimeout(2000); computerData.forEach(async data => { await page.goto("https://computer-database.gatling.io/computers"); await page.click("#add"); await page.fill("#name", data.name); await page.selectOption("#company", {label: data.manufacture}); await page.click("input[type='submit']"); await expect(page.locator("div.alert-message.warning")).toContainText(`Done ! Computer ${data.name} has been created`); }); await page.goto('https://large-type.com/#finished'); await page.waitForTimeout(2000); });
[ "forEach runs synchronously -- the awaits in the async callbacks apply to the function they appear in, not to the surrounding function.\nI guess you want each iteration to kick in only when the previous one has completed all the actions being awaited. In that case, just avoid the callback, and use a straight for loop:\n for (const data of computerData) { \n await page.goto(\"https://computer-database.gatling.io/computers\");\n await page.click(\"#add\");\n await page.fill(\"#name\", data.name);\n await page.selectOption(\"#company\", {label: data.manufacture});\n await page.click(\"input[type='submit']\");\n await expect(page.locator(\"div.alert-message.warning\")).toContainText(`Done ! Computer ${data.name} has been created`); \n }\n\n", "Complete Data Driven Example:\nimport { test } from \"@fixtures/myFixtures\";\nimport { expect } from \"@playwright/test\";\n\nconst computerData = [{\n name: \"Comp A\",\n manufacture: \"Tandy Corporation\"\n },\n {\n name: \"Comp B\",\n manufacture: \"Commodore International\"\n },\n {\n name: \"Comp C\",\n manufacture: \"Thinking Machines\"\n },\n {\n name: \"Comp D\",\n manufacture: \"Nokia\"\n }\n ]\n computerData.forEach(data => {\n \n test(`Parameterized test ${data.name}`, async ({ page }) => {\n await page.goto(\"https://computer-database.gatling.io/computers\");\n await page.click(\"#add\");\n await page.fill(\"#name\", data.name);\n await page.selectOption(\"#company\", {\n label: data.manufacture\n });\n await page.click(\"input[type='submit']\");\n expect(page.locator(\"div.alert-message.warning\")).toContainText(\"Done\")\n })\n \n })\n\n" ]
[ 0, 0 ]
[]
[]
[ "async_await", "foreach", "javascript", "playwright" ]
stackoverflow_0074657326_async_await_foreach_javascript_playwright.txt
Q: Unable to clone an object from within an abstract class method in Scala I am creating an object of a class in Scala and I would like to clone the object but change one member's value. For that I'm trying to do something like this: abstract class A { var dbName: String def withConfig(db: String): A = { var a = this a.dbName = db a } } class A1(db: String) extends A { override var dbName: String = db } class A2(db: String) extends A { override var dbName: String = db } object Test { def main(args: Array[String]): Unit = { var obj = new A1("TEST") println(obj.dbName) var newObj = obj.withConfig("TEST2") println(newObj.dbName) println(obj.dbName) } } When I run this program, I get the below output: TEST TEST2 TEST2 While I was able to create a new object from the original in this, unfortunately it ended up modifying the value of the member of the original object as well. I believe this is because I'm using the same instance this and then changing the member. Thus I thought I can clone the object instead, for which I made a change to the withConfig method: def withConfig(db: String): A = { var a = this.clone().asInstanceOf[A] a.dbName = db a } Unfortunately, it is throwing an error saying Clone Not supported: TEST Exception in thread "main" java.lang.CloneNotSupportedException: c.i.d.c.A1 at java.lang.Object.clone(Native Method) at c.i.d.c.A.withConfig(Test.scala:7) at c.i.d.c.Test$.main(Test.scala:21) at c.i.d.c.Test.main(Test.scala) Is there a way I could achieve the functionality similar to clone(), but without making significant changes to the abstract class? A: You should override clone in classes abstract class A extends Cloneable { var dbName: String def withConfig(db: String): A = { var a = this.clone().asInstanceOf[A] a.dbName = db a } } class A1(db: String) extends A { override var dbName: String = db override def clone(): AnyRef = new A1(db) } class A2(db: String) extends A { override var dbName: String = db override def clone(): AnyRef = new A2(db) } By the way, using vars is not idiomatic. With vals instead of vars (and not using Java Cloneable at all) abstract class A { def db: String def withConfig(db: String): A } class A1(val db: String) extends A { override def withConfig(db: String): A = new A1(db) } class A2(val db: String) extends A { override def withConfig(db: String): A = new A2(db) } val obj = new A1("TEST") println(obj.db) // TEST val newObj = obj.withConfig("TEST2") println(newObj.db) // TEST2 println(obj.db) // TEST or (with withConfig returning more precise type than A) abstract class A { def db: String type This <: A def withConfig(db: String): This } class A1(val db: String) extends A { override type This = A1 override def withConfig(db: String): This = new A1(db) } class A2(val db: String) extends A { override type This = A2 override def withConfig(db: String): This = new A2(db) } I would even implement This and withConfig with a macro annotation import scala.annotation.{StaticAnnotation, compileTimeOnly} import scala.language.experimental.macros import scala.reflect.macros.blackbox @compileTimeOnly("enable macro annotations") class implement extends StaticAnnotation { def macroTransform(annottees: Any*): Any = macro ImplementMacro.impl } object ImplementMacro { def impl(c: blackbox.Context)(annottees: c.Tree*): c.Tree = { import c.universe._ annottees match { case q"$mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self => ..$stats }" :: tail => val tparams1 = tparams.map { case q"$mods type $tpname[..$tparams] = $tpt" => tq"$tpname" } q""" $mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self => ..$stats override type This = $tpname[..$tparams1] override def withConfig(db: String): This = new $tpname(db) } ..$tail """ } } } abstract class A { def db: String type This <: A def withConfig(db: String): This } @implement class A1(val db: String) extends A @implement class A2(val db: String) extends A //scalac: { // class A1 extends A { // <paramaccessor> val db: String = _; // def <init>(db: String) = { // super.<init>(); // () // }; // override type This = A1; // override def withConfig(db: String): This = new A1(db) // }; // () //} //scalac: { // class A2 extends A { // <paramaccessor> val db: String = _; // def <init>(db: String) = { // super.<init>(); // () // }; // override type This = A2; // override def withConfig(db: String): This = new A2(db) // }; // () //} Settings: Auto-Generate Companion Object for Case Class in Scala
Unable to clone an object from within an abstract class method in Scala
I am creating an object of a class in Scala and I would like to clone the object but change one member's value. For that I'm trying to do something like this: abstract class A { var dbName: String def withConfig(db: String): A = { var a = this a.dbName = db a } } class A1(db: String) extends A { override var dbName: String = db } class A2(db: String) extends A { override var dbName: String = db } object Test { def main(args: Array[String]): Unit = { var obj = new A1("TEST") println(obj.dbName) var newObj = obj.withConfig("TEST2") println(newObj.dbName) println(obj.dbName) } } When I run this program, I get the below output: TEST TEST2 TEST2 While I was able to create a new object from the original in this, unfortunately it ended up modifying the value of the member of the original object as well. I believe this is because I'm using the same instance this and then changing the member. Thus I thought I can clone the object instead, for which I made a change to the withConfig method: def withConfig(db: String): A = { var a = this.clone().asInstanceOf[A] a.dbName = db a } Unfortunately, it is throwing an error saying Clone Not supported: TEST Exception in thread "main" java.lang.CloneNotSupportedException: c.i.d.c.A1 at java.lang.Object.clone(Native Method) at c.i.d.c.A.withConfig(Test.scala:7) at c.i.d.c.Test$.main(Test.scala:21) at c.i.d.c.Test.main(Test.scala) Is there a way I could achieve the functionality similar to clone(), but without making significant changes to the abstract class?
[ "You should override clone in classes\nabstract class A extends Cloneable {\n var dbName: String\n\n def withConfig(db: String): A = {\n var a = this.clone().asInstanceOf[A]\n a.dbName = db\n a\n }\n}\n\nclass A1(db: String) extends A {\n override var dbName: String = db\n override def clone(): AnyRef = new A1(db)\n}\n\nclass A2(db: String) extends A {\n override var dbName: String = db\n override def clone(): AnyRef = new A2(db)\n}\n\nBy the way, using vars is not idiomatic.\n\nWith vals instead of vars (and not using Java Cloneable at all)\nabstract class A {\n def db: String\n def withConfig(db: String): A\n}\n\nclass A1(val db: String) extends A {\n override def withConfig(db: String): A = new A1(db)\n}\n\nclass A2(val db: String) extends A {\n override def withConfig(db: String): A = new A2(db)\n}\n\nval obj = new A1(\"TEST\")\nprintln(obj.db) // TEST\nval newObj = obj.withConfig(\"TEST2\")\nprintln(newObj.db) // TEST2\nprintln(obj.db) // TEST\n\nor (with withConfig returning more precise type than A)\nabstract class A {\n def db: String\n type This <: A\n def withConfig(db: String): This\n}\n\nclass A1(val db: String) extends A {\n override type This = A1\n override def withConfig(db: String): This = new A1(db)\n}\n\nclass A2(val db: String) extends A {\n override type This = A2\n override def withConfig(db: String): This = new A2(db)\n}\n\n\nI would even implement This and withConfig with a macro annotation\nimport scala.annotation.{StaticAnnotation, compileTimeOnly}\nimport scala.language.experimental.macros\nimport scala.reflect.macros.blackbox\n\n@compileTimeOnly(\"enable macro annotations\")\nclass implement extends StaticAnnotation {\n def macroTransform(annottees: Any*): Any = macro ImplementMacro.impl\n}\n\nobject ImplementMacro {\n def impl(c: blackbox.Context)(annottees: c.Tree*): c.Tree = {\n import c.universe._\n annottees match {\n case q\"$mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self => ..$stats }\" :: tail =>\n val tparams1 = tparams.map {\n case q\"$mods type $tpname[..$tparams] = $tpt\" => tq\"$tpname\"\n }\n q\"\"\"\n $mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self =>\n ..$stats\n override type This = $tpname[..$tparams1]\n override def withConfig(db: String): This = new $tpname(db)\n }\n\n ..$tail\n \"\"\"\n }\n }\n}\n\nabstract class A {\n def db: String\n type This <: A\n def withConfig(db: String): This\n}\n\n@implement\nclass A1(val db: String) extends A\n\n@implement\nclass A2(val db: String) extends A\n\n//scalac: {\n// class A1 extends A {\n// <paramaccessor> val db: String = _;\n// def <init>(db: String) = {\n// super.<init>();\n// ()\n// };\n// override type This = A1;\n// override def withConfig(db: String): This = new A1(db)\n// };\n// ()\n//}\n//scalac: {\n// class A2 extends A {\n// <paramaccessor> val db: String = _;\n// def <init>(db: String) = {\n// super.<init>();\n// ()\n// };\n// override type This = A2;\n// override def withConfig(db: String): This = new A2(db)\n// };\n// ()\n//}\n\nSettings: Auto-Generate Companion Object for Case Class in Scala\n" ]
[ 1 ]
[]
[]
[ "clone", "java", "scala" ]
stackoverflow_0074678693_clone_java_scala.txt
Q: Why WAF blocks multiple spaces? In my project we are using WAF. Recently I found a bug that is, when we are adding multiple spaced words in a textbox for example Hello there, this is a multi spaced word collection . and trying to saving it, the WAF blocks the request, but when we try to save the text without space (more than one continues spaces) like this : Hello there, this is a multi spaced word collection . it got saved. I compared the formData from the network only the difference I could identify is the space. Why the WAF blocks the request? is that a built-in functionality to prevent cyber attacks? Note: If I remove the extra spaces from my UI it works fine. So am very curious to know why the WAF blocks the request? A: It is likely that the WAF is blocking the request with multiple spaces because it is detecting a potential XSS (Cross-Site Scripting) attack. In a XSS attack, the attacker injects malicious JavaScript code into the web application, which is executed by the victim's browser and can steal sensitive data, such as cookies and passwords. One common way to perform a XSS attack is to inject JavaScript code into the web application by using multiple spaces in the input fields. When the user submits the form, the web application saves the input with the multiple spaces, and when the input is displayed on the page, the browser treats the multiple spaces as HTML whitespace, which is ignored by the HTML parser. However, when the HTML parser encounters the JavaScript code, it treats it as valid HTML and executes it. The user will use spaces to obscure the meaning of the input he is sending and increase the chances of the attack being successful. To prevent this type of attack, WAFs typically use a set of rules and signatures to identify and block input with multiple spaces, because it is a common pattern of XSS attacks. This is why the WAF is blocking the request with multiple spaces, and this is a built-in functionality to prevent cyber attacks. To fix the issue, you can remove the extra spaces from your input fields, or you can use a sanitization library, such as DOMPurify, to sanitize the input and remove the potentially malicious JavaScript code. This will allow the WAF to process the request without blocking it, and it will prevent the XSS attack from being successful.
Why WAF blocks multiple spaces?
In my project we are using WAF. Recently I found a bug that is, when we are adding multiple spaced words in a textbox for example Hello there, this is a multi spaced word collection . and trying to saving it, the WAF blocks the request, but when we try to save the text without space (more than one continues spaces) like this : Hello there, this is a multi spaced word collection . it got saved. I compared the formData from the network only the difference I could identify is the space. Why the WAF blocks the request? is that a built-in functionality to prevent cyber attacks? Note: If I remove the extra spaces from my UI it works fine. So am very curious to know why the WAF blocks the request?
[ "It is likely that the WAF is blocking the request with multiple spaces because it is detecting a potential XSS (Cross-Site Scripting) attack. In a XSS attack, the attacker injects malicious JavaScript code into the web application, which is executed by the victim's browser and can steal sensitive data, such as cookies and passwords.\nOne common way to perform a XSS attack is to inject JavaScript code into the web application by using multiple spaces in the input fields. When the user submits the form, the web application saves the input with the multiple spaces, and when the input is displayed on the page, the browser treats the multiple spaces as HTML whitespace, which is ignored by the HTML parser. However, when the HTML parser encounters the JavaScript code, it treats it as valid HTML and executes it.\nThe user will use spaces to obscure the meaning of the input he is sending and increase the chances of the attack being successful.\nTo prevent this type of attack, WAFs typically use a set of rules and signatures to identify and block input with multiple spaces, because it is a common pattern of XSS attacks. This is why the WAF is blocking the request with multiple spaces, and this is a built-in functionality to prevent cyber attacks.\nTo fix the issue, you can remove the extra spaces from your input fields, or you can use a sanitization library, such as DOMPurify, to sanitize the input and remove the potentially malicious JavaScript code. This will allow the WAF to process the request without blocking it, and it will prevent the XSS attack from being successful.\n" ]
[ 0 ]
[]
[]
[ "api", "web_application_firewall" ]
stackoverflow_0073247458_api_web_application_firewall.txt
Q: Using RTK query how do I add data to my state without a call to the server? I'm building my first app using RTK query. I need to set my authorization token in my headers. It is stored in a cookie, but they can't be accessed from the apiSlice, which means I need to store the token in my states which I'd have access to when setting my headers. I get the token from my cookies when the app first starts, but I'm failing to understand how do I store it in my state, now that I use RTK query? I'm not making any API call, I already have the data. How do I store it in my slice? A: The point of RTK Query is to make calls to the server and store the result of that call to the server. RTK Query does not replace all your other state management - it just takes over that one aspect. If you have non-server-data, you should still be using a normal slice for that, not try to put that into RTK Query. Apart from that: if you have a token that is in a cookie, there is probably no need to read that into your store and attach it to future requests. The point of cookies is that they are sent back and forth between the browser and the server - you don't have to manually do anything here, besides setting the credentials: "include" option.
Using RTK query how do I add data to my state without a call to the server?
I'm building my first app using RTK query. I need to set my authorization token in my headers. It is stored in a cookie, but they can't be accessed from the apiSlice, which means I need to store the token in my states which I'd have access to when setting my headers. I get the token from my cookies when the app first starts, but I'm failing to understand how do I store it in my state, now that I use RTK query? I'm not making any API call, I already have the data. How do I store it in my slice?
[ "The point of RTK Query is to make calls to the server and store the result of that call to the server.\nRTK Query does not replace all your other state management - it just takes over that one aspect. If you have non-server-data, you should still be using a normal slice for that, not try to put that into RTK Query.\nApart from that: if you have a token that is in a cookie, there is probably no need to read that into your store and attach it to future requests. The point of cookies is that they are sent back and forth between the browser and the server - you don't have to manually do anything here, besides setting the credentials: \"include\" option.\n" ]
[ 1 ]
[ "To add data to your state without making a call to the server using RTK query, you can use the update() method of your slice. This method allows you to update your state with new data without dispatching an action.\nFor example, if you have a slice called \"auth\" with a property called \"token\" that you want to update with your authorization token, you can use the following code:\nconst authSlice = createSlice({\n name: 'auth',\n initialState: {\n token: null\n },\n reducers: {\n // Add your reducer functions here\n }\n});\n\n// Get your authorization token from the cookie\nconst token = getTokenFromCookie();\n\n// Update the state with the new token\nauthSlice.update(state => {\n state.token = token;\n return state;\n});\n\nThis will update your state with the new token without making a call to the server. You can then access the token in your state using the select() method of your slice.\nconst token = authSlice.select(state => state.token);\n\nYou can then use the token to set the headers of your API requests.\nconst headers = {\n Authorization: `Bearer ${token}`\n};\n\nBy using the update() method of your slice, you can easily add data to your state without making a call to the server.\n" ]
[ -1 ]
[ "reactjs", "redux", "redux_toolkit", "rtk_query" ]
stackoverflow_0074674917_reactjs_redux_redux_toolkit_rtk_query.txt
Q: Turn values from string to integers in JSON file python I'm trying to change values in a JSON file from strings to integers, my issue is that the keys are row numbers so I can't call by key name (as they will change consistently). The values that need changing are within the "sharesTraded" object. Below is my JSON file: { "lastDate": { "30": "04/04/2022", "31": "04/04/2022", "40": "02/03/2022", "45": "02/01/2022" }, "transactionType": { "30": "Automatic Sell", "31": "Automatic Sell", "40": "Automatic Sell", "45": "Sell" }, "sharesTraded": { "30": "29,198", "31": "105,901", "40": "25,000", "45": "1,986" } } And here is my current code: import json data = json.load(open("AAPL22_trades.json")) dataa = data['sharesTraded'] dataa1 = dataa.values() data1 = [s.replace(',', '') for s in dataa1] data1 = [int(i) for i in data1] open("AAPL22_trades.json", "w").write( json.dumps(data1, indent=4)) However, I need the integer values to replace the string values. Instead, my code just replaces the entire JSON with the integers. I imagine there is something extra at the end that I'm missing because the strings have been changed to integers but applying it to the JSON is missing. A: You have a couple of problems. First, since you only convert the values to a list, you loose the information about which key is associated with the values. Second, you write that list back to the file, loosing all of the other data too. You could create a new dictionary with the modified values and assign that back to the original. import json data = json.load(open("AAPL22_trades.json")) data['sharesTraded'] = {k:int(v.replace(',', '')) for k,v in data['sharesTraded'].items()} json.dump(data, open("AAPL22_trades.json", "w"), indent=4) A: You could do the following: shares_traded = data['sharesTraded'] for key, value in shares_traded.items(): shares_traded[key] = int(value.replace(',', '')) In this way, only the values will be changed, and the key will stay as-is.
Turn values from string to integers in JSON file python
I'm trying to change values in a JSON file from strings to integers, my issue is that the keys are row numbers so I can't call by key name (as they will change consistently). The values that need changing are within the "sharesTraded" object. Below is my JSON file: { "lastDate": { "30": "04/04/2022", "31": "04/04/2022", "40": "02/03/2022", "45": "02/01/2022" }, "transactionType": { "30": "Automatic Sell", "31": "Automatic Sell", "40": "Automatic Sell", "45": "Sell" }, "sharesTraded": { "30": "29,198", "31": "105,901", "40": "25,000", "45": "1,986" } } And here is my current code: import json data = json.load(open("AAPL22_trades.json")) dataa = data['sharesTraded'] dataa1 = dataa.values() data1 = [s.replace(',', '') for s in dataa1] data1 = [int(i) for i in data1] open("AAPL22_trades.json", "w").write( json.dumps(data1, indent=4)) However, I need the integer values to replace the string values. Instead, my code just replaces the entire JSON with the integers. I imagine there is something extra at the end that I'm missing because the strings have been changed to integers but applying it to the JSON is missing.
[ "You have a couple of problems. First, since you only convert the values to a list, you loose the information about which key is associated with the values. Second, you write that list back to the file, loosing all of the other data too.\nYou could create a new dictionary with the modified values and assign that back to the original.\nimport json\n\ndata = json.load(open(\"AAPL22_trades.json\"))\ndata['sharesTraded'] = {k:int(v.replace(',', '')) \n for k,v in data['sharesTraded'].items()}\njson.dump(data, open(\"AAPL22_trades.json\", \"w\"), indent=4)\n\n", "You could do the following:\nshares_traded = data['sharesTraded']\n\nfor key, value in shares_traded.items():\n shares_traded[key] = int(value.replace(',', ''))\n\nIn this way, only the values will be changed, and the key will stay as-is.\n" ]
[ 2, 1 ]
[]
[]
[ "integer", "json", "python", "string" ]
stackoverflow_0074678918_integer_json_python_string.txt
Q: Converting TIFF images to NumPy format I would need help to create a code that would convert my tiff images to .npy format so I can save it as .npy file. I haven't found a good solution anywhere on this platform. Thank you in advance! A: Here is a code snippet that you can use to convert your TIFF images to .npy format in Python: import numpy as np from PIL import Image # Load the TIFF image im = Image.open('my_image.tiff') # Convert the image to a numpy array im_array = np.array(im) # Save the array to a .npy file np.save('my_image.npy', im_array) You can then load the .npy file using the np.load function and use the array for your further operations. # Load the .npy file im_array = np.load('my_image.npy') #Use the array for your operations ... I hope this helps! Let me know if you have any further questions.
Converting TIFF images to NumPy format
I would need help to create a code that would convert my tiff images to .npy format so I can save it as .npy file. I haven't found a good solution anywhere on this platform. Thank you in advance!
[ "Here is a code snippet that you can use to convert your TIFF images to .npy format in Python:\nimport numpy as np\nfrom PIL import Image\n\n# Load the TIFF image\nim = Image.open('my_image.tiff')\n\n# Convert the image to a numpy array\nim_array = np.array(im)\n\n# Save the array to a .npy file\nnp.save('my_image.npy', im_array)\n\nYou can then load the .npy file using the np.load function and use the array for your further operations.\n# Load the .npy file\nim_array = np.load('my_image.npy')\n#Use the array for your operations\n\n...\nI hope this helps! Let me know if you have any further questions.\n" ]
[ 0 ]
[]
[]
[ "numpy", "python", "tiff" ]
stackoverflow_0074678997_numpy_python_tiff.txt
Q: Dafny: Verification of the most simple array summation does not work. Can somebody explain me why? When I have three arrays and c[j] := b[h] + a[i]. The verification c[j] == b[h] + a[i] does not work. Can somebody please explain me why? It is assured that all indices are in range and all three arrays are int arrays. Here is my code: method addThreeArrays(a: array<int>, b: array<int>, c: array<int>, h: int, i: int, j: int) modifies c requires 0 <= h < a.Length requires 0 <= i < b.Length requires 0 <= j < c.Length ensures c[j] == a[h] + b[i] { c[j] := a[h] + b[i]; } I expected the "ensures" line to be true. But Dafny gives the error. "Postcondition" might not hold. I just want to understand where my error is. Thank you guys! :) A: Since Dafny arrays are allocated on the heap, they are allowed to alias. So it is possible to call your method with, for example, c and a pointing to the same array in memory. Also, it's possible that j == h. In that scenario, the postcondition may not hold since writing to c[j] also wrote to a[h] (since c and a point to the same array and j == h). You can fix this by adding a precondition that a != c and b != c.
Dafny: Verification of the most simple array summation does not work. Can somebody explain me why?
When I have three arrays and c[j] := b[h] + a[i]. The verification c[j] == b[h] + a[i] does not work. Can somebody please explain me why? It is assured that all indices are in range and all three arrays are int arrays. Here is my code: method addThreeArrays(a: array<int>, b: array<int>, c: array<int>, h: int, i: int, j: int) modifies c requires 0 <= h < a.Length requires 0 <= i < b.Length requires 0 <= j < c.Length ensures c[j] == a[h] + b[i] { c[j] := a[h] + b[i]; } I expected the "ensures" line to be true. But Dafny gives the error. "Postcondition" might not hold. I just want to understand where my error is. Thank you guys! :)
[ "Since Dafny arrays are allocated on the heap, they are allowed to alias. So it is possible to call your method with, for example, c and a pointing to the same array in memory. Also, it's possible that j == h. In that scenario, the postcondition may not hold since writing to c[j] also wrote to a[h] (since c and a point to the same array and j == h).\nYou can fix this by adding a precondition that a != c and b != c.\n" ]
[ 0 ]
[]
[]
[ "addition", "arrays", "dafny" ]
stackoverflow_0074677214_addition_arrays_dafny.txt
Q: At what stage is @SpringBootApplication executed in spring boot application? When writing a Spring Boot application, we have code like this: import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } Which means, it can run as a standalone application(having main method) - so far, so good. My doubt starts here: The main would be invoked by JVM, so it will see main method, and then execute the line: SpringApplication.run(Application.class, args); Then, who does check the annotation @SpringBootApplication - is it interpreted on-the-fly once control goes into Spring framework when JVM executes the first line? A: This took me a while to figure out as well... Your class Application is the 'main' class. It is calling a static method on SpringApplication. It is the SpringApplication class that actually starts the entire Spring Boot process and all the code that will check for the Spring Annotations and things like that. I have never looked at the code behind that class, but it has to be tremendous.
At what stage is @SpringBootApplication executed in spring boot application?
When writing a Spring Boot application, we have code like this: import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } Which means, it can run as a standalone application(having main method) - so far, so good. My doubt starts here: The main would be invoked by JVM, so it will see main method, and then execute the line: SpringApplication.run(Application.class, args); Then, who does check the annotation @SpringBootApplication - is it interpreted on-the-fly once control goes into Spring framework when JVM executes the first line?
[ "This took me a while to figure out as well...\nYour class Application is the 'main' class. It is calling a static method on SpringApplication.\nIt is the SpringApplication class that actually starts the entire Spring Boot process and all the code that will check for the Spring Annotations and things like that.\nI have never looked at the code behind that class, but it has to be tremendous.\n" ]
[ 0 ]
[]
[]
[ "java", "spring", "spring_boot" ]
stackoverflow_0074679036_java_spring_spring_boot.txt
Q: Is there a function that makes python read only some parts of a string and execute an operation I'm trying to make my Python read only the first 3 digits of a string and print an answer based on the first three digits of the string. I tried: if str[1,2,3] = 080: print(...) elif str[123] =090: print(,,,) A: Here is how you can achieve this in Python: # Store the string in a variable string = "Hello world" # Get the first three characters of the string first_three_chars = string[:3] # Check if the first three characters are "080" if first_three_chars == "080": print("The first three characters are 080") elif first_three_chars == "090": print("The first three characters are 090") else: print("The first three characters are not 080 or 090") In this code, we use the string[:3] syntax to get the first three characters of the string. Then, we use if and elif statements to check if the first three characters are "080" or "090". A: use the index between the subscript like: str[0:3] or str [:3] this will take the cursor from 0th index to 2nd index
Is there a function that makes python read only some parts of a string and execute an operation
I'm trying to make my Python read only the first 3 digits of a string and print an answer based on the first three digits of the string. I tried: if str[1,2,3] = 080: print(...) elif str[123] =090: print(,,,)
[ "Here is how you can achieve this in Python:\n# Store the string in a variable\nstring = \"Hello world\"\n\n# Get the first three characters of the string\nfirst_three_chars = string[:3]\n\n# Check if the first three characters are \"080\"\nif first_three_chars == \"080\":\n print(\"The first three characters are 080\")\nelif first_three_chars == \"090\":\n print(\"The first three characters are 090\")\nelse:\n print(\"The first three characters are not 080 or 090\")\n\nIn this code, we use the string[:3] syntax to get the first three characters of the string. Then, we use if and elif statements to check if the first three characters are \"080\" or \"090\".\n", "use the index between the subscript like:\nstr[0:3] or str [:3]\n\nthis will take the cursor from 0th index to 2nd index\n" ]
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074679053_python.txt
Q: Facing Bazel Build error while using Select() function I have a simple BUILD.bazel for selecting the targets as below. This works, however when i apply the same method to a bigger project having multiple .cpp and .h files, Iam facing an error. Can you please suggest? Simple BUILD.bazel: cc_library( name = "testlib", srcs = select ({ ":pc" : [ "source/t1.c" , ], ":ecu" : [ "source/t2.c" , ], }) ) config_setting( name = "pc", define_values = { "target" : "pc", } ) config_setting( name = "ecu", define_values = { "target" : "ecu", } ) Command that works: Build for PC: bazel build --define target=pc //... Build for ECU: bazel build --define target=ecu //... However below error coming when I apply above method to large project: failed: configurable "srcs" triggers an implicit .so output even though there are no sources to compile in this configuration caused by.....
Facing Bazel Build error while using Select() function
I have a simple BUILD.bazel for selecting the targets as below. This works, however when i apply the same method to a bigger project having multiple .cpp and .h files, Iam facing an error. Can you please suggest? Simple BUILD.bazel: cc_library( name = "testlib", srcs = select ({ ":pc" : [ "source/t1.c" , ], ":ecu" : [ "source/t2.c" , ], }) ) config_setting( name = "pc", define_values = { "target" : "pc", } ) config_setting( name = "ecu", define_values = { "target" : "ecu", } ) Command that works: Build for PC: bazel build --define target=pc //... Build for ECU: bazel build --define target=ecu //... However below error coming when I apply above method to large project: failed: configurable "srcs" triggers an implicit .so output even though there are no sources to compile in this configuration caused by.....
[]
[]
[ "It looks like you are trying to use the select() function in your cc_library rule to select different source files to compile based on a target configuration. This is a valid use of the select() function. However, the error message you are seeing suggests that Bazel is unable to find any source files to compile in one of the configurations.\nOne possible reason for this error is that the values specified in the define_values attribute of your config_setting rules do not match the keys used in the select() function in your cc_library rule. For example, in your cc_library rule, the keys used in the select() function are :pc and :ecu, but in your config_setting rules, the values specified in the define_values attribute are \"target\": \"pc\" and \"target\": \"ecu\". These values do not match the keys used in the select() function, so Bazel will not be able to find the source files to compile.\nTo fix this error, you will need to ensure that the keys used in the select() function in your cc_library rule match the values specified in the define_values attribute of your config_setting rules. For example, you could change the config_setting rules to use the same keys as in the select() function:\nconfig_setting(\n name = \"pc\",\n define_values = {\n \":pc\" : True,\n }\n)\n\nconfig_setting(\n name = \"ecu\",\n define_values = {\n \":ecu\" : True,\n }\n)\nWith these changes, Bazel will be able to find the source files to compile in each configuration. You can then build your target using the bazel build command as before, passing the appropriate --define flag to specify the target configuration.\nI hope this helps! Let me know if you have any other questions.\n\n" ]
[ -1 ]
[ "bazel" ]
stackoverflow_0074679024_bazel.txt
Q: Individual Unit selection in RTS games In most RTS games only ONE unit can be active at a time (of course, if you don`t use a selection box over multiple units). So, if you select the second unit, the first one is deselected automatically. How is it possible to achieve in JavaScript? ` function knightMove(){ console.log("I move"); } function riderMove(){ console.log("I move too"); } let knight = document.querySelector(".knight"); let rider = document.querySelector(".rider"); // UNIT SELECTION function select(unit,funct1){ unit.addEventListener("click",selectedUnit); function selectedUnit(){ window.addEventListener("keydown",funct1); unit.style.boxShadow = "0 0 44px 22px red"; console.log(name, "IS SELECTED"); // DESELECT IF BACKGROUND IS CLICKED bg.addEventListener("click",()=>{ window.removeEventListener("keydown",funct1); unit.style.boxShadow = "0 0 44px 22px white"; console.log(name, "IS DESELECTED"); }) } } select(knight,knightMove); select(rider,riderMove); ` A: The simplest way would be to store the one selected unit as a global variable. Then you can simply add and remove a CSS class as necessary const knight = document.querySelector('.knight'); const rider = document.querySelector('.rider'); let selectedUnit = null; for (const unit of [knight, rider]) unit.addEventListener('click', selectUnit); document.addEventListener('click', deselectCurrentUnit); function deselectCurrentUnit(){ if (selectedUnit) selectedUnit.classList.remove('selected'); } function selectUnit(event) { event.stopPropagation(); deselectCurrentUnit(); const unit = event.target; selectedUnit = unit; unit.classList.add('selected'); } body { background: green; } .unit { cursor: pointer; margin: 50px; box-shadow: 0 0 44px 22px white; } .selected { box-shadow: 0 0 44px 22px red; } <p class="knight unit">Knight</p> <p class="rider unit">Rider</p>
Individual Unit selection in RTS games
In most RTS games only ONE unit can be active at a time (of course, if you don`t use a selection box over multiple units). So, if you select the second unit, the first one is deselected automatically. How is it possible to achieve in JavaScript? ` function knightMove(){ console.log("I move"); } function riderMove(){ console.log("I move too"); } let knight = document.querySelector(".knight"); let rider = document.querySelector(".rider"); // UNIT SELECTION function select(unit,funct1){ unit.addEventListener("click",selectedUnit); function selectedUnit(){ window.addEventListener("keydown",funct1); unit.style.boxShadow = "0 0 44px 22px red"; console.log(name, "IS SELECTED"); // DESELECT IF BACKGROUND IS CLICKED bg.addEventListener("click",()=>{ window.removeEventListener("keydown",funct1); unit.style.boxShadow = "0 0 44px 22px white"; console.log(name, "IS DESELECTED"); }) } } select(knight,knightMove); select(rider,riderMove); `
[ "The simplest way would be to store the one selected unit as a global variable.\nThen you can simply add and remove a CSS class as necessary\n\n\nconst knight = document.querySelector('.knight');\nconst rider = document.querySelector('.rider');\nlet selectedUnit = null;\n\nfor (const unit of [knight, rider]) unit.addEventListener('click', selectUnit);\ndocument.addEventListener('click', deselectCurrentUnit);\n\nfunction deselectCurrentUnit(){\n if (selectedUnit) selectedUnit.classList.remove('selected');\n}\n\nfunction selectUnit(event) {\n event.stopPropagation();\n deselectCurrentUnit();\n const unit = event.target;\n selectedUnit = unit;\n unit.classList.add('selected');\n}\nbody {\n background: green;\n}\n\n.unit {\n cursor: pointer;\n margin: 50px;\n box-shadow: 0 0 44px 22px white;\n}\n\n.selected {\n box-shadow: 0 0 44px 22px red;\n}\n <p class=\"knight unit\">Knight</p>\n <p class=\"rider unit\">Rider</p>\n\n\n\n" ]
[ 1 ]
[]
[]
[ "javascript", "mouse", "selection" ]
stackoverflow_0074678658_javascript_mouse_selection.txt
Q: Edge extension to rename tab title not working I am trying to write an Edge extension that changes the title of a tab. Here is what I've tried but it doesn't seem to change the tab's title. When I add alert(tab.title) it does seem like it has changed. Manifest.json { "name": "My Tab", "version": "2.0.0", "description": "Simple Microsoft Edge Extension", "manifest_version": 2, "author": "abc", "browser_action": { "default_popup": "bg.html", "default_title": "Hello World" }, "permissions": [ "tabs", "<all_urls>" ], "background": { "page": "bg.html", "persistent": true } } bg.html <!DOCTYPE html> <html> <head> <title>demo</title> </head> <body> <div> <h3>Click the button to get the page URL...<h3><br> <button id="btn1">click me</button> <input type="text" id="txt1" style="width:300px"> </div> <script type="text/javascript" src="background.js"></script> </body> </html> background.js var btn= document.getElementById("btn1"); btn.addEventListener("click", function(){ abc(); }); function abc() { chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) { var tab = tabs[0]; var title = document.getElementById("txt1").value; tabs[0].title = title; tab.reload(); }); } Any idea? A: It looks like you're trying to write an extension for Microsoft Edge, but you're using the Chrome tabs API. Microsoft Edge uses its own extension API, which is different from the Chrome tabs API. To change the title of the active tab in Microsoft Edge, you can use the browser.tabs.executeScript() method to execute some JavaScript code in the active tab. This code can then change the title of the page by setting the document.title property. Here is an example of how you might do this: browser.tabs.executeScript({ code: "document.title = 'New Title';" }); Note that this code should be run in the background script of your extension, not in the bg.html file. Also, keep in mind that the browser object is only available in the background script of your extension. If you need to access it from other scripts, you can use the browser.runtime.getBackgroundPage() method to get a reference to the background script from those other scripts.
Edge extension to rename tab title not working
I am trying to write an Edge extension that changes the title of a tab. Here is what I've tried but it doesn't seem to change the tab's title. When I add alert(tab.title) it does seem like it has changed. Manifest.json { "name": "My Tab", "version": "2.0.0", "description": "Simple Microsoft Edge Extension", "manifest_version": 2, "author": "abc", "browser_action": { "default_popup": "bg.html", "default_title": "Hello World" }, "permissions": [ "tabs", "<all_urls>" ], "background": { "page": "bg.html", "persistent": true } } bg.html <!DOCTYPE html> <html> <head> <title>demo</title> </head> <body> <div> <h3>Click the button to get the page URL...<h3><br> <button id="btn1">click me</button> <input type="text" id="txt1" style="width:300px"> </div> <script type="text/javascript" src="background.js"></script> </body> </html> background.js var btn= document.getElementById("btn1"); btn.addEventListener("click", function(){ abc(); }); function abc() { chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) { var tab = tabs[0]; var title = document.getElementById("txt1").value; tabs[0].title = title; tab.reload(); }); } Any idea?
[ "It looks like you're trying to write an extension for Microsoft Edge, but you're using the Chrome tabs API. Microsoft Edge uses its own extension API, which is different from the Chrome tabs API.\nTo change the title of the active tab in Microsoft Edge, you can use the browser.tabs.executeScript() method to execute some JavaScript code in the active tab. This code can then change the title of the page by setting the document.title property.\nHere is an example of how you might do this:\nbrowser.tabs.executeScript({\n code: \"document.title = 'New Title';\"\n});\n\nNote that this code should be run in the background script of your extension, not in the bg.html file.\nAlso, keep in mind that the browser object is only available in the background script of your extension. If you need to access it from other scripts, you can use the browser.runtime.getBackgroundPage() method to get a reference to the background script from those other scripts.\n" ]
[ 0 ]
[]
[]
[ "html", "javascript", "microsoft_edge_extension" ]
stackoverflow_0074679037_html_javascript_microsoft_edge_extension.txt
Q: Unable to complete operation on element with key none I'm practicing with an algorithm that generates a random number that the user needs, then keeps trying until it hits. But PySimpleGUI produces an error saying: Unable to complete operation on element with key None. import randomimport PySimpleGUI as sg class ChuteONumero: def init(self): self.valor_aleatorio = 0 self.valor_minimo = 1 self.valor_maximo = 100 self.tentar_novamente = True def Iniciar(self): # Layout layout = [ [sg.Text('Seu chute', size=(39, 0))], [sg.Input(size=(18, 0), key='ValorChute')], [sg.Button('Chutar!')], [sg.Output(size=(39, 10))] ] # Criar uma janela self.janela = sg.Window('Chute o numero!', Layout=layout) self.GerarNumeroAleatorio() try: while True: # Receber valores self.evento, self.valores = self.janela.Read() # Fazer alguma coisa com os vaalores if self.evento == 'Chutar!': self.valor_do_chute = self.valores['ValorChute'] while self.tentar_novamente == True: if int(self.valor_do_chute) > self.valor_aleatorio: print('Chute um valor mais baixo') break elif int(self.valor_do_chute) < self.valor_aleatorio: print('Chute um valor mais alto!') break if int(self.valor_do_chute) == self.valor_aleatorio: self.tentar_novamente = False print('Parabéns, você acertou!') break except: print('Não foi compreendido, apenas digite numeros de 1 a 100') self.Iniciar() def GerarNumeroAleatorio(self): self.valor_aleatorio = random.randint( self.valor_minimo, self.valor_maximo) chute = ChuteONumero() chute.Iniciar() I expected a layout to open, but it does not open. A: Revised your code ... import random import PySimpleGUI as sg class ChuteONumero: def __init__(self): self.valor_aleatorio = 0 self.valor_minimo = 1 self.valor_maximo = 100 self.tentar_novamente = True def Iniciar(self): # Layout layout = [ [sg.Text('Your kick', size=(39, 0))], [sg.Input(size=(18, 0), key='ValorChute')], [sg.Button('Kick!')], [sg.Output(size=(39, 10))] ] # Create a window self.janela = sg.Window('Guess The Number!', layout) self.GerarNumeroAleatorio() while True: # Receive amounts evento, valores = self.janela.read() if evento == sg.WIN_CLOSED: break # Do something with the values elif evento == 'Kick!': try: valor_do_chute = int(valores['ValorChute']) except ValueError: print('Not understood, just type numbers from 1 to 100') continue if valor_do_chute > self.valor_aleatorio: print('Guess a lower value') elif valor_do_chute < self.valor_aleatorio: print('Kick a higher value!') if valor_do_chute == self.valor_aleatorio: sg.popup_ok('Congratulations, you got it right!') break self.janela.close() def GerarNumeroAleatorio(self): self.valor_aleatorio = random.randint(self.valor_minimo, self.valor_maximo) chute = ChuteONumero() chute.Iniciar()
Unable to complete operation on element with key none
I'm practicing with an algorithm that generates a random number that the user needs, then keeps trying until it hits. But PySimpleGUI produces an error saying: Unable to complete operation on element with key None. import randomimport PySimpleGUI as sg class ChuteONumero: def init(self): self.valor_aleatorio = 0 self.valor_minimo = 1 self.valor_maximo = 100 self.tentar_novamente = True def Iniciar(self): # Layout layout = [ [sg.Text('Seu chute', size=(39, 0))], [sg.Input(size=(18, 0), key='ValorChute')], [sg.Button('Chutar!')], [sg.Output(size=(39, 10))] ] # Criar uma janela self.janela = sg.Window('Chute o numero!', Layout=layout) self.GerarNumeroAleatorio() try: while True: # Receber valores self.evento, self.valores = self.janela.Read() # Fazer alguma coisa com os vaalores if self.evento == 'Chutar!': self.valor_do_chute = self.valores['ValorChute'] while self.tentar_novamente == True: if int(self.valor_do_chute) > self.valor_aleatorio: print('Chute um valor mais baixo') break elif int(self.valor_do_chute) < self.valor_aleatorio: print('Chute um valor mais alto!') break if int(self.valor_do_chute) == self.valor_aleatorio: self.tentar_novamente = False print('Parabéns, você acertou!') break except: print('Não foi compreendido, apenas digite numeros de 1 a 100') self.Iniciar() def GerarNumeroAleatorio(self): self.valor_aleatorio = random.randint( self.valor_minimo, self.valor_maximo) chute = ChuteONumero() chute.Iniciar() I expected a layout to open, but it does not open.
[ "Revised your code ...\nimport random\nimport PySimpleGUI as sg\n\nclass ChuteONumero:\n\n def __init__(self):\n self.valor_aleatorio = 0\n self.valor_minimo = 1\n self.valor_maximo = 100\n self.tentar_novamente = True\n\n def Iniciar(self):\n # Layout\n layout = [\n [sg.Text('Your kick', size=(39, 0))],\n [sg.Input(size=(18, 0), key='ValorChute')],\n [sg.Button('Kick!')],\n [sg.Output(size=(39, 10))]\n ]\n # Create a window\n self.janela = sg.Window('Guess The Number!', layout)\n self.GerarNumeroAleatorio()\n while True:\n # Receive amounts\n evento, valores = self.janela.read()\n if evento == sg.WIN_CLOSED:\n break\n # Do something with the values\n elif evento == 'Kick!':\n try:\n valor_do_chute = int(valores['ValorChute'])\n except ValueError:\n print('Not understood, just type numbers from 1 to 100')\n continue\n if valor_do_chute > self.valor_aleatorio:\n print('Guess a lower value')\n elif valor_do_chute < self.valor_aleatorio:\n print('Kick a higher value!')\n if valor_do_chute == self.valor_aleatorio:\n sg.popup_ok('Congratulations, you got it right!')\n break\n self.janela.close()\n\n def GerarNumeroAleatorio(self):\n self.valor_aleatorio = random.randint(self.valor_minimo, self.valor_maximo)\n\nchute = ChuteONumero()\nchute.Iniciar()\n\n" ]
[ 0 ]
[]
[]
[ "pysimplegui", "python" ]
stackoverflow_0074678831_pysimplegui_python.txt
Q: Rust Vec: How to return error with Result? I have a function with reference input, and return: return value: if input is valid return error: if input is invalid fn get_fourth(input: &Vec<i32>) -> Result<i32, ParseIntError> { let q = match input.get(4) { Some(v) => v, _ => return Err(ParseIntError {kind: ParseIntError} ) }; Ok(*q) } ParseIntError is just temporary for my testing return error. I got error Compiling playground v0.0.1 (/playground) error[E0423]: expected value, found struct `ParseIntError` 6 | _ => return Err(ParseIntError {kind: ParseIntError} ) | ^^^^^^^^^^^^^ | help: use struct literal syntax instead | 6 | _ => return Err(ParseIntError {kind: ParseIntError { kind: val }} ) How do I solved it? Full code use std::num::ParseIntError; fn get_fourth(input: &Vec<i32>) -> Result<i32, ParseIntError> { let q = match input.get(4) { Some(v) => v, _ => return Err(ParseIntError {kind: ParseIntError} ) }; Ok(*q) } fn main() { let my_vec = vec![9, 0, 10]; let fourth = get_fourth(&my_vec); } A: You're returning an error just fine, its your use of ParseIntError that is messed up. You cannot construct an instance of ParseIntError yourself because its fields are private and there's no public constructing function. ParseIntError is just temporary for my testing return error. Well go ahead and make your own non-temporary error and you'll see the rest of your code works just fine: struct LengthError; fn get_fourth(input: &Vec<i32>) -> Result<i32, LengthError> { let q = match input.get(4) { Some(v) => v, _ => return Err(LengthError) }; Ok(*q) }
Rust Vec: How to return error with Result?
I have a function with reference input, and return: return value: if input is valid return error: if input is invalid fn get_fourth(input: &Vec<i32>) -> Result<i32, ParseIntError> { let q = match input.get(4) { Some(v) => v, _ => return Err(ParseIntError {kind: ParseIntError} ) }; Ok(*q) } ParseIntError is just temporary for my testing return error. I got error Compiling playground v0.0.1 (/playground) error[E0423]: expected value, found struct `ParseIntError` 6 | _ => return Err(ParseIntError {kind: ParseIntError} ) | ^^^^^^^^^^^^^ | help: use struct literal syntax instead | 6 | _ => return Err(ParseIntError {kind: ParseIntError { kind: val }} ) How do I solved it? Full code use std::num::ParseIntError; fn get_fourth(input: &Vec<i32>) -> Result<i32, ParseIntError> { let q = match input.get(4) { Some(v) => v, _ => return Err(ParseIntError {kind: ParseIntError} ) }; Ok(*q) } fn main() { let my_vec = vec![9, 0, 10]; let fourth = get_fourth(&my_vec); }
[ "You're returning an error just fine, its your use of ParseIntError that is messed up. You cannot construct an instance of ParseIntError yourself because its fields are private and there's no public constructing function.\n\nParseIntError is just temporary for my testing return error.\n\nWell go ahead and make your own non-temporary error and you'll see the rest of your code works just fine:\nstruct LengthError;\n\nfn get_fourth(input: &Vec<i32>) -> Result<i32, LengthError> {\n let q = match input.get(4) {\n Some(v) => v,\n _ => return Err(LengthError)\n };\n Ok(*q)\n}\n\n" ]
[ 0 ]
[]
[]
[ "error_handling", "rust", "vec" ]
stackoverflow_0074678993_error_handling_rust_vec.txt
Q: How do I copy all folder contents from one location to another - Python? I have been trying to make a python file that will copy contents from one folder to another. I would like it to work on any Windows system that I run it on. It must copy ALL contents, images, videos, etc. I have tried using this shutil code I found online, however it has not worked and shows the message:* Error occurred while copying file.* import shutil # Source path source = "%USERPROFILE%/Downloads/Pictures" # Destination path destination = "%USERPROFILE%/Downloads/Copied_pictures" # Copy the content of # source to destination try: shutil.copy(source, destination) print("File copied successfully.") # If source and destination are same except shutil.SameFileError: print("Source and destination represents the same file.") # If there is any permission issue except PermissionError: print("Permission denied.") # For other errors except: print("Error occurred while copying file.") Please help me resolve this issue, any support is highly appreciated. A: To copy all the contents of a folder, you can use the shutil.copytree method instead of shutil.copy. This method will copy all the contents of the source folder, including any sub-folders and files, to the destination folder. Here is an example of how you can use shutil.copytree to copy the contents of a folder: import shutil # Source path source = "%USERPROFILE%/Downloads/Pictures" # Destination path destination = "%USERPROFILE%/Downloads/Copied_pictures" # Copy the content of # source to destination try: shutil.copytree(source, destination) print("Files copied successfully.") # If source and destination are same except shutil.Error as e: print("Error: %s" % e) # If there is any permission issue except PermissionError: print("Permission denied.") # For other errors except: print("Error occurred while copying files.") Note that you need to catch the Error exception instead of the SameFileError exception when using shutil.copytree, as it can raise different types of errors. You can also specify additional options such as whether to ignore certain types of files or to preserve the file permissions when copying the files. Check the documentation of shutil.copytree for more details.
How do I copy all folder contents from one location to another - Python?
I have been trying to make a python file that will copy contents from one folder to another. I would like it to work on any Windows system that I run it on. It must copy ALL contents, images, videos, etc. I have tried using this shutil code I found online, however it has not worked and shows the message:* Error occurred while copying file.* import shutil # Source path source = "%USERPROFILE%/Downloads/Pictures" # Destination path destination = "%USERPROFILE%/Downloads/Copied_pictures" # Copy the content of # source to destination try: shutil.copy(source, destination) print("File copied successfully.") # If source and destination are same except shutil.SameFileError: print("Source and destination represents the same file.") # If there is any permission issue except PermissionError: print("Permission denied.") # For other errors except: print("Error occurred while copying file.") Please help me resolve this issue, any support is highly appreciated.
[ "To copy all the contents of a folder, you can use the shutil.copytree method instead of shutil.copy. This method will copy all the contents of the source folder, including any sub-folders and files, to the destination folder.\nHere is an example of how you can use shutil.copytree to copy the contents of a folder:\nimport shutil\n\n# Source path\nsource = \"%USERPROFILE%/Downloads/Pictures\"\n\n# Destination path\ndestination = \"%USERPROFILE%/Downloads/Copied_pictures\"\n\n# Copy the content of\n# source to destination\n\ntry:\n shutil.copytree(source, destination)\n print(\"Files copied successfully.\")\n\n# If source and destination are same\nexcept shutil.Error as e:\n print(\"Error: %s\" % e)\n\n# If there is any permission issue\nexcept PermissionError:\n print(\"Permission denied.\")\n\n# For other errors\nexcept:\n print(\"Error occurred while copying files.\")\n\nNote that you need to catch the Error exception instead of the SameFileError exception when using shutil.copytree, as it can raise different types of errors. You can also specify additional options such as whether to ignore certain types of files or to preserve the file permissions when copying the files. Check the documentation of shutil.copytree for more details.\n" ]
[ 0 ]
[]
[]
[ "copy", "copy_paste", "python", "shutil", "windows" ]
stackoverflow_0074679048_copy_copy_paste_python_shutil_windows.txt
Q: Last iteration of loop not completely executed I am currently writing a short script to scrape all outlets from a retailer in my home country. I first scrape all possible postal codes from the website of the postal service, after which I enter these one by one automatically with Selenium in their location finder. After this, I check whether the found locations are already in my result DataFrame and I add the ones that I did not find yet. Here is the code I used: # Define options and webdriver options = webdriver.ChromeOptions() options.add_argument('--ignore-certificate-errors') options.add_argument('--incognito') prefs = {"profile.default_content_setting_values.geolocation" :2} options.add_experimental_option("prefs",prefs) driver = webdriver.Chrome("path", options=options) # Get postal codes driver.get("website post office") soup = BeautifulSoup(driver.page_source) postal_codes = [code.string for code in soup.find_all("tag", class_="class")] # Get retail location driver.get("retail website url") option1_button = driver.find_element(By.XPATH,"xpath") driver.execute_script("arguments[0].click();", option1_button) option2_button = driver.find_element(By.XPATH,"xpath") driver.execute_script("arguments[0].click();", option2_button) outlets = pd.DataFrame(columns = ["Name","Address"]) for i in range(len(postal_codes)): searchbar = driver.find_element(By.XPATH,"xpath") searchbar.clear() searchbar.send_keys(postal_codes[i]) searchbar.send_keys(Keys.RETURN) soup = BeautifulSoup(driver.page_source) names = [name.strong.string for name in soup.find_all("div", class_="class")] addresses = [address.div.string for address in soup.find_all("div", class_="class")] for j in range(len(addresses)): if addresses[j] in outlets["Address"].values: print(addresses[j] + " added already") else: outlets = outlets.append({"Name": names[j],"Address": addresses[j]}, ignore_index=True) I am managing to scrape all of the locations except for the last postal code. The script perfectly manipulates the location finder to open up the retail locations for all postal codes except for the last one in the postal_code list. For this last postal code in the postal_code list, it opens up the webpage correctly and enters the correct postal code, but does not seem to register the addresses and the names for the outlets. When I open up the addresses list and the names list, they still contain the elements of the postal code before the last one. It seems like the loop is not entirely completing. Can someone tell me what the problem is and how to fix this? Thank you! A: import requests import pandas as pd headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0' } def main(url): with requests.Session() as req: req.headers.update(headers) params = { 'q': '9000', 'filter': [ 'KBC_PALO', 'CBC_PALO', ], 'language': 'nl', } r = req.get(url, params=params) df = pd.DataFrame(r.json()['branches']) print(df) if __name__ == "__main__": main('https://www.kbc.be/X9Y-P/elasticsearch-service/api/v3/branches/search') Output: branchId branchName ... saturdayOH cashCd 0 ORG7441 KBC BANK GENT KOUTER ... N;09.00.00;12.00.00 2 1 ORG7426 KBC BANK GENT DE STERRE ... N;09.00.00;12.00.00 2 2 ORG6304 KBC BANK GENT GRAVENSTEEN ... NaN 3 3 ORG3225 KBC BANK GENT WATERSPORTBAAN ... N;09.00.00;12.00.00 3 4 ORG7446 KBC BANK GENTBRUGGE ... NaN 3 5 ORG7447 KBC BANK WONDELGEM ... NaN 3 6 ORG7434 KBC BANK ZWIJNAARDE ... NaN 3 7 ORG7439 KBC BANK MARIAKERKE ... NaN 1 8 ORG3407 KBC BANK OOSTAKKER ... NaN 3 9 ORG3395 KBC BANK ST.-AMANDSBERG ... N;09.00.00;12.00.00 2 [10 rows x 20 columns]
Last iteration of loop not completely executed
I am currently writing a short script to scrape all outlets from a retailer in my home country. I first scrape all possible postal codes from the website of the postal service, after which I enter these one by one automatically with Selenium in their location finder. After this, I check whether the found locations are already in my result DataFrame and I add the ones that I did not find yet. Here is the code I used: # Define options and webdriver options = webdriver.ChromeOptions() options.add_argument('--ignore-certificate-errors') options.add_argument('--incognito') prefs = {"profile.default_content_setting_values.geolocation" :2} options.add_experimental_option("prefs",prefs) driver = webdriver.Chrome("path", options=options) # Get postal codes driver.get("website post office") soup = BeautifulSoup(driver.page_source) postal_codes = [code.string for code in soup.find_all("tag", class_="class")] # Get retail location driver.get("retail website url") option1_button = driver.find_element(By.XPATH,"xpath") driver.execute_script("arguments[0].click();", option1_button) option2_button = driver.find_element(By.XPATH,"xpath") driver.execute_script("arguments[0].click();", option2_button) outlets = pd.DataFrame(columns = ["Name","Address"]) for i in range(len(postal_codes)): searchbar = driver.find_element(By.XPATH,"xpath") searchbar.clear() searchbar.send_keys(postal_codes[i]) searchbar.send_keys(Keys.RETURN) soup = BeautifulSoup(driver.page_source) names = [name.strong.string for name in soup.find_all("div", class_="class")] addresses = [address.div.string for address in soup.find_all("div", class_="class")] for j in range(len(addresses)): if addresses[j] in outlets["Address"].values: print(addresses[j] + " added already") else: outlets = outlets.append({"Name": names[j],"Address": addresses[j]}, ignore_index=True) I am managing to scrape all of the locations except for the last postal code. The script perfectly manipulates the location finder to open up the retail locations for all postal codes except for the last one in the postal_code list. For this last postal code in the postal_code list, it opens up the webpage correctly and enters the correct postal code, but does not seem to register the addresses and the names for the outlets. When I open up the addresses list and the names list, they still contain the elements of the postal code before the last one. It seems like the loop is not entirely completing. Can someone tell me what the problem is and how to fix this? Thank you!
[ "import requests\nimport pandas as pd\n\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0'\n}\n\n\ndef main(url):\n with requests.Session() as req:\n req.headers.update(headers)\n params = {\n 'q': '9000',\n 'filter': [\n 'KBC_PALO',\n 'CBC_PALO',\n ],\n 'language': 'nl',\n }\n r = req.get(url, params=params)\n df = pd.DataFrame(r.json()['branches'])\n print(df)\n\n\nif __name__ == \"__main__\":\n main('https://www.kbc.be/X9Y-P/elasticsearch-service/api/v3/branches/search')\n\nOutput:\n branchId branchName ... saturdayOH cashCd\n0 ORG7441 KBC BANK GENT KOUTER ... N;09.00.00;12.00.00 2\n1 ORG7426 KBC BANK GENT DE STERRE ... N;09.00.00;12.00.00 2\n2 ORG6304 KBC BANK GENT GRAVENSTEEN ... NaN 3\n3 ORG3225 KBC BANK GENT WATERSPORTBAAN ... N;09.00.00;12.00.00 3\n4 ORG7446 KBC BANK GENTBRUGGE ... NaN 3\n5 ORG7447 KBC BANK WONDELGEM ... NaN 3\n6 ORG7434 KBC BANK ZWIJNAARDE ... NaN 3\n7 ORG7439 KBC BANK MARIAKERKE ... NaN 1\n8 ORG3407 KBC BANK OOSTAKKER ... NaN 3\n9 ORG3395 KBC BANK ST.-AMANDSBERG ... N;09.00.00;12.00.00 2\n\n[10 rows x 20 columns]\n\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "selenium_chromedriver", "web_scraping" ]
stackoverflow_0074678059_beautifulsoup_python_selenium_selenium_chromedriver_web_scraping.txt
Q: npm error whenever I try to install a package I recently updated some npm packages and now it throws an error whenever I try to install a package with npm. I am new to npm and JS packages. Attatched is a image of the error. A: As suggested you can run npm install --save --legacy-peer-deps and see if it may resolve your problem. If not you can remove your node-modules folder and your package-lock.json file and run a fresh npm install command. Hope this works for you! A: Try this: Remove your node_modules folder (rm -rf node_modules) npm cache clean -f npm install --legacy-peer-deps
npm error whenever I try to install a package
I recently updated some npm packages and now it throws an error whenever I try to install a package with npm. I am new to npm and JS packages. Attatched is a image of the error.
[ "As suggested you can run npm install --save --legacy-peer-deps and see if it may resolve your problem.\nIf not you can remove your node-modules folder and your package-lock.json file and run a fresh npm install command.\nHope this works for you!\n", "Try this:\n\nRemove your node_modules folder (rm -rf node_modules)\nnpm cache clean -f\nnpm install --legacy-peer-deps\n\n" ]
[ 0, 0 ]
[]
[]
[ "npm", "npm_install", "npm_package", "reactjs" ]
stackoverflow_0074679009_npm_npm_install_npm_package_reactjs.txt
Q: psql pgadmin Procedure error column "trip" does not exist LINE 7: CALL example2(Trip) I want to create a stored procedure in pgadmin that will output the number of rows from the "Trip" table. The table itself is output in cmd, the number of rows in this table is also output in cmd. But when writing a procedure and calling it, such an error comes out. I have psql version 15. How can I fix this error? My code: CREATE PROCEDURE example2(INOUT _name character varying) AS $$ BEGIN SELECT count(*) FROM "_name"; END; $$ LANGUAGE plpgsql; CALL example2(Trip) Error: ERROR: ERROR: The "trip" column does not exist LINE 7: CALL example2(Trip) A: You are better off using a function then a procedure as it is easier to get value out. Using dynamic SQL along with the format function to properly quote the _name parameter. CREATE OR REPLACE FUNCTION public.example2(_name character varying) RETURNS integer LANGUAGE plpgsql AS $function$ DECLARE ct integer; BEGIN EXECUTE format('SELECT count(*) FROM %I', _name) INTO ct; RETURN ct; END; $function$ select example2('animals'); example2 ---------- 8
psql pgadmin Procedure error column "trip" does not exist LINE 7: CALL example2(Trip)
I want to create a stored procedure in pgadmin that will output the number of rows from the "Trip" table. The table itself is output in cmd, the number of rows in this table is also output in cmd. But when writing a procedure and calling it, such an error comes out. I have psql version 15. How can I fix this error? My code: CREATE PROCEDURE example2(INOUT _name character varying) AS $$ BEGIN SELECT count(*) FROM "_name"; END; $$ LANGUAGE plpgsql; CALL example2(Trip) Error: ERROR: ERROR: The "trip" column does not exist LINE 7: CALL example2(Trip)
[ "You are better off using a function then a procedure as it is easier to get value out. Using dynamic SQL along with the format function to properly quote the _name parameter.\nCREATE OR REPLACE FUNCTION public.example2(_name character varying)\n RETURNS integer\n LANGUAGE plpgsql\nAS $function$\nDECLARE\n ct integer;\nBEGIN\n EXECUTE format('SELECT count(*) FROM %I', _name) INTO ct;\n RETURN ct;\nEND;\n$function$\n\n\nselect example2('animals');\n example2 \n----------\n 8\n\n\n\n" ]
[ 0 ]
[]
[]
[ "plpgsql", "postgresql", "procedure" ]
stackoverflow_0074677967_plpgsql_postgresql_procedure.txt
Q: I'm getting an "Execution Timed Out" error? I'm trying to improve my algorithm skills. When I run my code, I get an "Execution Timed Out" error. Pseudocode [This is writen in pseudocode] if(number is even) number = number / 2 if(number is odd) number = 3*number + 1 My Code def hotpo(n): calculator = 0 while n >= 1: if n % 2 == 0: n = n / 2 else: n = 3 * n + 1 calculator = calculator + 1 return calculator A: you are dividing number by 2 if number is even but multiplying it by 3 and adding 1 into it. so for any number it will keep doing this 2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,..... you just have to change condition to n>1 in while loop because at last 2 will come and it got divided by 2, then n becomes 1 then again it will consider 1 as odd as per your condition then again 1*3+1=4 and again 4/2=2 and so on... I hope you understood..
I'm getting an "Execution Timed Out" error?
I'm trying to improve my algorithm skills. When I run my code, I get an "Execution Timed Out" error. Pseudocode [This is writen in pseudocode] if(number is even) number = number / 2 if(number is odd) number = 3*number + 1 My Code def hotpo(n): calculator = 0 while n >= 1: if n % 2 == 0: n = n / 2 else: n = 3 * n + 1 calculator = calculator + 1 return calculator
[ "you are dividing number by 2 if number is even but multiplying it by 3 and adding 1 into it.\nso for any number it will keep doing this\n2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,.....\nyou just have to change condition to n>1 in while loop\nbecause at last 2 will come and it got divided by 2, then n becomes 1 then again it will consider 1 as odd as per your condition then again 1*3+1=4 and again 4/2=2 and so on...\nI hope you understood..\n" ]
[ 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0074678975_algorithm_python.txt
Q: Google form uploaded files need to be grouped in one folder automatically I have a Google Form that allows users to fill business details and then add JPG files at the end of the form. I need a Apps Script that: Creates a folder in Drive. The name of the folder should be same as the input received in the second input field "Business Name". Move all the file received in that responce to that folder. I have tried: function onFormSubmit(e) { const folderId = "1VXzzzzzzzzzzzzzz"; const form = FormApp.getActiveForm(); const formResponses = form.getResponses(); const itemResponses = formResponses[formResponses.length-1].getItemResponses(); Utilities.sleep(3000); // This line might not be required. // Prepare the folder. const destFolder = DriveApp.getFolderById(folderId); const folderName = itemResponses[0].getResponse(); const subFolder = destFolder.getFoldersByName(folderName); const folder = subFolder.hasNext() ? subFolder : destFolder.createFolder(folderName); // Move files to the folder. itemResponses[1].getResponse().forEach(id => DriveApp.getFileById(id).moveTo(folder)); } But, this is not a complete solution as it re-creates the same folder everytime I run the script. If I can run this script on form submit then it would be great. A: The subFolder variable does not point to a folder but to an instance of the DriveApp.FolderIterator class. To get a folder, use .next(), like this: const folder = subFolder.hasNext() ? subFolder.next() : destFolder.createFolder(folderName);
Google form uploaded files need to be grouped in one folder automatically
I have a Google Form that allows users to fill business details and then add JPG files at the end of the form. I need a Apps Script that: Creates a folder in Drive. The name of the folder should be same as the input received in the second input field "Business Name". Move all the file received in that responce to that folder. I have tried: function onFormSubmit(e) { const folderId = "1VXzzzzzzzzzzzzzz"; const form = FormApp.getActiveForm(); const formResponses = form.getResponses(); const itemResponses = formResponses[formResponses.length-1].getItemResponses(); Utilities.sleep(3000); // This line might not be required. // Prepare the folder. const destFolder = DriveApp.getFolderById(folderId); const folderName = itemResponses[0].getResponse(); const subFolder = destFolder.getFoldersByName(folderName); const folder = subFolder.hasNext() ? subFolder : destFolder.createFolder(folderName); // Move files to the folder. itemResponses[1].getResponse().forEach(id => DriveApp.getFileById(id).moveTo(folder)); } But, this is not a complete solution as it re-creates the same folder everytime I run the script. If I can run this script on form submit then it would be great.
[ "The subFolder variable does not point to a folder but to an instance of the DriveApp.FolderIterator class. To get a folder, use .next(), like this:\n const folder = subFolder.hasNext() ? subFolder.next() : destFolder.createFolder(folderName);\n\n" ]
[ 0 ]
[]
[]
[ "google_apps_script", "google_drive_api", "google_forms", "triggers" ]
stackoverflow_0074678961_google_apps_script_google_drive_api_google_forms_triggers.txt
Q: Xcode XCUItest LaunchTests - how do they work If I create a new Xcode project with Xcode 14 with checked 'Include Tests' checkbox it creates 2 files in the UITests folder: I am interested in the second one: the [Project]LaunchTests.swift file. There is this automatically generated code: func testLaunch() throws { let app = XCUIApplication() app.launch() // Insert steps here to perform after app launch but before taking a screenshot, // such as logging into a test account or navigating somewhere in the app let attachment = XCTAttachment(screenshot: app.screenshot()) attachment.name = "Launch Screen" attachment.lifetime = .keepAlways add(attachment) } If I run this test from the diamond in the code, it runs 4 tests that I can view in the report navigator: Xcode runs these 4 tests, but I didn't define them anywhere. Question: where can I find the definition of that tests? Is this kind of an internal testplan which is associated with the LaunchTests file? Where can I find more information about this? It looks like there is a way to run tests with changing light/dark mode and changing orientation without writing a line of code. Thanks in advance. A: If you don't want the four variants of the test to run, then do not (as the template does) return the runsForEachTargetApplicationUIConfiguration value for this test class as true. As the documentation tells you, when this is true, the test runner consults your actual app target to see what variants it has (light and dark mode, orientations, language localizations).
Xcode XCUItest LaunchTests - how do they work
If I create a new Xcode project with Xcode 14 with checked 'Include Tests' checkbox it creates 2 files in the UITests folder: I am interested in the second one: the [Project]LaunchTests.swift file. There is this automatically generated code: func testLaunch() throws { let app = XCUIApplication() app.launch() // Insert steps here to perform after app launch but before taking a screenshot, // such as logging into a test account or navigating somewhere in the app let attachment = XCTAttachment(screenshot: app.screenshot()) attachment.name = "Launch Screen" attachment.lifetime = .keepAlways add(attachment) } If I run this test from the diamond in the code, it runs 4 tests that I can view in the report navigator: Xcode runs these 4 tests, but I didn't define them anywhere. Question: where can I find the definition of that tests? Is this kind of an internal testplan which is associated with the LaunchTests file? Where can I find more information about this? It looks like there is a way to run tests with changing light/dark mode and changing orientation without writing a line of code. Thanks in advance.
[ "If you don't want the four variants of the test to run, then do not (as the template does) return the runsForEachTargetApplicationUIConfiguration value for this test class as true.\nAs the documentation tells you, when this is true, the test runner consults your actual app target to see what variants it has (light and dark mode, orientations, language localizations).\n" ]
[ 1 ]
[]
[]
[ "xcode", "xcuitest" ]
stackoverflow_0074678950_xcode_xcuitest.txt
Q: Selenium with python : failed to click on the button to switch the language of a website I am trying to go to the french version of this website : https://ciqual.anses.fr/. I tried to click on the button 'FR' but nothing happens, I am still on the english page. Here is my code : from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--no-sandbox') chrome_options.add_argument("--headless") driver = webdriver.Chrome("chromedriver", options=chrome_options) driver.get('https://ciqual.anses.fr/') switch_to_french = driver.find_element("xpath", "//a[@id='fr-switch']") ActionChains(driver).move_to_element(switch_to_french).click() #to see what happened : from IPython.display import Image png = driver.get_screenshot_as_png() Image(png, width='500') #I am still on the english website Please help ! A: Try this: switch_to_french = driver.find_element(By.XPATH, "//a[@id='fr-switch']") driver.execute_script("arguments[0].click();", switch_to_french)
Selenium with python : failed to click on the button to switch the language of a website
I am trying to go to the french version of this website : https://ciqual.anses.fr/. I tried to click on the button 'FR' but nothing happens, I am still on the english page. Here is my code : from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--no-sandbox') chrome_options.add_argument("--headless") driver = webdriver.Chrome("chromedriver", options=chrome_options) driver.get('https://ciqual.anses.fr/') switch_to_french = driver.find_element("xpath", "//a[@id='fr-switch']") ActionChains(driver).move_to_element(switch_to_french).click() #to see what happened : from IPython.display import Image png = driver.get_screenshot_as_png() Image(png, width='500') #I am still on the english website Please help !
[ "Try this:\nswitch_to_french = driver.find_element(By.XPATH, \"//a[@id='fr-switch']\")\ndriver.execute_script(\"arguments[0].click();\", switch_to_french)\n\n" ]
[ 0 ]
[]
[]
[ "click", "python", "selenium" ]
stackoverflow_0074678963_click_python_selenium.txt
Q: How would one merge 2 data frames based on a category and numeric in df1 - matching the category and finding a value falling within the range of df2? I want to merge df1 and df2, by pulling in only the numerics from df2 into df1? This would be a nested (Lookup(xlookup) in excel, but Im having difficulty working this in r? Any info would be much appreciated. df1 <- data.frame(Names = c("A","B","C","D","E"), Rank = c("R1","R3","R4","R2","R5"), Time_in_rank = c(2,4.25,3,1.5,5)) df2 <- data.frame(Time_in_rank =c(0,1,2,3,4), R1 =c(20000,25000,30000,35000,40000), R2 =c(45000,50000,55000,60000,65000), R3 =c(70000,75000,80000,85000,90000), R4 =c(95000,96000,97000,98000,100000), R5 =c(105000,107000,109000,111000,112000)) Desired output Names Time_in_rank Rank Salary A 2 R1 30000 B 4.25 R3 90000 C 3 R4 98000 Close but no cigar - Merge two data frames considering a range match between key columns Close but still no cigar - Complex non-equi merge in R A: data.table library(data.table) setDT(df1) setDT(df2) df1[setnames(melt(df2, id.vars = "Time_in_rank"), 1, "tir" )[, tir2 := shift(tir, type = "lead", fill = Inf), by = variable], Salary := value, on = .(Rank == variable, Time_in_rank >= tir, Time_in_rank < tir2)] df1 # Names Rank Time_in_rank Salary # <char> <char> <num> <num> # 1: A R1 2.00 30000 # 2: B R3 4.25 90000 # 3: C R4 3.00 98000 # 4: D R2 1.50 50000 # 5: E R5 5.00 112000 A: You could use a tidyverse approach: library(dplyr) library(tidyr) df1 %>% mutate(time_floor = floor(Time_in_rank)) %>% left_join(df2 %>% pivot_longer(-Time_in_rank, names_to = "Rank", values_to = "Salary"), by = c("Rank", "time_floor" = "Time_in_rank")) %>% select(-time_floor) This returns Names Rank Time_in_rank Salary 1 A R1 2.00 30000 2 B R3 4.25 90000 3 C R4 3.00 98000 4 D R2 1.50 50000 5 E R5 5.00 NA The main ideas are: df1's Time_in_rank rounded down corresponds to Time_in_rank used in df2. df2 is converted into a long format to join by time and rank.
How would one merge 2 data frames based on a category and numeric in df1 - matching the category and finding a value falling within the range of df2?
I want to merge df1 and df2, by pulling in only the numerics from df2 into df1? This would be a nested (Lookup(xlookup) in excel, but Im having difficulty working this in r? Any info would be much appreciated. df1 <- data.frame(Names = c("A","B","C","D","E"), Rank = c("R1","R3","R4","R2","R5"), Time_in_rank = c(2,4.25,3,1.5,5)) df2 <- data.frame(Time_in_rank =c(0,1,2,3,4), R1 =c(20000,25000,30000,35000,40000), R2 =c(45000,50000,55000,60000,65000), R3 =c(70000,75000,80000,85000,90000), R4 =c(95000,96000,97000,98000,100000), R5 =c(105000,107000,109000,111000,112000)) Desired output Names Time_in_rank Rank Salary A 2 R1 30000 B 4.25 R3 90000 C 3 R4 98000 Close but no cigar - Merge two data frames considering a range match between key columns Close but still no cigar - Complex non-equi merge in R
[ "data.table\nlibrary(data.table)\nsetDT(df1)\nsetDT(df2)\ndf1[setnames(melt(df2, id.vars = \"Time_in_rank\"), 1, \"tir\"\n )[, tir2 := shift(tir, type = \"lead\", fill = Inf), by = variable],\n Salary := value,\n on = .(Rank == variable, Time_in_rank >= tir, Time_in_rank < tir2)]\ndf1\n# Names Rank Time_in_rank Salary\n# <char> <char> <num> <num>\n# 1: A R1 2.00 30000\n# 2: B R3 4.25 90000\n# 3: C R4 3.00 98000\n# 4: D R2 1.50 50000\n# 5: E R5 5.00 112000\n\n", "You could use a tidyverse approach:\nlibrary(dplyr)\nlibrary(tidyr)\n\ndf1 %>% \n mutate(time_floor = floor(Time_in_rank)) %>% \n left_join(df2 %>% \n pivot_longer(-Time_in_rank, names_to = \"Rank\", values_to = \"Salary\"),\n by = c(\"Rank\", \"time_floor\" = \"Time_in_rank\")) %>% \n select(-time_floor)\n\nThis returns\n Names Rank Time_in_rank Salary\n1 A R1 2.00 30000\n2 B R3 4.25 90000\n3 C R4 3.00 98000\n4 D R2 1.50 50000\n5 E R5 5.00 NA\n\nThe main ideas are:\n\ndf1's Time_in_rank rounded down corresponds to Time_in_rank used in df2.\ndf2 is converted into a long format to join by time and rank.\n\n" ]
[ 1, 0 ]
[]
[]
[ "data.table", "dataframe", "merge", "non_equi_join", "r" ]
stackoverflow_0074670295_data.table_dataframe_merge_non_equi_join_r.txt
Q: Jetpack Compose run animation after recomposition Is there any way how to run animation once recomposition (of screen, or some composable) is done? When animation is running and there is recomposition at the same time, animation has very bad performance (it is not smooth at all). I tried delay to delay animation for a while, but I don't think that's a good idea. There must be better way of doing this. A: Please provide producible example so you won't need to ask it again. You can run an animation with Animatable calling animatable.animateTo() inside LaunchedEffect after composition is completed. And instead of creating recomposition by using Modifier.offset(), Modifier.background() you can select Modifiers counterparts with lambda. https://developer.android.com/jetpack/compose/performance/bestpractices#defer-reads You can animate alpha for instance without triggering recomposition after composition is completed inside Draw phase of frame val animatable = remember { Animatable(0f) } LaunchedEffect(key1 = Unit) { animatable.animateTo(1f) } Box( Modifier .size(100.dp) .drawBehind { drawRect(Color.Red.copy(alpha = animatable.value)) } ) https://stackoverflow.com/a/73274631/5457853
Jetpack Compose run animation after recomposition
Is there any way how to run animation once recomposition (of screen, or some composable) is done? When animation is running and there is recomposition at the same time, animation has very bad performance (it is not smooth at all). I tried delay to delay animation for a while, but I don't think that's a good idea. There must be better way of doing this.
[ "Please provide producible example so you won't need to ask it again. You can run an animation with Animatable calling animatable.animateTo() inside LaunchedEffect after composition is completed. And instead of creating recomposition by using Modifier.offset(), Modifier.background() you can select Modifiers counterparts with lambda.\nhttps://developer.android.com/jetpack/compose/performance/bestpractices#defer-reads\nYou can animate alpha for instance without triggering recomposition after composition is completed inside Draw phase of frame\nval animatable = remember {\n Animatable(0f)\n}\n\nLaunchedEffect(key1 = Unit) {\n animatable.animateTo(1f)\n}\n\nBox(\n Modifier\n .size(100.dp)\n .drawBehind {\n drawRect(Color.Red.copy(alpha = animatable.value))\n }\n)\n\nhttps://stackoverflow.com/a/73274631/5457853\n" ]
[ 0 ]
[]
[]
[ "android", "android_jetpack", "android_jetpack_compose", "kotlin" ]
stackoverflow_0074678913_android_android_jetpack_android_jetpack_compose_kotlin.txt
Q: Check whether input checkbox is empty using JavaScript I currently have a filter dropdown containing checkboxes. I have checkboxes for gender and category. I am now trying to make sure that the user will check at least one checkbox each part (gender and category). The problem is I don't know how to check whether the checkbox is empty or not. Below is the partial form for the filter dropdown: <form class="" method="GET" action="manage_product.php"> <h6 class="dropdown-header px-0">Gender</h6> <div class="form-check"> <input class="form-check-input" name="genderFil[]" type="checkbox" value="M" class="genderFil" id="genMale" <?= ($isMale == 1) ? "checked" : ""; ?>> <label class="form-check-label" for="genMale">Male</label> </div> <div class="form-check"> <input class="form-check-input" name="genderFil[]" type="checkbox" value="F" class="genderFil" id="genFemale" <?= ($isFemale == 1) ? "checked" : ""; ?>> <label class="form-check-label" for="genFemale">Female</label> </div> <div class="dropdown-divider"></div> <h6 class="dropdown-header px-0">Category</h6> <div class="form-check"> <input class="form-check-input" name="categoryFil[]" type="checkbox" value="1" class="categoryFil" id="catShoes" <?= ($isShoes == 1) ? "checked" : ""; ?>> <label class="form-check-label" for="catShoes">Shoes</label> </div> <div class="form-check"> <input class="form-check-input" name="categoryFil[]" type="checkbox" value="2" class="categoryFil" id="catPants" <?= ($isPants == 1) ? "checked" : ""; ?>> <label class="form-check-label" for="catPants">Pants</label> </div> <div class="form-check"> <input class="form-check-input" name="categoryFil[]" type="checkbox" value="3" class="categoryFil" id="catShirts" <?= ($isShirts == 1) ? "checked" : ""; ?>> <label class="form-check-label" for="catShirts">Shirts</label> </div> <div class="dropdown-divider"></div> <input type="submit" class="button_primary" name="applyFilter" value="Apply" onclick="checkFilter()"> </form> Below is the javascript that I tried to code: function checkFilter() { var res = true; var checkedGender = $('input[class="genderFil"]:checked').length; if(checkedGender < 1) { alert("Please select at least one gender!"); res = false; } var checkedCategory = $('input[class="categoryFil"]:checked').length; if(checkedCategory < 1) { alert("Please select at least one category!"); res = false; } return res; } It is only can be submitted if there is at least one gender and at least one category checked. How can I check whether the checkbox is empty or not? A: A checkbox has two states: checked and unchecked. To get the state of a checkbox, you follow these steps: First, select the checkbox using a DOM method such as getElementById() or querySelector(). Then, access the checked property of the checkbox element. If its checked property is true, then the checkbox is checked; otherwise, it is not. A: To check whether a checkbox is empty or not using JavaScript, you can use the querySelectorAll() method to select all the checkbox elements in the form, and then check the length property of the resulting NodeList to see if it is greater than 0. Here's an example of how you can use this approach to check whether the checkbox is empty or not: // Get the form element const form = document.querySelector("form"); // Get all the checkbox elements in the form const checkboxes = form.querySelectorAll('input[type="checkbox"]'); // Check if there are any checkboxes in the form if (checkboxes.length === 0) { // There are no checkboxes in the form, so the checkbox is empty console.log("The checkbox is empty"); } else { // There are checkboxes in the form, so the checkbox is not empty console.log("The checkbox is not empty"); } In your specific case, you can use the querySelectorAll() method to select all the checkboxes with the genderFil and categoryFil classes, and then check the length property of the resulting NodeLists to see if there are any checked checkboxes in each group. If there are no checked checkboxes in either group, you can show an alert message to the user and prevent the form from being submitted. Here's how you can modify your checkFilter() function to use this approach: function checkFilter() { // Select all the checkboxes with the "genderFil" class const genderCheckboxes = document.querySelectorAll('.genderFil'); // Check if there are any checked checkboxes in the "genderFil" group if (genderCheckboxes.length === 0) { // There are no checked checkboxes in the "genderFil" group alert("Please select at least one gender!"); return false; } // Select all the checkboxes with the "categoryFil" class const categoryCheckboxes = document.querySelectorAll('.categoryFil'); // Check if there are any checked checkboxes in the "categoryFil" group if (categoryCheckboxes.length === 0) { // There are no checked checkboxes in the "categoryFil" group alert("Please select at least one category!"); return false; } // If there are checked checkboxes in both groups, allow the form to be submitted return true; } A: This will work. function checkFilter() { var res = true; var checkedGender = document.getElementById('genderSelector').querySelectorAll('input[type="checkbox"]:checked').length; if(checkedGender < 1) { alert("Please select at least one gender!"); res = false; return res; } var checkedCategory = document.getElementById('categorySelector').querySelectorAll('input[type="checkbox"]:checked').length; if(checkedCategory < 1) { alert("Please select at least one category!"); res = false; return res; } return res; } <form class="" method="GET" action="manage_product.php" onsubmit="return checkFilter();"> <div id="genderSelector"> <h6 class="dropdown-header px-0">Gender</h6> <div class="form-check"> <input class="form-check-input" name="genderFil[]" type="checkbox" value="M" class="genderFil" id="genMale" <?= ($isMale == 1) ? "checked" : ""; ?>> <label class="form-check-label" for="genMale">Male</label> </div> <div class="form-check"> <input class="form-check-input" name="genderFil[]" type="checkbox" value="F" class="genderFil" id="genFemale" <?= ($isFemale == 1) ? "checked" : ""; ?>> <label class="form-check-label" for="genFemale">Female</label> </div> </div> <div class="dropdown-divider"></div> <div id="categorySelector"> <h6 class="dropdown-header px-0">Category</h6> <div class="form-check"> <input class="form-check-input" name="categoryFil[]" type="checkbox" value="1" class="categoryFil" id="catShoes" <?= ($isShoes == 1) ? "checked" : ""; ?>> <label class="form-check-label" for="catShoes">Shoes</label> </div> <div class="form-check"> <input class="form-check-input" name="categoryFil[]" type="checkbox" value="2" class="categoryFil" id="catPants" <?= ($isPants == 1) ? "checked" : ""; ?>> <label class="form-check-label" for="catPants">Pants</label> </div> <div class="form-check"> <input class="form-check-input" name="categoryFil[]" type="checkbox" value="3" class="categoryFil" id="catShirts" <?= ($isShirts == 1) ? "checked" : ""; ?>> <label class="form-check-label" for="catShirts">Shirts</label> </div> </div> <div class="dropdown-divider"></div> <input type="submit" class="button_primary" name="applyFilter" value="Apply"> </form>
Check whether input checkbox is empty using JavaScript
I currently have a filter dropdown containing checkboxes. I have checkboxes for gender and category. I am now trying to make sure that the user will check at least one checkbox each part (gender and category). The problem is I don't know how to check whether the checkbox is empty or not. Below is the partial form for the filter dropdown: <form class="" method="GET" action="manage_product.php"> <h6 class="dropdown-header px-0">Gender</h6> <div class="form-check"> <input class="form-check-input" name="genderFil[]" type="checkbox" value="M" class="genderFil" id="genMale" <?= ($isMale == 1) ? "checked" : ""; ?>> <label class="form-check-label" for="genMale">Male</label> </div> <div class="form-check"> <input class="form-check-input" name="genderFil[]" type="checkbox" value="F" class="genderFil" id="genFemale" <?= ($isFemale == 1) ? "checked" : ""; ?>> <label class="form-check-label" for="genFemale">Female</label> </div> <div class="dropdown-divider"></div> <h6 class="dropdown-header px-0">Category</h6> <div class="form-check"> <input class="form-check-input" name="categoryFil[]" type="checkbox" value="1" class="categoryFil" id="catShoes" <?= ($isShoes == 1) ? "checked" : ""; ?>> <label class="form-check-label" for="catShoes">Shoes</label> </div> <div class="form-check"> <input class="form-check-input" name="categoryFil[]" type="checkbox" value="2" class="categoryFil" id="catPants" <?= ($isPants == 1) ? "checked" : ""; ?>> <label class="form-check-label" for="catPants">Pants</label> </div> <div class="form-check"> <input class="form-check-input" name="categoryFil[]" type="checkbox" value="3" class="categoryFil" id="catShirts" <?= ($isShirts == 1) ? "checked" : ""; ?>> <label class="form-check-label" for="catShirts">Shirts</label> </div> <div class="dropdown-divider"></div> <input type="submit" class="button_primary" name="applyFilter" value="Apply" onclick="checkFilter()"> </form> Below is the javascript that I tried to code: function checkFilter() { var res = true; var checkedGender = $('input[class="genderFil"]:checked').length; if(checkedGender < 1) { alert("Please select at least one gender!"); res = false; } var checkedCategory = $('input[class="categoryFil"]:checked').length; if(checkedCategory < 1) { alert("Please select at least one category!"); res = false; } return res; } It is only can be submitted if there is at least one gender and at least one category checked. How can I check whether the checkbox is empty or not?
[ "A checkbox has two states: checked and unchecked.\nTo get the state of a checkbox, you follow these steps:\nFirst, select the checkbox using a DOM method such as getElementById() or querySelector().\nThen, access the checked property of the checkbox element. If its checked property is true, then the checkbox is checked; otherwise, it is not.\n", "To check whether a checkbox is empty or not using JavaScript, you can use the querySelectorAll() method to select all the checkbox elements in the form, and then check the length property of the resulting NodeList to see if it is greater than 0.\nHere's an example of how you can use this approach to check whether the checkbox is empty or not:\n// Get the form element\nconst form = document.querySelector(\"form\");\n\n// Get all the checkbox elements in the form\nconst checkboxes = form.querySelectorAll('input[type=\"checkbox\"]');\n\n// Check if there are any checkboxes in the form\nif (checkboxes.length === 0) {\n // There are no checkboxes in the form, so the checkbox is empty\n console.log(\"The checkbox is empty\");\n} else {\n // There are checkboxes in the form, so the checkbox is not empty\n console.log(\"The checkbox is not empty\");\n}\n\nIn your specific case, you can use the querySelectorAll() method to select all the checkboxes with the genderFil and categoryFil classes, and then check the length property of the resulting NodeLists to see if there are any checked checkboxes in each group. If there are no checked checkboxes in either group, you can show an alert message to the user and prevent the form from being submitted.\nHere's how you can modify your checkFilter() function to use this approach:\nfunction checkFilter() {\n // Select all the checkboxes with the \"genderFil\" class\n const genderCheckboxes = document.querySelectorAll('.genderFil');\n\n // Check if there are any checked checkboxes in the \"genderFil\" group\n if (genderCheckboxes.length === 0) {\n // There are no checked checkboxes in the \"genderFil\" group\n alert(\"Please select at least one gender!\");\n return false;\n }\n\n // Select all the checkboxes with the \"categoryFil\" class\n const categoryCheckboxes = document.querySelectorAll('.categoryFil');\n\n // Check if there are any checked checkboxes in the \"categoryFil\" group\n if (categoryCheckboxes.length === 0) {\n // There are no checked checkboxes in the \"categoryFil\" group\n alert(\"Please select at least one category!\");\n return false;\n }\n\n // If there are checked checkboxes in both groups, allow the form to be submitted\n return true;\n}\n\n", "This will work.\n\n\nfunction checkFilter()\n{\n var res = true;\n\n\n var checkedGender = document.getElementById('genderSelector').querySelectorAll('input[type=\"checkbox\"]:checked').length; \n if(checkedGender < 1)\n {\n alert(\"Please select at least one gender!\");\n res = false;\n return res;\n }\n\n\n var checkedCategory = document.getElementById('categorySelector').querySelectorAll('input[type=\"checkbox\"]:checked').length;\n if(checkedCategory < 1)\n {\n alert(\"Please select at least one category!\");\n res = false;\n return res;\n }\n\n return res;\n}\n<form class=\"\" method=\"GET\" action=\"manage_product.php\" onsubmit=\"return checkFilter();\">\n <div id=\"genderSelector\">\n <h6 class=\"dropdown-header px-0\">Gender</h6>\n <div class=\"form-check\">\n <input class=\"form-check-input\" name=\"genderFil[]\" type=\"checkbox\" value=\"M\" class=\"genderFil\" id=\"genMale\" <?= ($isMale == 1) ? \"checked\" : \"\"; ?>>\n <label class=\"form-check-label\" for=\"genMale\">Male</label>\n </div>\n <div class=\"form-check\">\n <input class=\"form-check-input\" name=\"genderFil[]\" type=\"checkbox\" value=\"F\" class=\"genderFil\" id=\"genFemale\" <?= ($isFemale == 1) ? \"checked\" : \"\"; ?>>\n <label class=\"form-check-label\" for=\"genFemale\">Female</label>\n </div>\n </div>\n\n <div class=\"dropdown-divider\"></div>\n\n <div id=\"categorySelector\">\n <h6 class=\"dropdown-header px-0\">Category</h6>\n <div class=\"form-check\">\n <input class=\"form-check-input\" name=\"categoryFil[]\" type=\"checkbox\" value=\"1\" class=\"categoryFil\" id=\"catShoes\" <?= ($isShoes == 1) ? \"checked\" : \"\"; ?>>\n <label class=\"form-check-label\" for=\"catShoes\">Shoes</label>\n </div>\n <div class=\"form-check\">\n <input class=\"form-check-input\" name=\"categoryFil[]\" type=\"checkbox\" value=\"2\" class=\"categoryFil\" id=\"catPants\" <?= ($isPants == 1) ? \"checked\" : \"\"; ?>>\n <label class=\"form-check-label\" for=\"catPants\">Pants</label>\n </div>\n <div class=\"form-check\">\n <input class=\"form-check-input\" name=\"categoryFil[]\" type=\"checkbox\" value=\"3\" class=\"categoryFil\" id=\"catShirts\" <?= ($isShirts == 1) ? \"checked\" : \"\"; ?>>\n <label class=\"form-check-label\" for=\"catShirts\">Shirts</label>\n </div>\n </div>\n\n <div class=\"dropdown-divider\"></div>\n <input type=\"submit\" class=\"button_primary\" name=\"applyFilter\" value=\"Apply\">\n</form>\n\n\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "javascript" ]
stackoverflow_0074678134_javascript.txt
Q: vue error 'Avoided redundant navigation to current location' when trying to reload page with new params I'm trying to reload page with new params on state changed: @Watch('workspace') onWorkspaceChanged(o: Workspace, n: Workspace){ if(o.type === n.type && o.id === n.id) return; this.$router.push({name: this.$route.name as string, params: {id: `${n.id}`, type: `${ n.type == WorkspaceType.COMPANY ? COMPANY : PERSON }`}}); } but receive error Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "previous location". I expect path to be changed from /profile/c/123, where 'c' is type param and 123 is id param, to /profile/p/321 and vice versa A: You should use the "replace" method instead of "push" in the router.push call: this.$router.replace({name: this.$route.name as string, params: {id: `${n.id}`, type: `${ n.type == WorkspaceType.COMPANY ? COMPANY : PERSON }`}}); A: I found the problem. It's not in the router. I messed up function arguments. In watcher function first argument should be new value. Thanks for trying to help
vue error 'Avoided redundant navigation to current location' when trying to reload page with new params
I'm trying to reload page with new params on state changed: @Watch('workspace') onWorkspaceChanged(o: Workspace, n: Workspace){ if(o.type === n.type && o.id === n.id) return; this.$router.push({name: this.$route.name as string, params: {id: `${n.id}`, type: `${ n.type == WorkspaceType.COMPANY ? COMPANY : PERSON }`}}); } but receive error Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "previous location". I expect path to be changed from /profile/c/123, where 'c' is type param and 123 is id param, to /profile/p/321 and vice versa
[ "You should use the \"replace\" method instead of \"push\" in the router.push call:\nthis.$router.replace({name: this.$route.name as string, params: {id: `${n.id}`, type: `${ n.type == WorkspaceType.COMPANY ? COMPANY : PERSON }`}});\n\n", "I found the problem. It's not in the router. I messed up function arguments. In watcher function first argument should be new value.\nThanks for trying to help\n" ]
[ 0, 0 ]
[]
[]
[ "typescript", "vue.js", "vue_router" ]
stackoverflow_0074675207_typescript_vue.js_vue_router.txt
Q: Error When Handling Json Data From API Get Request I am trying to access an int value from the key "market_cap_rank", within the first json object. the code below auto aborts the program and return "exited with code 3." also when i parsed the "r.text" ive noticed that it gives me entirly different json data! #include <cpr/cpr.h> #include <iostream> #include <nlohmann/json.hpp> #include <string> // for convenience using json = nlohmann::json; using namespace cpr; using namespace std; int main() { auto v = Get(Url{ "https://api.coingecko.com/api/v3/search?query=bitcoin" }); json data = json::parse(v.text); cout << "Rank: " << data["coins"]["market_cap_rank"] << endl; } I was expecting for the output to be "Rank: 1" A: From your comment, the issue is that data["coins"] is in fact a list of object; thus, data["coins"]["market_cap_rank"] does not make sense. You probably want to do: for ( json &item : data["coins"] ) { std::cout << "Item with id " << item["id"] << " has market cap rank of " << item["market_cap_rank"] << '\n'; }
Error When Handling Json Data From API Get Request
I am trying to access an int value from the key "market_cap_rank", within the first json object. the code below auto aborts the program and return "exited with code 3." also when i parsed the "r.text" ive noticed that it gives me entirly different json data! #include <cpr/cpr.h> #include <iostream> #include <nlohmann/json.hpp> #include <string> // for convenience using json = nlohmann::json; using namespace cpr; using namespace std; int main() { auto v = Get(Url{ "https://api.coingecko.com/api/v3/search?query=bitcoin" }); json data = json::parse(v.text); cout << "Rank: " << data["coins"]["market_cap_rank"] << endl; } I was expecting for the output to be "Rank: 1"
[ "From your comment, the issue is that data[\"coins\"] is in fact a list of object; thus, data[\"coins\"][\"market_cap_rank\"] does not make sense. You probably want to do:\nfor ( json &item : data[\"coins\"] ) {\n std::cout << \"Item with id \" << item[\"id\"] \n << \" has market cap rank of \" << item[\"market_cap_rank\"] << '\\n';\n}\n\n" ]
[ 0 ]
[]
[]
[ "c++", "json", "nlohmann_json" ]
stackoverflow_0074678489_c++_json_nlohmann_json.txt
Q: How can I extract the coefficient of a specific variable in an equation in R? For example, I have a string like "2 * a + 3 * b". I already have something that checks if a certain variable exists in the expression. So for example I input b, how could I make it return the 3? A: Not sure I understand you 100%. But if it is that you have a string and want to see the digit(s) that occur immediately prior to b, then you can use str_extract: library(stringr) str_extract(x, "\\d+(?=b)") [1] "3" This works by the look-ahead (?=b), which assterts that the digit(s) to be extracted must be followed by the character b. If you need the extracted substring in numeric format: as.numeric(str_extract(x, "\\d+(?=b)")) Data: x <- "2a+3b" A: If we know that the formula is linear, as in the example in the question, then we can take the derivative. # inputs s <- "2 * a + 3 * b" var <- "b" D(parse(text = s), var) ## [1] 3
How can I extract the coefficient of a specific variable in an equation in R?
For example, I have a string like "2 * a + 3 * b". I already have something that checks if a certain variable exists in the expression. So for example I input b, how could I make it return the 3?
[ "Not sure I understand you 100%. But if it is that you have a string and want to see the digit(s) that occur immediately prior to b, then you can use str_extract:\nlibrary(stringr)\nstr_extract(x, \"\\\\d+(?=b)\")\n[1] \"3\"\n\nThis works by the look-ahead (?=b), which assterts that the digit(s) to be extracted must be followed by the character b. If you need the extracted substring in numeric format:\nas.numeric(str_extract(x, \"\\\\d+(?=b)\"))\n\nData:\nx <- \"2a+3b\"\n\n", "If we know that the formula is linear, as in the example in the question, then we can take the derivative.\n# inputs\ns <- \"2 * a + 3 * b\"\nvar <- \"b\"\n\nD(parse(text = s), var)\n## [1] 3\n\n" ]
[ 1, 1 ]
[ "To extract the coefficient of a specific variable in an equation in R, you can use the lm() function to fit a linear model, and then use the coef() function to extract the coefficients.\nFor example, if you have an equation y = 2x + 3 and you want to extract the coefficient of the x variable, you can use the following code:\n# Fit a linear model to the equation\nmodel <- lm(y ~ x)\n\n# Extract the coefficients\ncoef(model)\n\nThis will return the coefficients of the equation, including the coefficient of the x variable, which in this case is 2.\n" ]
[ -1 ]
[ "r", "string" ]
stackoverflow_0074675913_r_string.txt
Q: How to check if any app is installed during XCTest? I need to check if an app with a particular bundleIdentifier is installed on the active device or Simulator and I need to do this from an XC UI test. I've tried doing: import XCTest class ServerLoop: XCTestCase { func testRunAppInstalled() async throws { let app = XCUIApplication("pl.bartekpacia.SomeApp") if app.exists { // code } } } but unfortunately it only tells me if the app is currently open, not installed. I want to be able to check if any app is installed, not only my apps. I need this because if the app with bundleId is not installed and I do XCUIApplication(bundleId), then the test fails and there's no way to prevent it from doing so. A: I couldn't make it work with the bundle identifier. But if you have the name of the app as it is visible on springboard, this code works in my tests: func test_existence() { let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard") let appIcon = springboard.icons["Settings"] if appIcon.exists { print("YEAH!") } else { XCTFail() } } A: It seems like the SpringBoard solution is a good one. You could also attempt a launch of an XCUIApplication and expect a fail on the test with XCTExpectFailure in nonStrict mode, with the continueAfterFailure property on XCTestCase set to true.
How to check if any app is installed during XCTest?
I need to check if an app with a particular bundleIdentifier is installed on the active device or Simulator and I need to do this from an XC UI test. I've tried doing: import XCTest class ServerLoop: XCTestCase { func testRunAppInstalled() async throws { let app = XCUIApplication("pl.bartekpacia.SomeApp") if app.exists { // code } } } but unfortunately it only tells me if the app is currently open, not installed. I want to be able to check if any app is installed, not only my apps. I need this because if the app with bundleId is not installed and I do XCUIApplication(bundleId), then the test fails and there's no way to prevent it from doing so.
[ "I couldn't make it work with the bundle identifier. But if you have the name of the app as it is visible on springboard, this code works in my tests:\nfunc test_existence() {\n let springboard = XCUIApplication(bundleIdentifier: \"com.apple.springboard\")\n let appIcon = springboard.icons[\"Settings\"]\n if appIcon.exists {\n print(\"YEAH!\")\n } else {\n XCTFail()\n }\n}\n\n", "It seems like the SpringBoard solution is a good one.\nYou could also attempt a launch of an XCUIApplication and expect a fail on the test with XCTExpectFailure in nonStrict mode, with the continueAfterFailure property on XCTestCase set to true.\n" ]
[ 1, 0 ]
[]
[]
[ "ios", "swift", "xctest", "xcuitest" ]
stackoverflow_0073976961_ios_swift_xctest_xcuitest.txt
Q: Gets RefrenceErrors: "Property 'Ionicons' doesn't exist" So im trying to add a bottom navbar in my ReactNative project. But everytime I try to run the project i get an error. This is the message i get: I also get a warning saying: Bottom Tab Navigator: 'tabBarOptions' is deprecated. Migrate the options to 'screenOptions' instead. I have tried to edit the edit the Ionicons code, by doing this: return <IonIcon icon={iconName.props}></IonIcon>; Here is the code: import React, { Component } from "react"; import { Text, View, StyleSheet, Image, TextInput, ScrollView, SafeAreaView, TouchableOpacity } from "react-native"; import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; // Screens import HomeScreen from './screens/HomeScreen'; import DetailsScreen from './screens/DetailsScreen'; import SettingsScreen from './screens/SettingsScreen.js'; //Screen names const homeName = "Home"; const detailsName = "Details"; const settingsName = "Settings"; const Tab = createBottomTabNavigator(); function MainContainer() { return ( <NavigationContainer> <Tab.Navigator initialRouteName={homeName} screenOptions={({ route }) => ({ tabBarIcon: ({ focused, color, size }) => { let iconName; let rn = route.name; if (rn === homeName) { iconName = focused ? 'home' : 'home-outline'; } else if (rn === detailsName) { iconName = focused ? 'list' : 'list-outline'; } else if (rn === settingsName) { iconName = focused ? 'settings' : 'settings-outline'; } // You can return any component that you like here! return <Ionicons name={iconName} size={size} color={color} />; }, })} tabBarOptions={{ "tabBarActiveTintColor": "tomato", "tabBarInactiveTintColor": "grey", "tabBarLabelStyle": { "paddingBottom": 10, "fontSize": 10 }, "tabBarStyle": [ { "display": "flex" }, null ] }}> <Tab.Screen name={homeName} component={HomeScreen} /> <Tab.Screen name={detailsName} component={DetailsScreen} /> <Tab.Screen name={settingsName} component={SettingsScreen} /> </Tab.Navigator> </NavigationContainer> ); } export default MainContainer; A: Are you using expo? If so, you need to import. import Ionicons from '@expo/vector-icons/Ionicons';
Gets RefrenceErrors: "Property 'Ionicons' doesn't exist"
So im trying to add a bottom navbar in my ReactNative project. But everytime I try to run the project i get an error. This is the message i get: I also get a warning saying: Bottom Tab Navigator: 'tabBarOptions' is deprecated. Migrate the options to 'screenOptions' instead. I have tried to edit the edit the Ionicons code, by doing this: return <IonIcon icon={iconName.props}></IonIcon>; Here is the code: import React, { Component } from "react"; import { Text, View, StyleSheet, Image, TextInput, ScrollView, SafeAreaView, TouchableOpacity } from "react-native"; import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; // Screens import HomeScreen from './screens/HomeScreen'; import DetailsScreen from './screens/DetailsScreen'; import SettingsScreen from './screens/SettingsScreen.js'; //Screen names const homeName = "Home"; const detailsName = "Details"; const settingsName = "Settings"; const Tab = createBottomTabNavigator(); function MainContainer() { return ( <NavigationContainer> <Tab.Navigator initialRouteName={homeName} screenOptions={({ route }) => ({ tabBarIcon: ({ focused, color, size }) => { let iconName; let rn = route.name; if (rn === homeName) { iconName = focused ? 'home' : 'home-outline'; } else if (rn === detailsName) { iconName = focused ? 'list' : 'list-outline'; } else if (rn === settingsName) { iconName = focused ? 'settings' : 'settings-outline'; } // You can return any component that you like here! return <Ionicons name={iconName} size={size} color={color} />; }, })} tabBarOptions={{ "tabBarActiveTintColor": "tomato", "tabBarInactiveTintColor": "grey", "tabBarLabelStyle": { "paddingBottom": 10, "fontSize": 10 }, "tabBarStyle": [ { "display": "flex" }, null ] }}> <Tab.Screen name={homeName} component={HomeScreen} /> <Tab.Screen name={detailsName} component={DetailsScreen} /> <Tab.Screen name={settingsName} component={SettingsScreen} /> </Tab.Navigator> </NavigationContainer> ); } export default MainContainer;
[ "Are you using expo? If so, you need to import.\nimport Ionicons from '@expo/vector-icons/Ionicons';\n\n" ]
[ 0 ]
[]
[]
[ "javascript", "react_native", "reactjs", "typescript" ]
stackoverflow_0074675950_javascript_react_native_reactjs_typescript.txt
Q: Why only few flutter plugins require WidgetsFlutterBinding.ensureInitialized()? sqflite requires WidgetsFlutterBinding.ensureInitialized() but not xmpp_plugin, shared_preferences or device_info_plus ? As per my knowledge plugins require platform specific channels due to which WidgetsFlutterBinding.ensureInitialized() is placed in main() function of flutter app. A: You are correct that the WidgetsFlutterBinding.ensureInitialized() method is required by some plugins, such as sqflite, because they require access to platform-specific channels in order to function properly. This is why the ensureInitialized() method is often placed in the main() function of a Flutter app. However, not all plugins require the ensureInitialized() method. For example, the shared_preferences and device_info_plus plugins do not require access to platform-specific channels, so they do not need the ensureInitialized() method to be called. The xmpp_plugin may or may not require the ensureInitialized() method depending on its specific implementation and the features it uses. In general, it is a good practice to call the ensureInitialized() method in the main() function of a Flutter app if any of the plugins used by the app require it. This ensures that the app is properly initialized and all the necessary platform-specific channels are set up before the app starts running. A: Most plugins should not require WidgetsFlutterBinding.ensureInitialized because the WidgetsFlutterBinding instance normally is initialized automatically. Some plugins require that it be explicitly called because they need the instance to be initialized earlier. From the WidgetsFlutterBinding.ensureInitialized documentation: You only need to call this method if you need the binding to be initialized before calling runApp .
Why only few flutter plugins require WidgetsFlutterBinding.ensureInitialized()?
sqflite requires WidgetsFlutterBinding.ensureInitialized() but not xmpp_plugin, shared_preferences or device_info_plus ? As per my knowledge plugins require platform specific channels due to which WidgetsFlutterBinding.ensureInitialized() is placed in main() function of flutter app.
[ "You are correct that the WidgetsFlutterBinding.ensureInitialized() method is required by some plugins, such as sqflite, because they require access to platform-specific channels in order to function properly. This is why the ensureInitialized() method is often placed in the main() function of a Flutter app.\nHowever, not all plugins require the ensureInitialized() method. For example, the shared_preferences and device_info_plus plugins do not require access to platform-specific channels, so they do not need the ensureInitialized() method to be called. The xmpp_plugin may or may not require the ensureInitialized() method depending on its specific implementation and the features it uses.\nIn general, it is a good practice to call the ensureInitialized() method in the main() function of a Flutter app if any of the plugins used by the app require it. This ensures that the app is properly initialized and all the necessary platform-specific channels are set up before the app starts running.\n", "Most plugins should not require WidgetsFlutterBinding.ensureInitialized because the WidgetsFlutterBinding instance normally is initialized automatically. Some plugins require that it be explicitly called because they need the instance to be initialized earlier.\nFrom the WidgetsFlutterBinding.ensureInitialized documentation:\n\nYou only need to call this method if you need the binding to be initialized before calling runApp\n.\n\n" ]
[ 1, 0 ]
[]
[]
[ "dart", "flutter", "flutter_dependencies" ]
stackoverflow_0074677610_dart_flutter_flutter_dependencies.txt
Q: keep getting dai.balanceOf() is not a function So i am trying to make a bot that will automatically swap from dai to usdc continously until the balance of dai in my wallet decreases by 10%. So now i am trying to test this on Goeril test-net where i have deployed the Multiswap Smart contract that will do the swap to Uniswap usdc and Dai pool. But im having the issue on the actual bot itself, everytime im trying to test the script it says that dai.balanceOf() is not a function. I have tried to fix this but i am completely stuck, and i also believe there are other issues with the script too. Could someone please help. Script for the Bot: require("@nomiclabs/hardhat-ethers"); require("dotenv").config(); var fs = require('fs'); const { ethers } = require("hardhat"); const fsPromises = fs.promises; const DAI = '0x6B175474E89094C44Da98b954EedeAC495271d0F'; const ABI_FILE_PATH = 'artifacts/contracts/SwapExamples.sol/SwapExamples.json'; const DEPLOYED_CONTRACT_ADDRESS = '0xAb54Bf58D1cf4F6E5fe14917fa909AaAc4c4cE91'; const dai = ethers.getContractAt("IERC20", DAI); function waitforme(milisec) { return new Promise(resolve => { setTimeout(() => { resolve('') }, milisec); }) } async function getABI() { const data = await fsPromises.readFile(ABI_FILE_PATH, 'utf8'); const abi = JSON.parse(data)['abi']; return abi } async function main() { const {PRIVATE_KEY} = process.env; const {INFURA_GORELI_ENDPOINT_KEY} = process.env; let provider = ethers.getDefaultProvider(`https://eth-goerli.g.alchemy.com/v2/${INFURA_GORELI_ENDPOINT_KEY}`) let signer = new ethers.Wallet(PRIVATE_KEY, provider); const abi = await getABI(); const UniContract = new ethers.Contract(DEPLOYED_CONTRACT_ADDRESS, abi, signer); const balance = await dai.balanceOf(signer); for (let i = 0; i < 111; i++) { const amountIn = balance if (amountIn.mul(10).lte(balance.mul(9))) {break;} await dai.connect(signer).deposit(amountIn); await dai.connect(signer).approve(UniContract, amountIn); // Swap let tx = await UniContract.swapExactInputMultihop(amountIn); await tx.wait(); console.log("DAI balance", balance) await waitforme(1000); } } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); and this is the contract that i have deployed onto the test net: pragma solidity =0.7.6; pragma abicoder v2; import "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol"; import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol"; contract SwapExamples { // NOTE: Does not work with SwapRouter02 ISwapRouter public constant swapRouter = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; /// @notice swapInputMultiplePools swaps a fixed amount of WETH for a maximum possible amount of DAI /// swap USDC --> DAI --> USDC function swapExactInputMultihop(uint amountIn) external returns (uint amountOut) { TransferHelper.safeTransferFrom( DAI, msg.sender, address(this), amountIn ); TransferHelper.safeApprove(DAI, address(swapRouter), amountIn); ISwapRouter.ExactInputParams memory params = ISwapRouter .ExactInputParams({ path: abi.encodePacked( DAI, uint24(500), USDC, uint24(500), DAI ), recipient: msg.sender, deadline: block.timestamp, amountIn: amountIn, amountOutMinimum: 0 }); amountOut = swapRouter.exactInput(params); } } There could be other issues that i am missing so if anyones finds anything else wrong with my script please let me know i would really appreciate it So i have tried to search online to see if i could fix this, essentially i need a continous transaction to be made on the testnet from Dai -> usdc -> Dai again and the balance of dai should deplete until the loop breaks when 10% of the balance is gone. I believe the main culprit could be either this part: require("@nomiclabs/hardhat-ethers"); require("dotenv").config(); var fs = require('fs'); const { ethers } = require("hardhat"); const fsPromises = fs.promises; where i might be missing something or async function main() { const {PRIVATE_KEY} = process.env; const {INFURA_GORELI_ENDPOINT_KEY} = process.env; let provider = ethers.getDefaultProvider(`https://eth-goerli.g.alchemy.com/v2/${INFURA_GORELI_ENDPOINT_KEY}`) let signer = new ethers.Wallet(PRIVATE_KEY, provider); const abi = await getABI(); const UniContract = new ethers.Contract(DEPLOYED_CONTRACT_ADDRESS, abi, signer); const balance = await dai.balanceOf(signer); for (let i = 0; i < 111; i++) { const amountIn = balance if (amountIn.mul(10).lte(balance.mul(9))) {break;} await dai.connect(signer).deposit(amountIn); await dai.connect(signer).approve(UniContract, amountIn); // Swap let tx = await UniContract.swapExactInputMultihop(amountIn); await tx.wait(); console.log("DAI balance", balance) await waitforme(1000); } } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); A: this function is async const dai = ethers.getContractAt("IERC20", DAI); You have to await it but you cannot await on top level. you have to call it inside an async function. in your case you have to call it inside main async function main() { const dai = await ethers.getContractAt("IERC20", DAI); }
keep getting dai.balanceOf() is not a function
So i am trying to make a bot that will automatically swap from dai to usdc continously until the balance of dai in my wallet decreases by 10%. So now i am trying to test this on Goeril test-net where i have deployed the Multiswap Smart contract that will do the swap to Uniswap usdc and Dai pool. But im having the issue on the actual bot itself, everytime im trying to test the script it says that dai.balanceOf() is not a function. I have tried to fix this but i am completely stuck, and i also believe there are other issues with the script too. Could someone please help. Script for the Bot: require("@nomiclabs/hardhat-ethers"); require("dotenv").config(); var fs = require('fs'); const { ethers } = require("hardhat"); const fsPromises = fs.promises; const DAI = '0x6B175474E89094C44Da98b954EedeAC495271d0F'; const ABI_FILE_PATH = 'artifacts/contracts/SwapExamples.sol/SwapExamples.json'; const DEPLOYED_CONTRACT_ADDRESS = '0xAb54Bf58D1cf4F6E5fe14917fa909AaAc4c4cE91'; const dai = ethers.getContractAt("IERC20", DAI); function waitforme(milisec) { return new Promise(resolve => { setTimeout(() => { resolve('') }, milisec); }) } async function getABI() { const data = await fsPromises.readFile(ABI_FILE_PATH, 'utf8'); const abi = JSON.parse(data)['abi']; return abi } async function main() { const {PRIVATE_KEY} = process.env; const {INFURA_GORELI_ENDPOINT_KEY} = process.env; let provider = ethers.getDefaultProvider(`https://eth-goerli.g.alchemy.com/v2/${INFURA_GORELI_ENDPOINT_KEY}`) let signer = new ethers.Wallet(PRIVATE_KEY, provider); const abi = await getABI(); const UniContract = new ethers.Contract(DEPLOYED_CONTRACT_ADDRESS, abi, signer); const balance = await dai.balanceOf(signer); for (let i = 0; i < 111; i++) { const amountIn = balance if (amountIn.mul(10).lte(balance.mul(9))) {break;} await dai.connect(signer).deposit(amountIn); await dai.connect(signer).approve(UniContract, amountIn); // Swap let tx = await UniContract.swapExactInputMultihop(amountIn); await tx.wait(); console.log("DAI balance", balance) await waitforme(1000); } } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); and this is the contract that i have deployed onto the test net: pragma solidity =0.7.6; pragma abicoder v2; import "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol"; import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol"; contract SwapExamples { // NOTE: Does not work with SwapRouter02 ISwapRouter public constant swapRouter = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; /// @notice swapInputMultiplePools swaps a fixed amount of WETH for a maximum possible amount of DAI /// swap USDC --> DAI --> USDC function swapExactInputMultihop(uint amountIn) external returns (uint amountOut) { TransferHelper.safeTransferFrom( DAI, msg.sender, address(this), amountIn ); TransferHelper.safeApprove(DAI, address(swapRouter), amountIn); ISwapRouter.ExactInputParams memory params = ISwapRouter .ExactInputParams({ path: abi.encodePacked( DAI, uint24(500), USDC, uint24(500), DAI ), recipient: msg.sender, deadline: block.timestamp, amountIn: amountIn, amountOutMinimum: 0 }); amountOut = swapRouter.exactInput(params); } } There could be other issues that i am missing so if anyones finds anything else wrong with my script please let me know i would really appreciate it So i have tried to search online to see if i could fix this, essentially i need a continous transaction to be made on the testnet from Dai -> usdc -> Dai again and the balance of dai should deplete until the loop breaks when 10% of the balance is gone. I believe the main culprit could be either this part: require("@nomiclabs/hardhat-ethers"); require("dotenv").config(); var fs = require('fs'); const { ethers } = require("hardhat"); const fsPromises = fs.promises; where i might be missing something or async function main() { const {PRIVATE_KEY} = process.env; const {INFURA_GORELI_ENDPOINT_KEY} = process.env; let provider = ethers.getDefaultProvider(`https://eth-goerli.g.alchemy.com/v2/${INFURA_GORELI_ENDPOINT_KEY}`) let signer = new ethers.Wallet(PRIVATE_KEY, provider); const abi = await getABI(); const UniContract = new ethers.Contract(DEPLOYED_CONTRACT_ADDRESS, abi, signer); const balance = await dai.balanceOf(signer); for (let i = 0; i < 111; i++) { const amountIn = balance if (amountIn.mul(10).lte(balance.mul(9))) {break;} await dai.connect(signer).deposit(amountIn); await dai.connect(signer).approve(UniContract, amountIn); // Swap let tx = await UniContract.swapExactInputMultihop(amountIn); await tx.wait(); console.log("DAI balance", balance) await waitforme(1000); } } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); });
[ "this function is async\n const dai = ethers.getContractAt(\"IERC20\", DAI);\n\nYou have to await it but you cannot await on top level. you have to call it inside an async function. in your case you have to call it inside main\nasync function main() {\n const dai = await ethers.getContractAt(\"IERC20\", DAI);\n}\n\n" ]
[ 0 ]
[]
[]
[ "bots", "ethers.js", "javascript", "solidity", "uniswap" ]
stackoverflow_0074678648_bots_ethers.js_javascript_solidity_uniswap.txt
Q: Getting Parsing error when consuming FileStreamResult Api I have an api that generates an excel file and returns a FileStreamResult as follows: public async Task<IActionResult> GetFile( string id ) { Stream stream = null; //code to generate file return File( stream, "application/octet-stream", $"{id}.xlsx" ); // returns a FileStreamResult } When I then try to call this api I do: FileStreamResult response = (FileStreamResult)await _api.GetFile(id); However I get the following error as well as a 200 Ok code: Unexpected character encountered while parsing value: P. Path '', line 0, position 0. However when I test the GetFile Api from postman it returns a response I know this is a JSON error, but I am not sure how I can correctly handle the API response, any help appreciated. A: Not sure if you cut some code in posting your example, but it looks to me like stream is null. If there is some missing code and you're hydrating the stream, you might consider setting stream.Position = 0; before sending it back. That said, I was able to make your model work with this code: [HttpGet("GetMyFile")] public async Task<IActionResult> GetFile(string id) { Stream stream = System.IO.File.OpenRead(@"C:\temp\myfile.xlsx"); //code to generate file return File(stream, "application/octet-stream", $"{id}.xlsx"); // returns a FileStreamResult }
Getting Parsing error when consuming FileStreamResult Api
I have an api that generates an excel file and returns a FileStreamResult as follows: public async Task<IActionResult> GetFile( string id ) { Stream stream = null; //code to generate file return File( stream, "application/octet-stream", $"{id}.xlsx" ); // returns a FileStreamResult } When I then try to call this api I do: FileStreamResult response = (FileStreamResult)await _api.GetFile(id); However I get the following error as well as a 200 Ok code: Unexpected character encountered while parsing value: P. Path '', line 0, position 0. However when I test the GetFile Api from postman it returns a response I know this is a JSON error, but I am not sure how I can correctly handle the API response, any help appreciated.
[ "Not sure if you cut some code in posting your example, but it looks to me like stream is null. If there is some missing code and you're hydrating the stream, you might consider setting stream.Position = 0; before sending it back. That said, I was able to make your model work with this code:\n [HttpGet(\"GetMyFile\")]\n public async Task<IActionResult> GetFile(string id)\n {\n Stream stream = System.IO.File.OpenRead(@\"C:\\temp\\myfile.xlsx\");\n //code to generate file \n\n return File(stream, \"application/octet-stream\", $\"{id}.xlsx\"); // returns a FileStreamResult\n }\n\n" ]
[ 0 ]
[]
[]
[ "asp.net_mvc", "c#" ]
stackoverflow_0074678978_asp.net_mvc_c#.txt