How Can I Get Google Play to Work on Android Emulator in Android Studio Bumblebee 2021.x.x.x Posted: 10 Apr 2022 02:07 AM PDT The AVD GUI does NOT allow the selection of Play Images for some reason anymore! |
Should i build my own component or should i use react component Library Posted: 10 Apr 2022 02:07 AM PDT I'm deciding whether i should build my own component or use existing one like material UI. When i build my own component styling the component seems easy and i can add features, animation, and whatever i want when building it and i built it rather quickly. I also found out that when using component library like material UI i find myself fighting with material UI more just to make some adjustments in the end i don't have a full freedom to do anything what i want. But some reason majority of the web encourage me to use an existing library component like material UI. Here are an example: https://www.quora.com/Should-you-use-an-existing-UI-framework-e-g-React-Material-UI-or-design-and-build-the-components-from-scratch I just don't understand, I want to build my website/app more unique than other website. I have the skills and experience needed to build one. But i don't know let me know what you think? Tldr; i want to build my own component from scratch since i have the skills to do so. But many blogs encourage me to use existing library. Let me know what you think |
Unable to track free calls for printf Posted: 10 Apr 2022 02:07 AM PDT I'm writing are small memory profiler which is using the LD_PRELOAD trick. Overall it works good for malloc and free. Unfortunately I'm not able to track IO-Operations such as printf. Those functions get tracked correctly at the malloc functions but it didn't seam that they got passed to free. Here are code snippets: void heaptracker_init(void) { ignore = false; // get original symbols libc_hooks.malloc = dlsym(RTLD_NEXT, "malloc"); check_error_dlfcn(libc_hooks.malloc); // for the other primitives as well ... // init list for storing information if ((alloc_list = list_init()) == NULL) return; // does write results from list if (atexit(heaptracker_destroy)) return; initialized = true; stopped = true; // for concurrent access on list ... if ((errno = pthread_mutex_init(&mutex, NULL)) != 0) { return; } stopped = false; } The malloc routine does store the allocations in a list and performs the actual allocation. void *malloc(size_t size) { if (!initialized) heaptracker_init(); void * (*libc_malloc)(size_t) = libc_hooks.malloc; void *p = libc_malloc(size); list_append(alloc_list, infos, p, size, stacktrace_length); return p; } The free routine looks like this: void free(void *ptr) { if (pthread_mutex_lock(&mutex) != 0) return; // does remove list_remove(alloc_list, ptr); errno = pthread_mutex_unlock(&mutex); libc_hooks.free(ptr); } For a small test programm like this one: int main() { printf("Hello World"); char *buffer = malloc(100); return 0; } The expected output should be: { "type": "leak", "bytes": 100, "stacktrace": ["main"] } While the actual output is: [ { "type": "leak", "bytes": 100, "stacktrace": ["main"] }, { "type": "leak", "bytes": 1024, "stacktrace": ["main", "_IO_printf", ..., "_IO_file_doallocate"] } ] |
Selenium - Java - Chrome Headles doesn't use provided user-data-dir when headless Posted: 10 Apr 2022 02:07 AM PDT I am trying to run some tests with Selenium 4.1.3, Chrome 100 and Java 18. The test requires to use a specific Chrome profile. My code works perfectly when Chrome is headed but doesn't work (doesn't use the specified Chrome profile) when headless. My code is below (there's a boolean flag "headless", chaning the values makes the program run headed vs. headless - and working vs. not working): public static void main(String[] args) { try { System.setProperty("webdriver.chrome.driver", "chromedriver.exe"); //System.setProperty("webdriver.chrome.verboseLogging", "false"); ChromeOptions options = new ChromeOptions(); options.addArguments("--window-size=1920,1080"); options.addArguments("--start-maximized"); options.addArguments("start-maximized"); boolean headless = true; if (headless) { options.addArguments("--headless"); options.addArguments("--remote-debugging-port=9222"); //options.setHeadless(true); options.setAcceptInsecureCerts(true); } options.addArguments("--log-level=3"); options.addArguments("--silent"); options.addArguments("no-sandbox"); options.addArguments("--no-sandbox"); options.addArguments("enable-automation"); options.addArguments("--disable-infobars"); options.addArguments("--disable-dev-shm-usage"); options.addArguments("--disable-gpu"); options.addArguments("--disable-custom-jumplist"); options.addArguments("--allow-no-sandbox-job"); options.addArguments("--lang=it-IT"); String userData = "C:\\Chrome\\fravotto19750619\\"; options.addArguments("--user-data-dir=" + userData); //String profileDir = ""; //chromiumOptions.addArguments("--profile-directory=" + profileDir); ChromiumDriver driver = new ChromeDriver(options); driver.navigate().to("https://www.gmail.com"); String fileName = "test.jpeg"; try { File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); File dst = new File(fileName); try (InputStream in = new FileInputStream(src)) { try (OutputStream out = new FileOutputStream(dst)) { byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } } } catch (Exception e) { e.printStackTrace(); } BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); in.readLine(); driver.quit(); System.exit(0); } catch (Exception e) { e.printStackTrace(); } } I tried to play with options (did many attempts) and in similar thread I did not find any solution to this, I assume that the same code should run similarily when headed or headless but there's a kind of difference. Any thought? Thanks |
how can I go about getting the linear impulse required at a position to fully stop a rotating and moving cuboid Posted: 10 Apr 2022 02:07 AM PDT I'm trying to find the impulse at a position that will completely stop a cuboid of a given size, mass, linear velocity, and rotational velocity. This function should give me the actual impulse which I can negate and apply to the part to stop the part in its tracks. This is all meant for Roblox which has a basepart:ApplyImpulseAtPosition(part,worldposition) function that I am trying to make use of. Here's the function I came up with, but I am not sure if it's correct because it created glitchy, snappy, feedback looping results in my testing. local function getImpulseAtPosition(part,pos) local smallNumber = 1e-10 local pos = part.CFrame:Inverse()*pos local CFRot = CFrame.new(part.CFrame.p):Inverse()*part.CFrame local size = part.Size local mass = part.Mass local linearVel = part.Velocity local rotationalVel = part.RotVelocity local linearInertia = part.Velocity*mass if rotationalVel.Magnitude > smallNumber then local rotationalAxis = part.RotVelocity.Unit local xI,yI,zI = (size.Y^2+size.Z^2)*mass/12, (size.X^2+size.Z^2)*mass/12, (size.X^2+size.Y^2)*mass/12 local vI = xI*math.abs(Vector3.xAxis:Dot(rotationalAxis))^0.5+yI*math.abs(Vector3.yAxis:Dot(rotationalAxis))^0.5+zI*math.abs(Vector3.zAxis:Dot(rotationalAxis))^0.5 local rotationalLinearVel = -pos:Cross(rotationalVel) local centerDist = pos:Cross(rotationalAxis).Magnitude^2 local rotationalInertia = centerDist > smallNumber and rotationalLinearVel*(vI/centerDist) or Vector3.zero return CFRot*rotationalInertia+linearInertia else return linearInertia end end sorry for the messy variable names, I just threw it together while trying to use my brain at its full capacity. |
Can C++20's 'operator==(const T&) = default' be mimiqued in C++17? Posted: 10 Apr 2022 02:06 AM PDT In C++ 20 we are able let the compiler automatically generate the implementation for operator== for us like this (and all the other default comparasions too, but I'm just interested in operator== here): #include <compare> struct Point { int x; int y; bool operator==(const Point&) const = default; }; Is there a way to archieve the same (automatically generate operator== ) but in C++17? Since libraries are an okay solution I had a look at boost/operators. Would the following be the equivalent as the above? #include <boost/operators.hpp> struct Point : boost<equality_comparable<Point, Point>> { int x; int y; bool operator==(const Point&) const = default; // will this get auto-generated too and do the same as above? }; |
Fixing of ava.lang.IllegalStateException: No active conversation found. at com.rapidclipse.framework.server.jpa.Jpa.getEntityManager(Jpa.java:200) Posted: 10 Apr 2022 02:06 AM PDT I have a running RapidClipse X Project, in which I work with a MySQL Database. I created a class to copy data from one table into a second table. For this I use a stream HibKontoDAO().findAll().stream().forEach( tc -> { ... copy data } The call and the process of this code works very well from anywhere in my application, except by calling it by a rest service. Always when I call it via REST then I get following Error: java.lang.IllegalStateException: No active conversation found. at com.rapidclipse.framework.server.jpa.Jpa.getEntityManager(Jpa.java:200) at com.rapidclipse.framework.server.jpa.Jpa.getEntityManager(Jpa.java:180) What I did: I used for testing purpoase the simple Hello World example out of: https://www.javaguides.net/2020/01/resteasy-hello-world-example-tutorial.html I placed the code in my application and it worked also very well! Then I changed it. In the HelloWorldResource class I call my code (which gives back a text) String myUmsMes = this.StartTransfer(); final HlpHelloWorldRest helloWorld = new HlpHelloWorldRest(myUmsMes); When I run this, I get in the Stream the error. HibKontoDAO().findAll().stream().forEach( tc -> { ... copy data } The full stacktrace is: Apr. 10, 2022 10:55:09 AM com.rieder.finmgmt.helper.HlpHelloWorldRestResource StartTransfer INFO: com.rieder.finmgmt.helper.HlpHelloWorldRestResource Exception happend java.lang.IllegalStateException: No active conversation found. at com.rapidclipse.framework.server.jpa.Jpa.getEntityManager(Jpa.java:200) at com.rapidclipse.framework.server.jpa.Jpa.getEntityManager(Jpa.java:180) at com.rapidclipse.framework.server.jpa.dal.JpaDataAccessObject$Default.em(JpaDataAccessObject.java:173) at com.rapidclipse.framework.server.jpa.dal.JpaDataAccessObject$Default.findAll(JpaDataAccessObject.java:243) at com.rieder.finmgmt.helper.HlpHelloWorldRestResource.StartTransfer(HlpHelloWorldRestResource.java:89) at com.rieder.finmgmt.helper.HlpHelloWorldRestResource.helloWorld(HlpHelloWorldRestResource.java:49) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:564) at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:138) at org.jboss.resteasy.core.ResourceMethodInvoker.internalInvokeOnTarget(ResourceMethodInvoker.java:546) at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTargetAfterFilter(ResourceMethodInvoker.java:435) at org.jboss.resteasy.core.ResourceMethodInvoker.lambda$invokeOnTarget$0(ResourceMethodInvoker.java:396) at org.jboss.resteasy.core.interception.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:358) at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:398) at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:365) at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:338) at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:440) at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:229) at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:135) at org.jboss.resteasy.core.interception.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:358) at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:138) at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:215) at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:245) at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:61) at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56) at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:196) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:364) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:624) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:831) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1673) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang.Thread.run(Thread.java:832) Both codes runs fine if they runs alone. And I found nothing in web for the .... No active conversation found..... Any idea what I did wrong, what could be the reason, or how to fix this? Thank you in advance! |
How do I get div to use percentage height of parent? Posted: 10 Apr 2022 02:06 AM PDT While trying to make a full-screen page with flexbox container that has items spaced evenly I found that I cannot in any way set the height of the container to full page height. How can this simple thing not work?? I want to have the flex container cover min 100% of page height and be able to grow beyond that if needed. But a good start would just be having it be 'static' 100% height, or any percentage! I'm not interested in setting the height of the div to vh units ! I put the body min-height to 100vh based on the explanation here: https://www.freecodecamp.org/news/html-page-width-height/ https://codepen.io/rradarr/pen/dyJKpWv HTML: <div class="first"> <div>a</div> <div>a</div> <div>a</div> <div>a</div> <div>a</div> <div>a</div> </div> CSS: * { margin: 0; } body { min-height: 100vh; border: 1px solid green; } .first { min-height: 100%; /*why does this not work???*/ border: 1px solid red; display: flex; flex-direction: column; justify-content: space-between; } |
how to increase the number of significand digits of a double type variable in C++? Posted: 10 Apr 2022 02:06 AM PDT I have written some code. The issue is that in one of the parts of code, it must add 1.0 to the variable 'is', and the reason the issue exists seems to be because the variable 'is', whose value is 2^68, is very large, and 1.0 is no where significant enough to be added to the number, as there aren't enough significand bits in the number. How do I add more significand bits to the double? Is it also possible to do so without using any external libraries? If not, which library should I use for this purpose and what changes should I add to the code in accordance to the library? The Code: #include <bits/stdc++.h> #include <cmath> using namespace std; void p(string s) { cout << s + "\n\x1b[0m"; } void cls() { p("\033[2J\033[1;1H"); } long double is = pow(2, 68); long double x; long double z; long double i2 = (is / 2.0); long double x2 = (x / 2.0); long double z2 = (z / 2.0); long double rem, fraction; int main() { cout.precision(200); while (3 > 2) { if ( modf(i2, &rem) != 0) { x = ((3.0 * is) + 1.0); } else { x = (is / 2.0); } while (3 > 2) { if ((x == 1.0) || (x == 2.0) || (x == 4.0)) { cout<<is<<" Doesn't Work"<<endl; is += 1.0; break; } if (x == is) { p(to_string(is)); p("success! Counterexample found!"); break; } else { if ( modf(x2, &rem) != 0) { z = ((3.0 * x) + 1.0); } else { z = (x / 2.0); } } if ((z == 1.0) or (z == 2.0) or (z == 4.0)) { cout<<is<<" Doesn't Work"<<endl; is += 1.0; break; } if (z == is) { p(to_string(is)); p("success! Counterexample found!"); break; } else { if ( modf(z2, &rem) != 0) { x = ((3.0 * z) + 1.0); } else { x = (z / 2.0); } } } } return 0; } Any help is appreciated. |
"Created by" Opensea Minter vs. Contract deployer Posted: 10 Apr 2022 02:05 AM PDT |
Hot reload by air is not working on my app Posted: 10 Apr 2022 02:05 AM PDT I want to use hot reload in my golang app. I use air package. But when I modify my main.go , the api response is not changed. ↓ my app folders. my-app |--- app | |--- .air.toml | |--- Dockerfile | |--- go.mod | |--- go.sum | |--- main.go | |--- docker-compose.yml ↓ Dockerfile FROM golang:1.16 ENV GOPATH /go ENV GO111MODULE on COPY go.mod /var/www/html/go.mod COPY go.sum /var/www/html/go.sum WORKDIR /var/www/html/ RUN go mod download RUN go mod tidy && \ go install github.com/cosmtrek/air@v1.27.3 COPY . /var/www/html/ CMD ["air", "-c", ".air.toml"] ↓ docker-compose.yml version: '3' services: app: build: ./app tty: true volumes: - ./app:/var/www/html depends_on: - mysql ports: - "3000:3000" command: "air" ↓ main.go package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { engine := gin.Default() engine.GET("/", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "hello world", }) }) engine.Run(":3000") } And when I do command docker-compose up --build , I get ↓. my console What is wrong? |
Effect of min_granularity_ns on performance Posted: 10 Apr 2022 02:05 AM PDT In order to find the effect of kernel parameter, min_granularity_ns , a 16-thread OMP implementation of a matrix multiplication code is launched with high and low values of that parameter. The perf result is shown below: # echo 1000000 > /sys/kernel/debug/sched/min_granularity_ns # perf stat -a -e $EVENTS -- ./mm_omp 16 Using 16 threads Total execution Time in seconds: 12.3690895601 MM execution Time in seconds: 12.2312941169 Performance counter stats for 'system wide': 911.97 Joules power/energy-pkg/ 218,012,129,383 instructions # 0.26 insn per cycle 823,773,717,094 cycles 37,701 context-switches 131 cpu-migrations 51,012 page-faults 12.369310043 seconds time elapsed # echo 1000000000 > /sys/kernel/debug/sched/min_granularity_ns # perf stat -a -e $EVENTS -- ./mm_double_omp 16 Using 16 threads Total execution Time in seconds: 12.3981724780 MM execution Time in seconds: 12.2612874920 Performance counter stats for 'system wide': 881.48 Joules power/energy-pkg/ 218,063,319,724 instructions # 0.27 insn per cycle 822,622,830,036 cycles 37,959 context-switches 146 cpu-migrations 51,553 page-faults 12.400958939 seconds time elapsed As you can see there is no difference between the results albeit the large change in the kernel parameter, from 1 us to 1 second. Although there are other parameters in addition to min_granularity_ns , does that "no-difference" make sense? Or maybe this is not a correct program to test? |
How to create a fallabck function for react native biometrics library to get passcode validation Posted: 10 Apr 2022 02:05 AM PDT I am creating biometrics authentication using https://www.npmjs.com/package/react-native-biometrics library for which i need biometric fallback function so if the passcode doesn't work it will set to type passcode. |
how can bind array values in map function react Posted: 10 Apr 2022 02:06 AM PDT hope you are doing great, I am trying to bind array values in my map function but I am unsuccessful in achieving my result Here is the console result of line number 32 where I am getting data here is my code my screen is looking like this now |
Not the required data is displayed for the new user, because the data is taken from the cache of the previous user Posted: 10 Apr 2022 02:06 AM PDT I made a custom module that displays the weather in a particular city. But I got these comments after the code review: 1. Interesting question, what happens to your cache data, if the site first comes to a person from the city of London, and then Paris? As I understand it, it means that a person from Paris, when he enters the site, will see the weather in London, because it will be taken from the cache. But I put the data in the cache so that there are not too many requests, I made a request once, put the data in the cache, and the next time I took the data from the cache. 2. In the small function, you are calling the http://ip-api.com/json/ endpoint twice. What happens when the site is visited by a thousand people per minute? Here, I do not understand what the problem is. If it meant that the connection limit to the resource would be exhausted, then how to solve this problem? In the getCity() function, put the data in the cache in the same way as I do in the build() function? But then the same problem comes up as in the first remark, if a person from another city visits the site, then the data from the cache (name of the city of London) will be taken and not the name of his real city. How then to be? Can you please tell me what needs to be changed in my code? Below I will write a slightly reduced code for my php file. Full version here: https://phpsandbox.io/n/sweet-forest-1lew-1wmof // .... use Drupal\Core\Cache\CacheBackendInterface; use GuzzleHttp\Client; //.... public function getCity() { $ip = '193.62.157.66'; // just for testing try { $response_ip = $this->httpClient->get('http://ip-api.com/json/' . $ip); $response_data_ip = $response_ip->getBody(); $data_ip = json_decode($response_data_ip); if ($data_ip->status == 'success') { return $data_ip->city; } else { return $this->configFactory->get('sydneypro_weather.settings')->get('weather_city'); } } catch (RequestException $e) { return FALSE; } } public function build() { $client = $this->httpClient; $api_key = $this->configFactory->get('sydneypro_weather.settings')->get('weather_api_key'); $cid = 'sydneypro_weather'; $weather_config = $this->configFactory->get('sydneypro_weather.settings'); if (!$weather_config) { $this->logger->get('sydneypro_weather')->error('Config "sydneypro_weather.settings" is missing4'); return []; } if (empty($api_key) || empty($this->getCity())) { return [ '#type' => 'markup', '#markup' => $this->t('Please enter your API key and City in the Admin panel to see the weather'), ]; } try { if ($cache = $this->cacheBackend->get($cid)) { $data = $cache->data; } else { $response = $client->get('http://api.openweathermap.org/data/2.5/weather?q=' . $this->getCity() . ',&appid=' . $api_key . '&units=metric'); $response_data = $response->getBody(); $data = json_decode($response_data); $this->cacheBackend->set($cid, $data, $this->time->getRequestTime() + 21600); } $build = [ '#theme' => 'weather_block', '#data' => $data, '#attached' => [ 'library' => [ 'sydneypro_weather/sydneypro_weather', ], ], ]; return $build; } // .... |
docker:Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? Posted: 10 Apr 2022 02:06 AM PDT I'm remotely connecting to a school server (Ubuntu 20.04.2 LTS) through Visual Studio Code (VScode, version 1.66) to perform some tasks, and today I follow docker.com (https://docs.docker.com/engine/install/ubuntu/) to install docker engine on Ubuntu. when I do sudo docker run hello-world to verify that Docker Engine is installed correctly by running the hello-world image after all steps, it shows error like this: docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?. See 'docker run --help'. After that I check the docker version , it shows Client: Docker Engine - Community Version: 20.10.14 API version: 1.41 Go version: go1.16.15 Git commit: a224086 Built: Thu Mar 24 01:48:02 2022 OS/Arch: linux/amd64 Context: default Experimental: true Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? Then look at sudo docker info , which shows Client: Context: default Debug Mode: false Plugins: app: Docker App (Docker Inc., v0.9.1-beta3) buildx: Docker Buildx (Docker Inc., v0.8.1-docker) scan: Docker Scan (Docker Inc., v0.17.0) Server: ERROR: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? errors pretty printing info After I unstall and reinstall docker follow this tutorial, it still shows such an error, I think I need to follow the server side of docker, but I don't know how to do it? This is history: root@yp:~# sudo apt-get remove docker docker-engine docker.io containerd runc ... root@yp:~# sudo apt-get update ... root@yp:~# sudo apt-get install \ > ca-certificates \ > curl \ > gnupg \ > lsb-release ... root@yp:~# curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg ... root@yp:~# echo \ > "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \ > $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null ... root@yp:~# sudo apt-get update ... root@yp:~# sudo apt-get install docker-ce docker-ce-cli containerd.io ... root@yp:~# sudo docker run hello-world docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?. See 'docker run --help'. |
data matching between two lists with python Posted: 10 Apr 2022 02:07 AM PDT I have a task about data matching between two lists in python,the lists like these below: listA = [['a','b'],['c','d'],['a','f']] listB = [['b','m'],['d','h'],['f','n'],['f','q']] Now, i do the matching like this: match_list=[] for x in listA: for y in listB: if x[1] == y[0]: match_list.append([x[0],y[1]) the match_list will like this:[[a,m],[c,h],[a,n],[c,h],[a,q]] Now although the data matching can be achieved, it runs too slowly when there is a large amount of data in the list. I wonder if there is an easier way to accomplish this task |
Why is a value not updating correctly? Posted: 10 Apr 2022 02:06 AM PDT I am currently trying to teach myself react. I ran into this weird behavior and couldn't explain what was going on so I was hoping to get some answers. In the below code snippet. I have a variable index that's initially set to 0 . When I click the button, I expect handleClick() to update the value of index . However, it does not do it as I would expect. const { useState } = React; const Home = () => { let names = ["Hello", "World"]; let index = 0; const [name, setName] = useState(names[index]); const handleClick = () => { console.log(`Output: ${name}`); console.log(`Index = ${index}`); index = (index+1)%2; setName(names[index]); } return ( <div className="Home"> <button onClick={handleClick}>Click</button> </div> ); } ReactDOM.render(<Home />, document.body); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> I expect the console.log output to be as follows: Output: Hello Index = 0 Output: World Index = 1 Output: Hello Index = 0 Output: World Index = 1 ... Instead, what I get is: Output: Hello Index = 0 Output: World Index = 0 Output: World Index = 1 Output: Hello Index = 0 ... Can someone explain what is going on here? |
Function that checks if values in a list are the same as specific value lists in a dictionary? Posted: 10 Apr 2022 02:07 AM PDT To preface, I want to establish that I'm new to python and I'm still in the process of learning for loops. I want to make a function that takes a list of strings and a dictionary as inputs. If any strings in the list match a set of values in the dictionary, they should return a key corresponding to those values. An example input would look something like available_dishes(ingredients, recipes) . Where ingredients = ['Fish','Rice','Eggs','Ketchup'] recipes = {'Sushi':['Fish','Rice','Seaweed'],'Grilled_Fish':['Fish'],'Omurice':['Eggs','Rice','Ketchup']} Because the list only has the necessary ingredients for grilled fish and omurice, this would return the output: ['Grilled_Fish','Omurice'] . Specifically, the results should appear in the order that the keys appear in the dictionary. What I'm Trying In my attempt, I have isolated one of the lists in the list of dictionary values. I tried focusing on one list so that I might understand how the rest of them might function. What I've made isn't necessarily a function but a group of variables I wanted to try interpreting. recipe_ingredients = list(recipes.values()) for i in ingredients: if i in recipe_ingredients[0]: print(i) Unfortunately, for now, my knowledge of python is limited so this only returns the matching ingredients between the two lists: Fish Rice . I'm still somewhat inexperienced with for loops, so I'd like to see how this could be done using them as well as if statements. If possible, could this be done without the use of list comprehension? Any help is appreciated. |
Why does my Spark Code take so long to execute? Posted: 10 Apr 2022 02:05 AM PDT This is the code Im running. Why could it possibly take so long? it's been running for over an hour. from pyspark import SparkConf, SparkContext from pyspark.sql import SparkSession, Row conf = SparkConf() conf.setMaster('spark://192.168.56.1:7077') conf.set('spark.authenticate', False) sc = SparkContext.getOrCreate(conf=conf) big_list = range(1000000) rdd = sc.parallelize(big_list, 2) odds = rdd.filter(lambda x: x % 2 != 0) odds.take(10) |
Getting empty ctx.body on post requests in Koajs Posted: 10 Apr 2022 02:05 AM PDT I'm new to Koa. I wrote a simple api server with it. I have used "koa-bodyparser" and i have added content-type: application/json to the request header, but i still get empty request body on post requests. Could anyone please guide me? this is my server.js const Koa = require('koa'); const bodyParser = require('koa-bodyparser')(); const compress = require('koa-compress')(); const cors = require('@koa/cors')(); const helmet = require('koa-helmet')(); const logger = require('koa-logger')(); const errorHandler = require('./middleware/error.middleware'); const applyApiMiddleware = require('./api'); const { isDevelopment } = require('./config'); const db = require('./db/db'); const server = new Koa(); db.connectDB(); /** * Add here only development middlewares */ if (isDevelopment) { server.use(logger); } /** * Pass to our server instance middlewares */ server .use(errorHandler) .use(helmet) .use(compress) .use(cors) .use(bodyParser); /** * Apply to our server the api router */ applyApiMiddleware(server); module.exports = server; and this is my endpoint: router.post('/', controller.createOne); and the createone method: exports.createOne = async ctx => { console.log(ctx.body); ctx.assert(username, 400, 'Username is required'); ctx.assert(password, 400, 'Password is required') try { const { name, username, password } = ctx.request.body; let user = await User.findOne({ username }); if (user){ ctx.status = 400; ctx.body = { errors: [{ msg: 'User already exists' }] }; } user = new User({ name, username, password }); const salt = await bcrypt.genSalt(10); user.password = await bcrypt.hash(password, salt); await user.save(); user.password = undefined; ctx.status = 201; ctx.body = user; } catch (error) { console.error(error.message); ctx.status = 500; ctx.body = { errors: [{ msg: error.message }] } } }; and the postman request: |
Implementing google map in Flutter just like Zomato or Swiggy Posted: 10 Apr 2022 02:05 AM PDT I am trying to implement a map in my flutter application that contains a marker which points to the center of the map and when we stop dragging the map , we get the latlong of the center position. Got inspired by Zomato and Swiggy's Map UI . How to implement this ?? import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:geolocator/geolocator.dart'; import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; void main() => runApp(const InitApp()); class InitApp extends StatelessWidget { const InitApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: RenderMap(), ); } } class RenderMap extends StatefulWidget { @override State<RenderMap> createState() => _RenderMapState(); } class _RenderMapState extends State<RenderMap> { late Position _currentLocation; late GoogleMapController _controller; bool loadingMap = false; bool init = true; getCurrentLoc() async { bool serviceEnabled; LocationPermission permission; serviceEnabled = await Geolocator.isLocationServiceEnabled(); if (!serviceEnabled) { return Future.error('Location services are disabled.'); } permission = await Geolocator.checkPermission(); if (permission == LocationPermission.denied) { permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied) { return Future.error('Location permissions are denied'); } } if (permission == LocationPermission.deniedForever) { return Future.error( 'Location permissions are permanently denied, we cannot request permissions.'); } _currentLocation = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high); setState(() {}); } @override void initState() { // TODO: implement initState super.initState(); getCurrentLoc(); } @override void dispose() { // TODO: implement dispose super.dispose(); _controller.dispose(); } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( body: Container( height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, child: Stack( alignment: Alignment.center, children: [ (loadingMap) ? const Center( child: CircularProgressIndicator(), ) : GoogleMap( zoomControlsEnabled: false, myLocationButtonEnabled: true, indoorViewEnabled: false, onMapCreated: (controller) { _controller = controller; }, initialCameraPosition: CameraPosition( target: LatLng(_currentLocation.latitude, _currentLocation.longitude), zoom: 16, ), mapType: MapType.normal, ), Image.asset( 'assets/pin.png', height: 35, fit: BoxFit.cover, ), ], ), )), ); } } this is the source code , i am using a stack widget to hold the map and the marker at the center , now i want to know the latlong of the position that the pin is pointing to. Since the pin is at the center I just need to the the latlong of the cameraPosition . |
How do I disable the value of the options drop-down menu from the front end once the value selected option has been clicked Posted: 10 Apr 2022 02:05 AM PDT Hi do you have any idea of disabling or locking the option item/value once the value have been selected and insert it onto the database? Example there is a form and when I selected the option with a value one and click save or submit button That value will be lock and can't be selected anymore |
How can I modify this code to write to Laravel controller Posted: 10 Apr 2022 02:07 AM PDT My problem is that when I send a post from an rfid card via esp8266, the data is an rfid number, but the data can't appear because the code I gave has not been written into Laravel. This PHP code : <?php if(isset($_POST['uid'])) { $uid = $_POST["uid"]; $sql = mysqli_query($dbconnect, "INSERT INTO tb_entry VALUES ('$uid')"); } ?> How can I write this code into Laravel controller? |
How to simulate session expiration manually with devtools? Posted: 10 Apr 2022 02:05 AM PDT I need to track what happens with certain events on the site at the time of the session expiration. To simulate session expiration, I clear local and session storage. I'm not sure if this is the correct solution. |
How to take out object from div's onClick event in React Posted: 10 Apr 2022 02:05 AM PDT I want to take out the object by clicking on the div, when I am implementing the click function shows class in the console and not object Code Sample <div className="leftblock"> <div className="Title">Select Client :</div> <div className="clientBlock" > {Clients.map((eachClient, index) => { return ( <div className="clientdiv" style={{borderLeft:``3px solid ${eachClient.ColorHexCode}``}} onClick={(obj)=>selected(obj)} > <div className="lh-18" > {index + 1 }. <span className="fw-bold fs-12" > {eachClient.Name}</span> </div> <div className="lh-18"> Client Id: <span className="fw-bold fs-12"> {eachClient.Id}</span> </div> <div className="lh-18"> Client Code : <span className="fw-bold fs-12">{eachClient.Code}</span> </div> </div> ); })} </div> </div> const selected = (obj) => { console.log(obj, "selected") }; |
Accessing Payload of JWT with mvc dotnet core Posted: 10 Apr 2022 02:05 AM PDT I have a problem with accessing the (payload of) JWT in a dotnet core controller. I don't know where I am wrong. I think I covered all the important points in the following description. If I have missed something, that could help, please let me know. Thank you for your time. Adding authentication service to the servicecollection services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = false, ValidateIssuerSigningKey = false, ValidIssuer = null, ValidAudience = null, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("testify")) }; }); The token I used for the request: The postman call: The code of the controller action: [HttpPost] [ProducesResponseType(typeof(void), 201)] [ProducesResponseType(typeof(void), 400)] [ProducesResponseType(typeof(void), 401)] [ProducesResponseType(typeof(void), 403)] [ApiExplorerSettings(GroupName = "AuditLog")] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public IActionResult Insert([Required] Dto.Log auditLog) => RunSafely(() => { var log = _mapper.Map<Dto.Log, Log>(auditLog); log.CorrelationId = _headerReader.GetCorrelationId(Request?.Headers); _logRepository.AddLog(log); return this.StatusCode((int)HttpStatusCode.Created); }); The state of the controller: |
How to avoid escape characters outputted to log file with logging? Posted: 10 Apr 2022 02:05 AM PDT I'm trying to color level names like INFO, WARNING, and so on but the problem is when a message is logged to the log file - there are weird characters. However, it gets printed out perfectly fine to the console. Code: import logging import sys logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[ logging.FileHandler("log.txt"), logging.StreamHandler(sys.stdout) ] ) logging.addLevelName(logging.INFO, "\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.INFO)) logging.info("This is just an information for you") This prints the level name "INFO" with color, but the output is: 2022-04-05 02:44:52,741 [[1;31mINFO[1;0m] This is just an information for you How can this be fixed? EDIT: logging.addLevelName(logging.INFO, "\033[1;94m%s\033[1;0m" % logging.getLevelName(logging.INFO)) logging.addLevelName(logging.WARNING, "\033[1;93m%s\033[1;0m" % logging.getLevelName(logging.WARNING)) logging.addLevelName(logging.ERROR, "\033[1;91m%s\033[1;0m" % logging.getLevelName(logging.ERROR)) |
Getting a datetime variable from a database using dataTableReader Posted: 10 Apr 2022 02:06 AM PDT So i have a database and i am getting from it it's data by dataTableReader. I think when you get them from the database you get them as an object , not sure, but for sure it's not the variable i set them to be in the database. so fur I have used only int and varchar in the database so i have converted them by using toString() and int.parse() . now i need to use a datetime variable. How can i get it from the database as a datetime or convert it to datetime and not as string(using toString() )? Thanks for the Help |
What is NamedTemporaryFile useful for on Windows? Posted: 10 Apr 2022 02:06 AM PDT The Python module tempfile contains both NamedTemporaryFile and TemporaryFile . The documentation for the former says Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later) What is the point of the file having a name if I can't use that name? If I want the useful (for me) behaviour of Unix on Windows, I've got to make a copy of the code and rip out all the bits that say if _os.name == 'nt' and the like. What gives? Surely this is useful for something, since it was deliberately coded this way, but what is that something? |
No comments:
Post a Comment