Posts

Showing posts from February, 2022

Tailwind css V3- custom colors with string interpolation

I've just upgraded tailwind in my react project to get rid of this warning: warn - The `purge`/`content` options have changed in Tailwind CSS v3.0. warn - Update your configuration file to eliminate this warning. warn - https://tailwindcss.com/docs/upgrade-guide#configure-content-sources As I understand it the 'purge' property is now replaced with 'content'. I replaced the property name and for the most part everything worked the same. However in my old Tailwind config file I needed to safelist a bunch of colors in order to make them show up. Without the purge property to use I don't know where to put the safelist module.exports = { mode: 'jit', purge: { content: ['./src/**/*.{js,jsx,ts,tsx}'], options: { safelist: [ 'bg-[#ffffff]', 'bg-[#d9ffff]', 'bg-[#cc80ff]', 'bg-[#c2ff00]', 'bg-[#ffb5b5]', 'bg-[#909090]', 'bg-[#3...

How to locate the Constraint validation text using Selenium and Java

Image
I'm trying to make a Selenium test script that checks if a bootstrap validation popover appears when submitting a form containing a bad value. My script below returns this error: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#amount"} Relevant code: WebDriver driver = new ChromeDriver() WebElement field = driver.findElement(By.id("amount")); //errors here every execution Boolean is_valid = (Boolean)WebUI.executeScript("return arguments[0].checkValidity();", field); if (!is_valid) { //intentionally fail test } When I inspect the form field, I see the id equals amount , so why am I unable to find this element in Selenium? related question on SO EDIT Here's my full script that I omitted for brevity: WebUI.openBrowser('') WebUI.navigateToUrl('Foo') WebUI.setText(findTestObject('Object Repository/Page_bar/i...

unable to install yacas with Rstudio

I already downloaded Yacas on my windows. I first installed package Ryacas directly from Rstudio but no yacas functions can be run. I later ran this command and got the following errors: > devtools::install_github("r-cas/ryacas", build_opts = c("--no-resave-data", "--no-manual")) Downloading GitHub repo r-cas/ryacas@HEAD √ checking for file 'C:\Users\MyName\AppData\Local\Temp\RtmpEpL65w\remotes58d46bf01207\r-cas-ryacas-ea52235/DESCRIPTION' (684ms) - preparing 'Ryacas': (1.4s) √ checking DESCRIPTION meta-information ... - cleaning src - checking for LF line-endings in source and make files and shell scripts (1s) - checking for empty or unneeded directories (501ms) - building 'Ryacas_1.1.3.9002.tar.gz' Installing package into ‘C:/Users/MyName/Documents/R/win-library/4.1’ as ‘lib’ is unspecified) * installing *source* package 'Ryacas' ... ERROR: cannot remove earlier installation, is it in use? * removing 'C...

Using curl to download golang tarball produces strange result

I was trying to install golang on Ubuntu 21.10. This requires downloading the golang tarball and extracting it to a particular place on the filesystem. First I tried: curl -O https://go.dev/dl/go1.17.7.linux-amd64.tar.gz which simply created a file with following text: <a href="https://dl.google.com/go/go1.17.7.linux-amd64.tar.gz">Found</a>. The same command output with verbose flag : $ curl -v https://go.dev/dl/go1.17.7.linux-amd64.tar.gz * Trying 216.239.32.21:443... * Connected to go.dev (216.239.32.21) port 443 (#0) * ALPN, offering h2 * ALPN, offering http/1.1 * successfully set certificate verify locations: * CAfile: /etc/ssl/certs/ca-certificates.crt * CApath: /etc/ssl/certs * TLSv1.3 (OUT), TLS handshake, Client hello (1): * TLSv1.3 (IN), TLS handshake, Server hello (2): * TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8): * TLSv1.3 (IN), TLS handshake, Certificate (11): * TLSv1.3 (IN), TLS handshake, CERT verify (15): * TLSv1.3 (IN), TLS hand...

How to override DOM changes?

Image
I am working on a demo in which the client has a modal box which display is set to none . When I click on the CTA button fadein and fadeout classes are applied, and display:none changes to display:block for 3-4 sec and then display:block is turned back into display:none I want to remove toggle display:none to display:block and remove the fadein and fadeout classes. Is there a way I can use the console to remove the display toggle as well as removed classes using javascript Edit: I have uploaded the DOM changes which I want to remove.

Formatting to get desired constraint in python-constraint

This is a constraint problem being solved with python-constraint. I have 10 hours with the following constraint: no 2 activities/tasks can occur at the same 1hr slot. I have 9 activities to be taken by 9 hours of the schedule. Then I have 3 tasks, 'x', 'y', and 'z'. I want one of those tasks to be chosen for the other 1hr slot. This is what I have. Here I am adding the 9 activities as variables: problem.addVariables(['Activity1','Activity2', 'Activity3', 'Activity4', 'Activity5', 'Activity6', 'Activity7', 'Activity8', 'Activity9'], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) Here I am trying to add one of the three tasks as a variable: d = {'x': 1, 'y': 2, 'z': 3} for k,v in d.items(): problem.addVariables(["%s" %(k)], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) Here is for adding the constraint: problem.addConstraint(AllDifferentConstraint(),['Activity1','A...

I have no erors in my scripts I but receive many errors in the xlocnum, io, and the xiosbase files, I tried looking at the errors but dont understand

The errors might be showing because of the internal thing I had created and defined as static here is the build ouput 1>------ Build started: Project: C++_Game_Stuff, Configuration: Debug Win32 ------ 1>win64_maybe32_idk_platform.cpp 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\xiosbase(41,1): error C2159: more than one storage class specified 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\xiosbase(93): message : see reference to class template instantiation 'std::_Iosb<_Dummy>' being compiled 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\xiosbase(41,43): error C2059: syntax error: '=' 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\xiosbase(41,1): error C2238: unexpected token(s) preceding ';' 1>C:\Program Files (x86)\Micro...

Place a Window behind desktop icons using PyQt on Ubuntu/GNOME

I'm trying to develop a simple cross-platform Wallpaper manager, but I am not able to find any method to place my PyQt Window between the current wallpaper and the desktop icons using XLib (on windows and macOS it's way easier and works perfectly). This works right on Cinnamon (with a little workround just simulating a click), but not on GNOME. Can anyone help or give me any clue? (I'm providing all this code just to provide a minimum executable piece, but the key part, I guess, is right after 'if "GNOME"...' sentence) import Xlib import ewmh import pygetwindow from pynput import mouse DISP = Xlib.display.Display() SCREEN = DISP.screen() ROOT = DISP.screen().root EWMH = ewmh.EWMH(_display=DISP, root=ROOT) def sendBehind(self, hWnd): w = DISP.create_resource_object('window', hWnd) w.change_property(DISP.intern_atom('_NET_WM_STATE', False), Xlib.Xatom.ATOM, 32, [DISP.intern_atom('_NET_WM_STATE_BELOW', False), ], X...

android studio sdk messed up

i'm trying to install android studio. i downloaded it from this link: https://r5---sn-p5qs7nzk.gvt1.com/edgedl/android/studio/ide-zips/2021.1.1.21/android-studio-2021.1.1.21-linux.tar.gz . i also downloaded the sdk from here: https://dl.google.com/android/repository/platform-tools_r33.0.0-linux.zip . i untared android studio and in the bin folder, i ran: chmod +x studio.sh && ./studio.sh it bringed up the android studio wizard &... when it got to the sdk part, i couldn't select android sdk tools because it said (installed) but it isn't. i know what you might say: Android Studio comes with the sdk!NO! IT DOESN'T! when i try to change the sdk directory it says: Nothing to do! Android SDK is up to date. SDK emulator directory is missing . what should i do?

Drop-down not updating when calling RaisePropertyChanged (Prism, BindableBase, WPF)

I want to update the data on drop-down in a view from my view-model. The data is updated in some objects in my model. I understood that the INotifyPropertyChanged interface only works on view-model level. But I thought when the view-model subscribe to an event that I can update my view by raising the RaisePropertyChanged for the object in the view-model which needs to be updated. I call the UpdateConfiguration() which triggers to fetch the new data. Becacuse the function PutSetupWorkspaceConfiguration() is time consuming it returns the the first data and then compute the rest in the background. After its done its rasing the IsChanged event which works. So the method OnListChanged() gets called but then the gui does not update. What am I doing wrong since the event and the getter gets called? /*viewmodel*/ private SetupWorkspaceConfiguration setupWorkspaceConfiguration; public ObservableCollection<TestingModel> TestingModels { get => setupWorkspaceConfiguration?...

Compare two different images and find the differences

Image
I have a webcam which takes pictures of a concrete slab. Now I want to check if there are objects on the slab or not. The objects could be anything and accordingly cannot be enumerated in a class. Unfortunately I cannot compare the webcam image directly with an image without objects on the concrete slab, because the image of the camera could shift minimally in x and y direction and the lighting is also not always the same. So I cannot use cv2.substract . I would prefer a foreground and background substract, where the background is just my concrete slab and the foreground is then the objects. But since the objects don´t move but lie still on the slab, I can´t use cv2.createBackgroundSubtractorMOG2() either. The Pictures look like this: The Concrete slap without any objects: The slap with Objects:

Make Hidden child's relation /Laravel Eloquent

Model structure: AccessoryGroup (hasMany: accessories ) Accessory (belongsTo: accessory_group ) Get all accessory groups with accessories (with accesory_group ) In accessories I needed accessory_group relation, to create some custom attribute (appends) But after usage I don't won't my Api to return relation from accessories->accessory_group AccessoryGroup ::with([ 'accessories' => function ($query) { $accessory = $query->getRelated(); // Can I somehow use this $accessory relation for my problem // something like $accessory->makeHidden('accessory_group'); - not working }, 'accessories.accessory_group', ]) ->get(); when i add public $hidden = ['accesory_group']; in Accessory model I get what i want, but then it's always hidden (always need to use makeVisible)

EASY PYTHON SELENIUM: How do I download an mp4 WITHOUT using urllib?

I'm trying to download this video: https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4 I tried the following but it doesn't work. link = "https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4" urllib.request.urlretrieve(link, 'video.mp4') I'm getting: urllib.error.HTTPError: HTTP Error 403: Forbidden Is there another way to download an mp4 file without using urllib?

How to set multisample renderpass with depth attachment?

Firstly i have taking no error from validation layers and multisample is working. But when i copy depth resolved image , I understand that it is empty. When copy depth msaa image , I saw that it is not empty.( but as expected validation layers gave error because i copied VK_SAMPLE_COUNT_4_BIT to VK_SAMPLE_COUNT_1_BIT but still worked interesting . This is how I found out that there is no problem in depth msaa image) Therefore here should be depth resolving problem , where i am making mistake : VkAttachmentDescription colorAttachment_MSAA{}; colorAttachment_MSAA.samples = VK_SAMPLE_COUNT_4_BIT; ... VkAttachmentDescription colorAttachment_Resolve{}; colorAttachment_Resolve.samples = VK_SAMPLE_COUNT_1_BIT; ... VkAttachmentDescription depthAttachment_MSAA{}; depthAttachment_MSAA.samples = VK_SAMPLE_COUNT_4_BIT; ... VkAttachmentDescription depthAttachment_Resolve{}; depthAttachment_Resolve.samples = VK_SAMPLE_COUNT_1_BIT; depthAttachment_Resolve.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CAR...

Regex, All before an underscore, and all between second underscore and the last period?

How do I get everything before the first underscore, and everything between the last underscore and the period in the file extension? So far, I have everything before the first underscore, not sure what to do after that. .+?(?=_) EXAMPLES: 111111_SMITH, JIM_END TLD 6-01-20 THR LEWISHS.pdf 222222_JONES, MIKE_G URS TO 7.25 2-28-19 SA COOPSHS.pdf DESIRED RESULTS: 111111_END TLD 6-01-20 THR LEWISHS 222222_MIKE_G URS TO 7.25 2-28-19 SA COOPSHS

Error"utf-8' codec can't decode byte 0x96 in Python using MacOS

import pandas as pd,re,emoji,os,string from textblob import TextBlob import dateutil.parser as dparser keyword_bank = None keyword_files_paths = [] def getSubjectivity(text): return TextBlob(text).sentiment.subjectivity def getPolarity(text): return TextBlob(text).sentiment.polarity def deEmojify(text): text = str(text).encode("utf-8") text = emoji.get_emoji_regexp().sub(r'', text.decode('utf-8')) try: text = re.sub(r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*', '', text) except:pass return text def extractDateFromString(text): try: return dparser.parse(str(text),fuzzy=True).date() except: return text def getWordCount(text): try: return len(str(text).split()) except: len(str(text)) def filterText(text): newstr = '' string1 = text for char in text: if str(char).isalpha(): newstr = newstr+...

How to find_elements with multiple attributes using cssSelector Python and Selenium

I'm trying to find all the elements that have <a href=....> inside the <div id="contents" ...> Here is the HTML code: <div id="contents" class="style-scope"> <div id="dismissible" class="style-scope"> <a id="thumbnail" href="http://www.test.com"> Here is my python code: items = driver.find_elements(By.cssSelector("div[id="contents"] a[id="thumbnail"]")) It gives me the error: SyntaxError: invalid syntax. Perhaps you forgot a comma? Where do I need to put the comma?

Multiplying columns in a visual in Power BI

If I have a matrix visual where one column is a percentage of column total (where filters can change the output), how can I multiply that by another column within the matrix? For example, if I’m multiplying the forecast error of an item (column in an existing table) by the percentage of sales dollars (which would appear as “%CT sales dollars)? Edit: adding screenshots. In the first screenshot you see that we have "products" and their sales dollars are marked as a percentage of the column total. In the second screenshot, you see that the column still totals 100%, even if the matrix is filtered. How do we create a third column that multiplies the two numeric columns together? IE- dollar percentage times forecast error percentage? Screenshot 1 Screenshot 2

What is the difference between CSVLogger and model.evaluate()?

I have been using Keras/TF's CSVLogger in order to save the training and validation accuracies. Then I was plotting those data to check the trajectory of training and validation accuracy or loss. Yesterday, I read this link . Here, they used model.evaluate() to plot the accuracy metric. What is the difference between these two approaches?

Reduce size of snowflake-connector-python[pandas] module

I am trying to create a lambda function in AWS which connects to a Snowflake database. For this I need the snowflake-connector-python[pandas] package ( https://docs.snowflake.com/en/user-guide/python-connector-pandas.html ), which together with all of its dependencies has a size of over 250 MB uncompressed (around 280 MB). This is an issue because AWS lambda allows a maximum of 250 MB of dependencies (using AWS layers). The size of the package is quite surprising, looking at the dependencies the biggest offenders are pyarrow (around 80 MB), pandas (around 60 MB), and numpy (around 40 MB). Is there a way to reduce the size of the whole package, installing only the relevant parts, so as to reduce the size to below 250 MB? Namely I need to be able to connect, read, and write to Snowflake, nothing fancy. I know that there are other options in these cases, such as containers, however I would like to avoid this if possible.

Logging in Postgres sql from cmd using a specific post

How can i use the command prompt to log into Postgres installation? I am trying to use this command on C:\Program Files\PostgreSQL\14\data directory psql -h localhost -p 5433 Since there is some other program which has another installation of an earlier release of Postgres on port 5432, thus port 5433. But it is producing this error: psql: error: connection to server at "localhost" (::1), port 5433 failed: FATAL: role "user1" does not exist https://docs.bitnami.com/virtual-machine/infrastructure/postgresql/administration/connect-remotely/

How do I cleanly delete elements from a Sidebar List in SwiftUI on macOS

Image
I would like to give users the option to delete List elements from a SwiftUI app's sidebar in macOS. Here's what I currently have: import Foundation import SwiftUI @main struct FoobarApp: App { @StateObject private var modelData = ModelData() var body: some Scene { WindowGroup { ContentView() .environmentObject(modelData) } .commands { } } } class ModelData: ObservableObject { @Published var myLinks = [URL(string: "https://google.com")!, URL(string: "https://apple.com")!, URL(string: "https://amazon.com")!] } struct ContentView: View { @EnvironmentObject var modelData: ModelData @State private var selected: URL? var body: some View { NavigationView { List(selection: $selected) { Section(header: Text("Bookmarks")) { ForEach(modelData.myLinks, id: \.self) { url in ...

Add PowerShell package as native dependency

Image
How should one add the PowerShell package as a Native dependency ? In spite of adding it one is unable to run basic PowerShell commands to show output on the screen. PFB REPL link. https://blazorrepl.telerik.com/GQacljYn3647KP3G59 The HTML and C# Hello World are working. However, the PowerShell Hello World doesn’t work.

Sharing node_modules folder between lambda using Lambda Layers + Cloud Formation

I have a project that uses serverless-framework ( this ) to define the AWS resources to be used. I have the various .yml files that describe each resource that the project needs to run. Recently, I've had to install several NPM packages for my lambdas and they've become very large in megabytes (>3MB), so the code is no longer viewable from the console. Since including node_modules in each lambda is not a best practice and they are very heavy this way, I was wondering about using a Lambda Layer to share node_modules between lambdas. As .yml I have a shared structure between all of them called provider.yml , something like: name: aws runtime: nodejs14.x lambdaHashingVersion: 20201221 region: ${opt:region, "eu-central-1"} stage: ${opt:stage, "dev"} profile: ${self:custom.profiles.${self:provider.stage}} deploymentBucket: name: avatar-${self:provider.stage}-deploymentbucket versioning: true blockPublicAccess: true environment: EXAMPLE_ENV_VAR: ${self...

Accessing running container (inside VM) from host OS

I have set up 3 Linux VM through multipass on my host Mac OSX. I have installed docker on these machines and started a 3 node docker swarm. docker swarm init After that, I have created 2 services one is for Postgres DB and the other is for drupal with the following command. docker service create -d --name postgras-db --network test-swarm-network -e POSTGRES_PASSWORD=<password> postgres docker service create -d --name drupal-frontend --network test-swarm-network -p 80:80 drupal Port 80:80 is exposed for drupal and both of these services are connected to the same overlay network. My services are up and running. If I am doing everything on the host machine then I will simply do http://localhost:80 or http://localhost to get the desired output but now when running it in VM how I can test the drupal front from host MAC, i.e which IP to hit in the host browser to get the desired result. P.S: There is nothing specific here about drupal (it could be any other container like Ngin...

Display is good but the software may have some problem, because hardware is good

Image
The system is crashing again and again with out any reason.

How to sort an array by a number inside w/ javascript [duplicate]

So I'm having trouble sorting an array. I'm trying to make it descend from the highest average to the lowest. This is the table -> [ { "average": "86.8", "user": "User1" }, { "average": "93", "user": "User2" }, { "average": "91.5", "user": "User3" } ] This is how I set the array let usr = [] if (users.docs.length > 0) { for (const user of users.docs) { let exportable = user.data() usr.push(exportable) } }

How to get a line count of all individual files in a directory on AWS S3 using a terminal?

I am new to terminal commands. I know we can do something like wc -l directory/* if the files were local. But how do I achieve the same on AWS S3 using a terminal? The output should be the file name and the count. For example, there are two files present in a directory in S3 - 'abcd.txt' (5 lines in the file) and 'efgh.txt' (10 lines in the file). I want the line counts of each file without downloading the files, using terminal. Output - 'abcd.txt' 5 'efgh.txt' 10

How to manipulate the ScrollController in Flutter's sliding up panel plugin?

I'm using Flutter's sliding_up_panel plugin. I want to scroll the panel to the top when a new item is selected from my app drawer. Presently selecting a new item closes the panel and refreshes the panel content. Then opens it to a 200px peak, but it doesn't reset the panel's Scroll location to the top. I've been going around in circles trying the same solutions in slightly different ways and getting nowhere. What I've tried: I have global PanelController slidingPanelController = new PanelController(); ScrollController slideUpPanelScrollController = new ScrollController(); I tried attaching my global slideUpPanelScrollController to my panel's listview, but when swiping up the panel's ListView it simultaneously starts closing the whole panel. If you were scrolling up to read the content you'd skimmed, well, you're not able to because it's disappearing. Preventing this bug is easy, you do it the canonical way from the plugin's ex...

Conditionnal call of a FastApi Model

I have a multilang FastApi connected to MongoDB. My document in MongoDB is duplicated in the two languages available and structured this way (simplified example): { "_id": xxxxxxx, "en": { "title": "Drinking Water Composition", "description": "Drinking water composition expressed in... with pesticides.", "category": "Water", "tags": ["water","pesticides"] }, "fr": { "title": "Composition de l'eau de boisson", "description": "Composition de l'eau de boisson exprimée en... présence de pesticides....", "category": "Eau", "tags": ["eau","pesticides"] }, } I therefore implemented two models DatasetFR and DatasetEN, each one make references with specific external ...

Invalid Argument Error / Graph Execution Error

I'm having multiple errors while running this VGG training code (code and errors shown below). I don't know if its because of my dataset or is it something else. import numpy as np import pandas as pd import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.vgg16 import preprocess_input from tensorflow.keras.preprocessing.image import ImageDataGenerator from sklearn.metrics.pairwise import cosine_similarity import os import scipy train_directory = 'sign_data/train' #To be changed test_directory = 'sign_data/test' #To be changed train_datagen = ImageDataGenerator( rescale = 1./255, rotation_range = 0.1, width_shift_range = 0.2, height_shift_range = 0.2, shear_range = 0.1 ) train_generator = train_datagen.flow_from_directory( train_directory, target_size = (224, 224), color_mode = 'rgb', shuffle = True, batch_size=32 ) test_...

ngModel does not work on modal page in Ionic 6

I am developing an Ionic/Angular app and wanted to use ngModel as alwayls. I am opening a modal from a modal and then want to use it like: <ion-list> <ion-item> <ion-label position="stacked">Name des Rezepts</ion-label> <ion-input [(ngModel)]="model" ></ion-input> </ion-item> </ion-list> <ion-button (click)="save()">Save</ion-button> i declared the variable in typescript like: public model=""; But when i click save, my output IS ALWAYS the empty string?! I imported ReactiveFormsModule in my app.module.ts and on normal pages it works, but in modals it seems like that it does not work?! Do you guys have any ideas? Thank you!

How to start nodejs and filebeat in same contianer

I need to create a docker container with nodejs app and filebeat in same container. So filebeat will relay nodejs logs to my logstash server. I have created docker file and when i build the image it runs without error. But when i go inside container and see no files related to filebeat are created. NodeJS app runs as expected but filebeat is not working at all. I have used the custom file given by filebeat https://www.elastic.co/guide/en/beats/filebeat/current/running-on-docker.html mentioned here So can we run the nodeJS app and filebeat in same container? and if yes what i am doing wrong ? Here is my docker file --- # Test web app that returns the name of the host/pod/container servicing req # Linux x64 FROM docker.elastic.co/beats/filebeat:7.13.4 COPY --chown=root:filebeat filebeat.yml /usr/share/filebeat/filebeat.yml FROM node:current-alpine LABEL org.opencontainers.image.title="Test node App" \ org.opencontainers.image.description="Create logs for Ope...

How to read contents of a bin file to a vector? [duplicate]

I'm a beginner with C++, so I don't know much about it. I have been searching questions for a while but nothing quite helps. How to read the contents of a .bin file into a std::vector<uint8_t> ?

How to perform join query using Java stream

I am fetching data from db and storing it in list. Then based on the the id, I want to create new Object. I have already implemented it using old for loop method. I am trying to implement it using java stream. Any help? Thanks. List<Employee> emp = new ArrayList<Employee>(); emp.add(new Employee(1, "Ben", "Glasgow")); emp.add(new Employee(2, "Max", "Seattle")); emp.add(new Employee(3, "Sam", "Mumbai")); emp.add(new Employee(4, "John", "Aukland")); emp.add(new Employee(5, "Rob", "Tokyo")); List<Department> dpt = new ArrayList<Department>(); dpt.add(new Department(1, 40000, "tech")); dpt.add(new Department(2, 30000, "mgm")); dpt.add(new Department(3, 50000, "tech")); dpt.add(new Department(4, 30000, "mgm")); List<EmpDep...

text in axes pyqtgraph

how to add text in vertical axes in pyqtgraph(other than label for axes). when use TextItem, add text in ViewBox not in axes enter image description here

ZMQ detect client unavailability with heartbeat

I am experiencing with zmq, but I could not find an answer in the docs and examples that the proper use of the following socket options: ZMQ_HEARTBEAT_IVL ZMQ_HEARTBEAT_TIMEOUT ZMQ_HEARTBEAT_TTL The documentation states that they can be used with any socket types ("when using connection-oriented transports"). Is there a way to use them with REQ/REP socket pairs? Test client code: zmq::context_t context( 1 ); zmq::socket_t client( context, ZMQ_REQ ); client.connect( "tcp://localhost:5555" ); // Send request. std::string request( "test message" ); zmq::message_t message( string.size() ); memcpy( message.data(), string.data(), string.size() ); socket.send( message, flags ); // Wait for reply. socket.recv( &message ); // Do some work that takes cca 10 secs. // ... delete client; Test server code: zmq::context_t context( 1 ); zmq::socket_t server( context, zmq::socket_type::rep ); //server.set( zmq::sockopt::rcvtimeo, 5000 ); server.set( zmq:...

Saving Array ID to Database with value to each id

Good Evening.... Hope i can explain my problem correctly. I am getting data (ID) in array and value (numbers) in controller. Now i want to save the "numbers" in each "ID". array ID ["Buffalo-01", "Buffalo-02", "Buffalo-04"] Numbers - 40. Want to save 40 to each ID. Controller public function addbuffalototalmilk(Request $req ) { $buffalomilking = Buffalodata::where('avgmilk','<>','0')->Where('status','=','Available')->count(); // MIlking Animal Nos $getbuffalomilkingid = Buffalodata::where('avgmilk','<>','0')->Where('status','=','Available')->pluck('buffaloID'); // Get Buffalo Details of Milking $totalmorningmilk = $req->get('morningtotalmilk'); $totaleveningmilk = $req->get('eveningto...

Request not being completed with Expo authSession

I'm quite new to app development and have ran into an error while trying to set up Google authentication, but it appears the request hasn't finished loading. (Error message is: [Unhandled promise rejection: Error: Cannot prompt to authenticate until the request has finished loading.] ) I'm not sure how I can work around this issue, perhaps some more experienced developers answer my question? import React, { useState, useEffect } from 'react'; import { View, Text, Button, StyleSheet, TextInput } from 'react-native'; import { useAuthRequest } from 'expo-auth-session'; import * as WebBrowser from 'expo-web-browser'; WebBrowser.maybeCompleteAuthSession(); const App = () => { const [accessToken, setAccessToken] = useState(); const [request, response, promptAsync] = useAuthRequest({ iosClientId: "701989901250-95eku3luaf6qj1q0ba82dmeun3v4f486.apps.googleusercontent.com", expoClientId: "701989901250-ieiu...

What is the knative's "mesh" gateway

I see that for every knative service, 2 VirtualService objects are created namely ksvc-ingress which has knative-serving/knative-ingress-gateway & knative-serving/knative-local-gateway gateways configured and ksvc-mesh which has mesh as the gateway. I can see the knative-serving/* gateways using kubectl but I am unable to find the mesh gateway object in any namespace. I would like to understand if mesh here denotes some special object or is it an istio keyword representing something else?

Spring Repositories returning Lists example

The Spring Data CrudRepository has various methods that return multiple instances of the entity managed by the repository. It does so by using Iterable and not List, as one might expect. In many cases, that is of no consequence, since you typically want to iterate over the result anyway. However, you might occasionally prefer a List. In these cases, Iterable is annoying. I will write more about why that choice was made in the first place and how you can deal with it as long as you are on Spring Data 2.x. However, let me get the good news out first: Repositories returning Lists Spring Data 3.0.0-M2 now offers a ListCrudRepository, which returns a List where CrudRepository returns an Iterable. Example 1. CrudRepository versus ListCrudRepository @NoRepositoryBean public interface CrudRepository<T, ID> extends Repository<T, ID> { <S extends T> S save(S entity); <S extends T> Iterable<S> saveAll(Iterable<S> entities); Optional<T> findById(ID i...

Spring Security: Configuring HttpSecurity

Spring Security 5.4 introduced the ability to configure HttpSecurity by creating a SecurityFilterChain bean. Below is an example configuration using the WebSecurityConfigurerAdapter that secures all endpoints with HTTP Basic: @Configuration public class SecurityConfiguration extends WebSecurityConfigurerAdapter {     @Override     protected void configure(HttpSecurity http) throws Exception {         http             .authorizeHttpRequests((authz) -> authz                 .anyRequest().authenticated()             )             .httpBasic(withDefaults());     } } Going forward, the recommended way of doing this is registering a SecurityFilterChain bean: @Configuration public class SecurityConfiguration {     @Bean     public SecurityFilterChain filterChain(HttpSecurity http) throws Except...

Spring Security: Configuring WebSecurity

Spring Security 5.4 also introduced the WebSecurityCustomizer. The WebSecurityCustomizer is a callback interface that can be used to customize WebSecurity. Below is an example configuration using the WebSecurityConfigurerAdapter that ignores requests that match /ignore1 or /ignore2: @Configuration public class SecurityConfiguration extends WebSecurityConfigurerAdapter {     @Override     public void configure(WebSecurity web) {         web.ignoring().antMatchers("/ignore1", "/ignore2");     } } Going forward, the recommended way of doing this is registering a WebSecurityCustomizer bean: @Configuration public class SecurityConfiguration {     @Bean     public WebSecurityCustomizer webSecurityCustomizer() {         return (web) -> web.ignoring().antMatchers("/ignore1", "/ignore2");     } } WARNING: If you are configuring WebSecurity to ignore requests, consider using permitAll via HttpSe...

Spring Security: LDAP Authentication exampe

Spring Security 5.7 introduced the EmbeddedLdapServerContextSourceFactoryBean, LdapBindAuthenticationManagerFactory and LdapPasswordComparisonAuthenticationManagerFactory which can be used to create an embedded LDAP Server and an AuthenticationManager that performs LDAP authentication. Below is an example configuration using WebSecurityConfigurerAdapter the that creates an embedded LDAP server and an AuthenticationManager that performs LDAP authentication using bind authentication: @Configuration public class SecurityConfiguration extends WebSecurityConfigurerAdapter {     @Override     protected void configure(AuthenticationManagerBuilder auth) throws Exception {         auth             .ldapAuthentication()             .userDetailsContextMapper(new PersonContextMapper())             .userDnPatterns("uid={0},ou=people")           ...

Spring Security: JDBC Authentication example

Below is an example configuration using the WebSecurityConfigurerAdapter with an embedded DataSource that is initialized with the default schema and has a single user: @Configuration public class SecurityConfiguration extends WebSecurityConfigurerAdapter {     @Bean     public DataSource dataSource() {         return new EmbeddedDatabaseBuilder()             .setType(EmbeddedDatabaseType.H2)             .build();     }     @Override     protected void configure(AuthenticationManagerBuilder auth) throws Exception {         UserDetails user = User.withDefaultPasswordEncoder()             .username("user")             .password("password")             .roles("USER")             .build();         auth.jdbc...

Spring Security: In-Memory Authentication example

Below is an example configuration using the WebSecurityConfigurerAdapter that configures an in-memory user store with a single user: @Configuration public class SecurityConfiguration extends WebSecurityConfigurerAdapter {     @Override     protected void configure(AuthenticationManagerBuilder auth) throws Exception {         UserDetails user = User.withDefaultPasswordEncoder()             .username("user")             .password("password")             .roles("USER")             .build();         auth.inMemoryAuthentication()             .withUser(user);     } } The recommended way of doing this is registering an InMemoryUserDetailsManager bean: @Configuration public class SecurityConfiguration {     @Bean     public InMemoryUserDetailsManager userDeta...

Spring Security : Global and Local AuthenticationManager example

Global AuthenticationManager To create an AuthenticationManager that is available to the entire application you can simply register the AuthenticationManager as a @Bean. @Configuration public class SecurityConfiguration {     @Bean     public EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {         EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean =             EmbeddedLdapServerContextSourceFactoryBean.fromEmbeddedLdapServer();         contextSourceFactoryBean.setPort(0);         return contextSourceFactoryBean;     }     @Bean     AuthenticationManager ldapAuthenticationManager(             BaseLdapPathContextSource contextSource) {         LdapBindAuthenticationManagerFactory factory =              new LdapBindAuthenticati...

Spring Security without the WebSecurityConfigurerAdapter

Spring Security moving towards a component-based security configuration. In Spring Security 5.7.0-M2, WebSecurityConfigurerAdapter is deprecated. To assist with the transition to this new style of configuration, we have compiled a list of common use-cases and the suggested alternatives going forward. In the examples below we follow best practice by using the Spring Security lambda DSL and the method HttpSecurity#authorizeHttpRequests to define our authorization rules. If you are new to the lambda DSL you can read about it in this blog post. If you would like to learn more about why we choose to use HttpSecurity#authorizeHttpRequests you can check out the reference documentation. Configuring HttpSecurity In Spring Security 5.4 we introduced the ability to configure HttpSecurity by creating a SecurityFilterChain bean. Below is an example configuration using the WebSecurityConfigurerAdapter that secures all endpoints with HTTP Basic: @Configuration public class SecurityConfiguration exten...