instruction
stringlengths
0
30k
API key 401 error in .env.development file
|javascript|bash|environment-variables|command-line-interface|
null
I am relaying my ssh connection and I want to restrict the ability of the remote user to view my files so I set `umask = 047`. However, it seems to also affect the local user in some way as I can no longer `mkdir` as the local user using either ``` mkdir test ``` or ``` sudo mkdir test ``` both yield `Permission denied` error However, I can ``` touch test ``` with no problem. I have checked that ownership of the current folder is the local user logged into wsl.
WSL able to touch file but mkdir: Permission denied
|windows-subsystem-for-linux|
i want to integrate cashfree payment gateway in ruby on rails, my project is built on ruby on rails at backend and React.js on froentend help me to integrate cashfree wanted a flow of gateway that 1) user comes click make payment 2) a cashfree window opens where user enter bank detail 3) user can pay through many way like: upi, barcode, cards, internet banking, etc gem cashfree but doc of that not available
{"Voters":[{"Id":16217248,"DisplayName":"CPlus"},{"Id":3744182,"DisplayName":"dbc"},{"Id":18157,"DisplayName":"Jim Garrison"}]}
I have been getting this error for a long now when trying to install hadoop on ubuntu.. :~/hadoop$ bin/hdfs namenode -format Unrecognized option: - Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit. I tried to format the namenode using the command but rather got this error as unrecognized command
Can anyoone help me with this problem while trying to install hadoop on ubuntu?
|ubuntu|hadoop|jvm|hdfs|namenode|
null
Kind of new to user authorization. After a few researches, I have a general idea of access and refresh token design with JWT. However, I still have a few questions: 1, After user signs in, user gets access and refresh token. Eventually, when user sends certain request, say "reqA", access token expires. Then user needs to send request to auth server with refresh token to get new access token. Then send the reqA again? In short, at some point of time while we are logged in, we need to make three requests just to successfully obtain resources from reqA? If expires duration is fairly short, we are frequently making extra requests just to refresh this access token? 2, From question 1, knowing that access token is expired ONLY by failing a request seems clumsy. When and how should we refresh access token? Should we set up some scheduled interval to refresh access token, listen to some event to fresh, etc in frontend? 3, Or should we somehow check the iat and expiration attributes of the access token before sending any requests and refresh access token as needed (say only refresh within the last 1 minute before it expires). Thanks
About access token and refresh token
|express-jwt|
I have set up a Kubernetes cluster with a single master node and three worker nodes running in VMs. Within this cluster, I deployed an nginx pod and created a LoadBalancer service using MetalLB to allocate an external IP address. The LoadBalancer service is exposing port 80, and when I SSH into the VM hosting the Kubernetes cluster and curl the external IP address, I receive the expected response from nginx. However, when attempting to access the service from my local device using the same external IP address, I encounter a connection failure with the error message: "Failed to connect to <IP> port 80 after 348 ms: Couldn't connect to server." I suspect the issue may lie in the IP address range specified in the IPAddressPool of MetalLB. Currently, I've assigned an external IP address within the range of my master node. How can I determine the appropriate value for the IP address range in MetalLB's IPAddressPool to enable access to the LoadBalancer service from devices outside the Kubernetes cluster? Any guidance or suggestions would be greatly appreciated. I created an nginx pod using below command ``` kubectl create deploy nginx --image=quay.io/redhattraining/hello-world-nginx ``` The result of `kubectl get deploy -oyaml` looks like ``` apiVersion: v1 items: - apiVersion: apps/v1 kind: Deployment metadata: annotations: deployment.kubernetes.io/revision: "1" creationTimestamp: "2024-03-30T08:34:01Z" generation: 1 labels: app: nginx name: nginx namespace: default resourceVersion: "5748" uid: ff20a336-075e-45cd-9a2e-29110d3e9bce spec: progressDeadlineSeconds: 600 replicas: 1 revisionHistoryLimit: 10 selector: matchLabels: app: nginx strategy: rollingUpdate: maxSurge: 25% maxUnavailable: 25% type: RollingUpdate template: metadata: creationTimestamp: null labels: app: nginx spec: containers: - image: quay.io/redhattraining/hello-world-nginx imagePullPolicy: Always name: hello-world-nginx resources: {} terminationMessagePath: /dev/termination-log terminationMessagePolicy: File dnsPolicy: ClusterFirst restartPolicy: Always schedulerName: default-scheduler securityContext: {} terminationGracePeriodSeconds: 30 status: availableReplicas: 1 conditions: - lastTransitionTime: "2024-03-30T08:34:20Z" lastUpdateTime: "2024-03-30T08:34:20Z" message: Deployment has minimum availability. reason: MinimumReplicasAvailable status: "True" type: Available - lastTransitionTime: "2024-03-30T08:34:02Z" lastUpdateTime: "2024-03-30T08:34:20Z" message: ReplicaSet "nginx-774b9c499f" has successfully progressed. reason: NewReplicaSetAvailable status: "True" type: Progressing observedGeneration: 1 readyReplicas: 1 replicas: 1 updatedReplicas: 1 kind: List metadata: resourceVersion: "" ``` **IPAddressPool** ``` apiVersion: metallb.io/v1beta1 kind: IPAddressPool metadata: name: first-pool namespace: metallb-system spec: addresses: - <IP Range> autoAssign: true avoidBuggyIPs: false ``` **Service** ``` apiVersion: v1 kind: Service metadata: name: nginx-lb-service spec: selector: app: nginx ports: - protocol: TCP port: 80 targetPort: 8080 type: LoadBalancer ``` `kubectl get svc` gives below result ``` NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE nginx-lb-service LoadBalancer 10.107.57.161 <First IP in the pool> 80:30732/TCP 13h ``` when I take ssh into the vm which host k8s cluster and then run curl <EXTERNAL-IP> I get the expected response ``` <html> <body> <h1>Hello, world from nginx!</h1> </body> </html> ``` but when I try the same from my local device it is giving me below response ``` curl: (7) Failed to connect to <IP> port 80 after 348 ms: Couldn't connect to server. ``` when nothing was not working I created L2Advertisement like ``` apiVersion: metallb.io/v1beta1 kind: L2Advertisement metadata: name: nginx-expose namespace: metallb-system spec: ipAddressPools: - first-pool ``` But that also didn't helped. Note: I am not using minikube or kind cluster.
Unable to Access Kubernetes LoadBalancer Service from Local Device Outside Cluster
|kubernetes|metallb|
null
Hi I am trying to upload a row I took from a dataframe and upload it to DynamoDB. I keep getting below error message and it wouldn't get fixed. I tried .astype(int), isinstance and everything I can find and it's still not working. Any thoughts please? Unsupported type "<class 'numpy.int64'>" for value "0"
TypeError trying to upload a row to DynamoDB; Unsupported type "<class 'numpy.int64'>" for value "0"
|amazon-dynamodb|
null
[screen shot](https://i.stack.imgur.com/PJAo9.jpg) Questions: 1. How to edit monitor screen layer separately, which is attached to 1st layer 2. If I tried edit the monitor screen individually background size is fixed so I can make the monitor screen size larger, so how to fix that too?
How to import a local image in vuex store without using axios
|vuejs3|vuex|
null
|c++|templates|visual-c++|
|c|recursion|return|clang|
When using FLATTEN function in Snowflake, we use the values in the PATH column, to dynamically construct a SELECT clause to query the semi-structured (JSON) column in the data table. We concatenate: ``` <variant_col>:<value_in_path_column>, ``` This means we assume the values in the PATH column are to be used with the Dot Notation (as described [here](https://docs.snowflake.com/en/user-guide/querying-semistructured#dot-notation)) We encountered a rare scenario, where the field key inside the variant column conatains a dot (.) in it, for example: ``` { "0.text": "some_string_value", "legal_name": "other_string_value" } ``` In this case, after running the FLATTEN function, we get the following output: | VARIANT_COL | SEQ | KEY | PATH | INDEX | VALUE | -------- | -------- | -------- | -------- | -------- | -------- | | { "0.text": "foo", "legal_name": "bar" } | 1 | 0.text | ['0.text'] | | "foo" | | { "0.text": "foo", "legal_name": "bar" } | 1 | legal_name | legal_name | | "bar" | We expect the value in the PATH column to be `"0.text"` instead of `['0.text']` Is there a way to force it into a Dot Notation? Thanks Code to recreate the issue: ``` create temp table notation_issue as select parse_json($${"0.text": "foo", "legal_name": "bar"}$$) as variant_col; create temp table flatten_results as select * from notation_issue, lateral flatten(variant_col, recursive=>True); select 'select ' || listagg('variant_col:' || path, ',\n') || ' from notation_issue' from flatten_results ; /* This raises an error */ select variant_col:['0.text'], variant_col:legal_name from notation_issue; /* This does not raise an error */ select variant_col['0.text'], variant_col:legal_name from notation_issue; /* This also does not raise an error */ select variant_col:"0.text", variant_col:legal_name from notation_issue; ```
How to make FLATTEN function in Snowflake return PATH in Dot Notation instead of Brackets Notation
|snowflake-cloud-data-platform|flatten|dot-notation|
null
When using the !! operator in Map Sonar cube issues warning [s6611 "Map" values should be accessed safely][1]. One solution from Sonar is to use getValue, which will throw a NoSuchElementException if the key is not found. val a = mapOf<Int, Map<String, String>>() a[999]!!["x"] // NullPointerException a.getValue(999)["x"] // NoSuchElementException: Key 999 is missing in the map. What is the benefit of NoSuchElementException other than reporting the value of a key that is not found? [1]: https://rules.sonarsource.com/kotlin/RSPEC-6611/
Why is NoSuchElementException preferred over NullPointerException when retrieving from a Map?
|kotlin|null|nullpointerexception|hashmap|nosuchelementexception|
I have a C#/Blazor project where i use tailwindcss for the user interface. Visual Studio highlights the @apply directives in the .css files from tailwind as unkown @-blocks. Are there any ways to teach Visual Studio about them, disable this warning or replace @apply by some known directives? Example: ``` table { @apply table-fixed inline-block border-collapse overflow-hidden border border-gray-dark rounded; } ``` For the *@tailwindcss* directives i used the replacements *@import 'tailwindcss/base';* and so on.
I thought I could easily display a toolbar in UIKit, but I was wrong, or at least I can't do so without getting "Unable to simultaneously satisfy constraints." console messages. Here is my code: ```swift import UIKit class ViewController: UIViewController { let toolbar = UIToolbar() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground toolbar.items = [ UIBarButtonItem(title: "Title", style: .plain, target: nil, action: nil), UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) ] view.addSubview(toolbar) toolbar.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ toolbar.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), toolbar.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), toolbar.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor), toolbar.heightAnchor.constraint(equalToConstant: 44) ]) } } ``` And here is the console log: ```lang-none Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "<NSAutoresizingMaskLayoutConstraint:0x600002107b10 h=--& v=--& _UIToolbarContentView:0x104008e40.height == 0 (active)>", "<NSLayoutConstraint:0x600002122e90 V:|-(0)-[_UIButtonBarStackView:0x10250d8b0] (active, names: '|':_UIToolbarContentView:0x104008e40 )>", "<NSLayoutConstraint:0x600002121ef0 _UIButtonBarStackView:0x10250d8b0.bottom == _UIToolbarContentView:0x104008e40.bottom (active)>", "<NSLayoutConstraint:0x600002107a70 UIButtonLabel:0x10250f280.centerY == _UIModernBarButton:0x1027059c0'Title'.centerY + 1.5 (active)>", "<NSLayoutConstraint:0x60000210ea30 'TB_Baseline_Baseline' _UIModernBarButton:0x1027059c0'Title'.lastBaseline == UILayoutGuide:0x600003b0ca80'UIViewLayoutMarginsGuide'.bottom (active)>", "<NSLayoutConstraint:0x60000210ea80 'TB_Top_Top' V:|-(>=0)-[_UIModernBarButton:0x1027059c0'Title'] (active, names: '|':_UIButtonBarButton:0x102607120 )>", "<NSLayoutConstraint:0x60000210e8f0 'UIButtonBar.maximumAlignmentSize' _UIButtonBarButton:0x102607120.height == UILayoutGuide:0x600003b00380'UIViewLayoutMarginsGuide'.height (active)>", "<NSLayoutConstraint:0x60000212c960 'UIView-bottomMargin-guide-constraint' V:[UILayoutGuide:0x600003b00380'UIViewLayoutMarginsGuide']-(0)-| (active, names: '|':_UIButtonBarStackView:0x10250d8b0 )>", "<NSLayoutConstraint:0x60000210ec60 'UIView-bottomMargin-guide-constraint' V:[UILayoutGuide:0x600003b0ca80'UIViewLayoutMarginsGuide']-(11)-| (active, names: '|':_UIButtonBarButton:0x102607120 )>", "<NSLayoutConstraint:0x60000212d6d0 'UIView-topMargin-guide-constraint' V:|-(0)-[UILayoutGuide:0x600003b00380'UIViewLayoutMarginsGuide'] (active, names: '|':_UIButtonBarStackView:0x10250d8b0 )>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x600002107a70 UIButtonLabel:0x10250f280.centerY == _UIModernBarButton:0x1027059c0'Title'.centerY + 1.5 (active)> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful. Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "<NSAutoresizingMaskLayoutConstraint:0x600002106710 h=--& v=--& _UIToolbarContentView:0x104008e40.width == 0 (active)>", "<NSLayoutConstraint:0x600002120b40 H:|-(0)-[_UIButtonBarStackView:0x10250d8b0] (active, names: '|':_UIToolbarContentView:0x104008e40 )>", "<NSLayoutConstraint:0x600002122e40 H:[_UIButtonBarStackView:0x10250d8b0]-(0)-| (active, names: '|':_UIToolbarContentView:0x104008e40 )>", "<NSLayoutConstraint:0x60000210eda0 'TB_Leading_Leading' H:|-(16)-[_UIModernBarButton:0x1027059c0'Title'] (active, names: '|':_UIButtonBarButton:0x102607120 )>", "<NSLayoutConstraint:0x60000210eb70 'TB_Trailing_Trailing' H:[_UIModernBarButton:0x1027059c0'Title']-(16)-| (active, names: '|':_UIButtonBarButton:0x102607120 )>", "<NSLayoutConstraint:0x60000210e580 'UISV-canvas-connection' UILayoutGuide:0x600003b00380'UIViewLayoutMarginsGuide'.leading == _UIButtonBarButton:0x102607120.leading (active)>", "<NSLayoutConstraint:0x60000210e5d0 'UISV-canvas-connection' UILayoutGuide:0x600003b00380'UIViewLayoutMarginsGuide'.trailing == UIView:0x10400e480.trailing (active)>", "<NSLayoutConstraint:0x60000210e9e0 'UISV-spacing' H:[_UIButtonBarButton:0x102607120]-(0)-[UIView:0x10400e480] (active)>", "<NSLayoutConstraint:0x60000212c820 'UIView-leftMargin-guide-constraint' H:|-(0)-[UILayoutGuide:0x600003b00380'UIViewLayoutMarginsGuide'](LTR) (active, names: '|':_UIButtonBarStackView:0x10250d8b0 )>", "<NSLayoutConstraint:0x60000212ca00 'UIView-rightMargin-guide-constraint' H:[UILayoutGuide:0x600003b00380'UIViewLayoutMarginsGuide']-(0)-|(LTR) (active, names: '|':_UIButtonBarStackView:0x10250d8b0 )>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x60000210eb70 'TB_Trailing_Trailing' H:[_UIModernBarButton:0x1027059c0'Title']-(16)-| (active, names: '|':_UIButtonBarButton:0x102607120 )> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful. ``` I tried giving the toolbar a frame rather than constraints, and also to not give it an explicit height. The only thing that works is to comment out `UIBarButtonItem(title: "Title", style: .plain, target: nil, action: nil)`, which isn't really a solution. What am I doing wrong?
|ios|swift|uikit|constraints|uitoolbar|
I had the same problem, it turned out to be some permissions, see [answers here][1] Write in your VS Code terminal or Windows PowerShell: Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned or Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted [1]: https://stackoverflow.com/questions/41117421/ps1-cannot-be-loaded-because-running-scripts-is-disabled-on-this-system
I need to add the Luxon library to my google sheet script. Where do I find the ID of the Luxon library, or are there other ways? Thank you
How do I add the Luxon library google sheet script
|google-apps-script|luxon|
Say I have a vector of some generic T objects: std::vector<T> vector_of_ts = {...}; That vector is basically a heap-allocated array of T objects, under the hood. Now, say I have the following: std::unique_ptr<T> t = std::make_unique<T>(...); Again, this is a heap-allocated T object under the hood. Is it possible to push back that object to the vector *by moving it*, without making temporary/extra copies? Something like: vector_of_ts.move(*t)
Can I move a std::unique_ptr<T> into a std::vector<T>?
|c++|move-semantics|
EntityFrameworkCore.DbUpdateException: Unable to delete row, SQL Syntax error
|entity-framework-core|mariadb|asp.net-core-webapi|dbcontext|
Given the invariant that your input string is a valid email address, you could just write: >> "hey@mycorp.com".split("@").last => "mycorp.com"
I wait until the page is loaded and use the "DOMContentLoaded" method to add eventhandlers on some p tags. This works until I open and close the modal. Can someone please tell me why the page fully freezes? ``` <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="div_1"> <p>One</p> <p>Two</p> <p>Three</p> </div> <p id="open_modal">open the modal</p> <script> document.addEventListener("DOMContentLoaded", () => { let test = document.querySelector("#div_1") for (let i = 0; i < test.children.length; i++) { test.children[i].addEventListener("click", () => { console.log(test.children[i].innerHTML) }); }; }); document.querySelector("#open_modal").addEventListener("click", () => { if (!document.querySelector("#modal")) { document.body.innerHTML += ` <div id="modal" style="display: block; position: fixed; z-index: 1; padding-top: 100px; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0,0,0); background-color: rgba(0,0,0,0.4)"> <div id="modal_content"> <span id="modal_close">&times;</span> <p style="color: green;">Some text in the Modal..</p> </div> </div> `; document.querySelector("#modal_close").addEventListener("click", () => { document.querySelector("#modal").style.display = "none"; }); } else { document.querySelector("#modal").style.display = "block"; }; }); </script> </body> </html> ```
how to integrate cashfree payment gateway in ruby on rails project
|ruby-on-rails|ruby|payment-gateway|payment-method|cashfree|
null
// Recursive Java program to print lca of two nodes // A binary tree node class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; } } class BinaryTree { Node root; /* Function to find LCA of n1 and n2. The function assumes that both n1 and n2 are present in BST */ Node lca(Node node, int n1, int n2) { if (node == null) return null; // If both n1 and n2 are smaller than root, then LCA // lies in left if (node.data > n1 && node.data > n2) return lca(node.left, n1, n2); // If both n1 and n2 are greater than root, then LCA // lies in right if (node.data < n1 && node.data < n2) return lca(node.right, n1, n2); return node; } /* Driver code */ public static void main(String args[]) { // Let us construct the BST shown in the above // figure BinaryTree tree = new BinaryTree(); tree.root = new Node(20); tree.root.left = new Node(8); tree.root.right = new Node(22); tree.root.left.left = new Node(4); tree.root.left.right = new Node(12); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(14); // Function calls int n1 = 10, n2 = 14; Node t = tree.lca(tree.root, n1, n2); System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data); n1 = 14; n2 = 8; t = tree.lca(tree.root, n1, n2); System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data); n1 = 10; n2 = 22; t = tree.lca(tree.root, n1, n2); } }
My task is to create a tool that, based on (specific) input data, will generate a 'grid' of employees' working hours and spit out specific shifts 6-14; 7-15; 10-20 etc etc. The general operation of such a macro, let's say I have one, the problem begins when the macro must have a requirement that in a given row (the row is one employee) the sum cannot be greater than 10. Below I paste the code I managed to create, which fills in the values ​​accordingly based on the input data, but without this requirement (row sum not greater than 10). ``` Sub AutoFill() Dim ws As Worksheet Dim col As Integer Dim row As Integer Dim suma As Integer Dim liczba_osob As Integer ' Ustaw arkusz, na którym chcesz działać Set ws = ThisWorkbook.Sheets("01") ' Wyczyść zakres G5:AD36 ws.Range("G5:AD36").ClearContents ' Iteruj przez kolumny od G do Y For col = 7 To 30 ' Pobierz liczbę osób w pracy w danej godzinie liczba_osob = ws.Cells(2, col).Value ' Ustaw sumę kolumny na 0 suma = 0 ' Uzupełnij komórki wartością 1 do momentu, gdy suma wiersza będzie równa liczbie osób w pracy For row = 5 To 36 ' Sprawdź, czy suma nie przekracza liczby osób w pracy If suma < liczba_osob Then ws.Cells(row, col).Value = 1 suma = suma + 1 Else ' Jeśli suma przekroczyła liczbę osób w pracy, zostaw komórkę pustą If Not IsEmpty(ws.Cells(row, col)) Then ws.Cells(row, col).ClearContents End If End If Next row Next col End Sub ``` There are also screenshots below in the attachments - in one there is the addition of "1" by the macro, in the other the addition of "1" by me in the way the macro should be supplemented. Yes, as part of the implementation, the number of employees in each hour is given in the G2:AD2 range, and the hours are listed in G1:AD1. Can anyone help me or guide me somehow to make it work? Unless it is possible to completely omit all these "1"s and directly generate individual changes 6-14, 7-15, etc. based on the demand given in G2:AD2... [enter image description here](https://i.stack.imgur.com/5SoVk.jpg) [enter image description here](https://i.stack.imgur.com/7hKUC.jpg) I need solution for filling like in screenshot.
React router dom routing redirect
|reactjs|typescript|react-router|
null
being pretty new to **Scala** can any one please kindly help me with a scenario where I need to get the file with latest modified date. There are two scenarios. consider 2 directories , - **dir1** (which has sub directories and files present inside each sub directory ) - **dir2** (no sub directories but has only files ) for Scenario 1 - I need to get the file with latest modified date inside a latest modified date directory for Scenario 2 - I just need the latest file with latest modified. Please do help me in any way possible, I tried experiments with **java.io** file handling but haven't made any good progress. [![adding the code I tried][1]][1] [1]: https://i.stack.imgur.com/edCB9.png
I'm relatively new to using neo4j. I've connected to a database with the py2neo library and populated the database with the faker library to create nodes for Person and Address each with attributes attached to them. I'm interested in creating indexes and testing the performance of different indexes. Before I get to that point, I created some indexes and used the command ``` `graph.run("SHOW INDEXES;")` ``` [Output][1] I was expecting 2 indexes to show but 3 indexes returned. The final one was a Look up type and had some null properties. That attached image shows the output, Why is this index showing up? Thanks. I was expecting only 2 to return, so I'm thinking maybe this is some lack of understanding on my part? I've started reading through the Neo4j documentation on indexes but I'm still unsure. Any help would be appreciated. Thanks! [1]: https://i.stack.imgur.com/6Hw4J.png
I'm trying to create a pod that runs Kafka and ZooKeeper and connect to it via Python. However, with my current configuration, I'm unable to send or receive messages from the Python client, although I can successfully connect to the port exposed by Kafka. I'm currently experiencing issues with my pod configuration. I've defined topics and checked in Lens which port the Kafka service exposed. I can confirm that it's connecting to Kafka, but when I send messages from a producer and access the container, none of them arrive. Similarly, no information is received from the consumer. I've already ruled out errors related to ports or topics as I've checked them thoroughly. apiVersion: apps/v1 kind: StatefulSet metadata: name: kafka-zookeeper spec: serviceName: kafka-zookeeper-service replicas: 1 selector: matchLabels: app: kafka-zookeeper template: metadata: labels: app: kafka-zookeeper spec: containers: - name: zookeeper image: docker.io/bitnami/zookeeper:3.9 env: - name: ALLOW_ANONYMOUS_LOGIN value: "yes" - name: ZOO_VOLUME_DIR value: /bitnami/zookeeper ports: - containerPort: 2181 name: zookeeper volumeMounts: - name: zookeeper-data mountPath: /bitnami/zookeeper - name: kafka image: docker.io/bitnami/kafka:3.4 env: - name: KAFKA_CFG_ZOOKEEPER_CONNECT value: kafka-zookeeper-service:2181 - name: KAFKA_VOLUME_DIR value: /bitnami/kafka - name: KAFKA_CFG_AUTO_CREATE_TOPICS_ENABLE value: "true" - name: KAFKA_CFG_PROCESS_ROLES value: controller,broker - name: KAFKA_CFG_LISTENERS value: "PLAINTEXT://:9092,CONTROLLER://:9093" - name: KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP value: "CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT" - name: KAFKA_CFG_CONTROLLER_QUORUM_VOTERS value: "1001@localhost:9093" - name: KAFKA_CFG_CONTROLLER_LISTENER_NAMES value: "CONTROLLER" - name: KAFKA_CFG_NODE_ID value: "1001" - name: KAFKA_CFG_ZOOKEEPER_METADATA_MIGRATION_ENABLE value: "true" ports: - containerPort: 9092 name: kafka - containerPort: 9093 name: kafka-plaintext - containerPort: 9094 name: kafka-tls volumeMounts: - name: kafka-data mountPath: /bitnami/kafka volumes: - name: zookeeper-data persistentVolumeClaim: claimName: zookeeper-data-pvc - name: kafka-data persistentVolumeClaim: claimName: kafka-data-pvc --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: zookeeper-data-pvc spec: accessModes: - ReadWriteOnce resources: requests: storage: 2Gi --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: kafka-data-pvc spec: accessModes: - ReadWriteOnce resources: requests: storage: 2Gi --- apiVersion: v1 kind: Service metadata: name: kafka-zookeeper-service spec: selector: app: kafka-zookeeper ports: - protocol: TCP port: 2181 targetPort: 2181 name: zookeeper - protocol: TCP port: 9092 targetPort: 9092 name: kafka - protocol: TCP port: 9093 targetPort: 9093 name: kafka-plaintext - protocol: TCP port: 9094 targetPort: 9094 name: kafka-tls > **Producer** from kafka import KafkaProducer import json def main(): bootstrap_servers = 'localhost:34715' topic = 'dev' message = {'message': 'Hello from the producer'} try: producer = KafkaProducer( bootstrap_servers=bootstrap_servers, value_serializer=lambda v: json.dumps(v).encode('utf-8') ) print("Successful connection to Kafka server at:", bootstrap_servers) producer.send(topic, value=message) print("Message sent successfully to topic:", topic) except Exception as e: print("Error sending message:", e) if __name__ == '__main__': main() > **Consumer** from kafka import KafkaConsumer def main(): consumer = KafkaConsumer('dev', bootstrap_servers='localhost:34715') try: for message in consumer: print(f'Message received: {message.value.decode("utf-8")}') finally: consumer.close() if __name__ == '__main__': main()
Having a dataset like this: |Index|Role|Name|Grade| |---|---|---|---| |1|Provider|Alex|7| |2|Provider|William|7.5| |7|Provider|Juan|5.5| |15|Provider|Pedro|4.5| |25|Client|George|8| |26|Provider|Mark|9.4| |37|Client|James|8.1| |39|Transporter|Anthony|9.5| |50|Transporter|Jason|7| I'm trying to group the consecutive rows with same **Role** value. I can achieve this by using the following sentence: df = df.groupby((df.Role!= df.Role.shift()).cumsum()).agg( Role = ('Role', 'first'), Name = ('Name', ' '.join), Grade = ('Grade', 'mean') ).reset_index(drop=True) This would leave the dataframe looking like this: |Index|Role|Name|Grade| |---|---|---|---| |1|Provider|Alex William Juan Pedro|6.125| |2|Client|George|8| |3|Provider|Mark|9.4| |4|Client|James|8.1| |5|Transporter|Anthony Jason|8.25| Now I would like to add a new rule. I would like to only group when the dataframe index has a difference of 5 units at maximum from previous row: |Index|Role|Name|Grade| |---|---|---|---| |1|Provider|Alex William Juan|6.67| |2|Provider|Pedro|4.5| |3|Client|George|8| |4|Provider|Mark|9.4| |5|Client|James|8.1| |6|Transporter|Anthony|9.5| |7|Transporter|Jason|7| How could I achieve this? Also if there is any grouping method more efficient, it is welcome.
Pandas groupby equal consecutive column values based on index
|pdf|
[1]I try to use FocusNode() in TextFormField so it will detect when I focus on the TextFormField, the text above will have it's color changed. But it seems not working, what seems to be the problem? [enter image description here][2] ``` import 'package:flutter/material.dart'; class SignIn extends StatefulWidget { const SignIn({Key? key}) : super(key: key); @override _SignInState createState() => _SignInState(); } class _SignInState extends State<SignIn> { bool isPasswordVisible = false; bool _isEmail = true; bool _isPassword = true; TextEditingController emailInput = TextEditingController(); TextEditingController passwordInput = TextEditingController(); FocusNode emailText = FocusNode(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: SingleChildScrollView( child: Container( padding: EdgeInsets.all(30.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Sign In to Coinify', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 24.0, fontFamily: "Graphik", ) ), SizedBox(height: 20.0), Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Email', style: TextStyle( fontWeight: FontWeight.w600, fontSize: 16.0, color: emailText.hasFocus ? Colors.blue : Colors.black, fontFamily: "Graphik", ), ), SizedBox(height: 8.0), TextFormField( focusNode: emailText, controller: emailInput, decoration: InputDecoration( contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 10), border: OutlineInputBorder(), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.grey) ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.blue) ), errorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red) ), hintText: 'Enter your email', errorText: _isEmail ? null : "Email must not be empty", ), ) ], ), SizedBox(height: 20.0), Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Password', style: TextStyle( fontWeight: FontWeight.w600, fontSize: 16.0, fontFamily: "Graphik", ), ), SizedBox(height: 8.0), TextFormField( controller: passwordInput, obscureText: !isPasswordVisible, decoration: InputDecoration( contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 10), border: OutlineInputBorder(), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.grey) ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.blue) ), errorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red), ), hintText: 'Enter your password', errorText: _isPassword ? null : "Password must not be empty", suffixIcon: GestureDetector( onTap: () { setState(() { isPasswordVisible = !isPasswordVisible; }); }, child: Icon( isPasswordVisible ? Icons.visibility : Icons.visibility_off, ), ), ), ) ], ), SizedBox(height: 50.0), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () { Navigator.pushNamed(context, '/forgot-password'); }, child: Text( 'Forgot password?', style: TextStyle( color: Colors.blue, ) ) ) ), MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () { Navigator.pushNamed(context, '/privacy-policy'); }, child: Text( 'Privacy policy', style: TextStyle( color: Colors.blue, ) ) ) ), ] ), SizedBox(height: 20.0), ElevatedButton( onPressed: () { setState(() { if(emailInput.text == ""){_isEmail = false;} else{_isEmail = true;} if(passwordInput.text == ""){_isPassword = false;} else{_isPassword = true;} if(_isEmail && _isPassword) {Navigator.pushNamed(context, '/sign-in-code');} }); }, child: Text( "Sign in", style: TextStyle( fontSize: 14.0, fontWeight: FontWeight.normal, color: Colors.white ), ), style: ButtonStyle( shape: MaterialStateProperty.all<RoundedRectangleBorder>( RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)) ), minimumSize: MaterialStateProperty.all(Size.fromHeight(60.0)), backgroundColor: MaterialStateProperty.all(Colors.blue), shadowColor: MaterialStateProperty.all(Colors.transparent) ), ) ] ) ), ) ); } } ``` I have tried to change the color in the ternary operator and realized that the Color seems to stuck in false value [1]: https://i.stack.imgur.com/w70Ig.png [2]: https://i.stack.imgur.com/oUKCW.png
In Delphi 7 I have a report written in QuickReport. The report is called by the function from another form ~~~ var RepResult : integer RepResult := ShowReport(param1,param2...); ~~~ The function inside report looks like ~~~ ` var QuickRep1 : TQuickReport; ReportResult : integer; function ShowReport(param1,param2...) : integer begin ... QuickRep1.PreviewModal; Result := ReportResult; end;` ~~~ The calculation of variable ReportResult is complicated, based on many queries inside QuickReport and calculated in events of DetailBands, ChildBands ,LoopBands and so on . The report and the calculations works fine , but now the customer wants to see result of this calculations in another place without viewing the report. So the question is : Is it possible to get only the result of the function without previewing or printing the report ? I tried QuickRep1.PreviewModeless and quickrep1.print to non-existed printer. Nothing works
Centering a map element on a generated PDF
I try to use FocusNode() in TextFormField so it will detect when I focus on the TextFormField, the text above will have it's color changed. But it seems not working, what seems to be the problem? [enter image description here][1] ``` import 'package:flutter/material.dart'; class SignIn extends StatefulWidget { const SignIn({Key? key}) : super(key: key); @override _SignInState createState() => _SignInState(); } class _SignInState extends State<SignIn> { bool isPasswordVisible = false; bool _isEmail = true; bool _isPassword = true; TextEditingController emailInput = TextEditingController(); TextEditingController passwordInput = TextEditingController(); FocusNode emailText = FocusNode(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: SingleChildScrollView( child: Container( padding: EdgeInsets.all(30.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Sign In to Coinify', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 24.0, fontFamily: "Graphik", ) ), SizedBox(height: 20.0), Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Email', style: TextStyle( fontWeight: FontWeight.w600, fontSize: 16.0, color: emailText.hasFocus ? Colors.blue : Colors.black, fontFamily: "Graphik", ), ), SizedBox(height: 8.0), TextFormField( focusNode: emailText, controller: emailInput, decoration: InputDecoration( contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 10), border: OutlineInputBorder(), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.grey) ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.blue) ), errorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red) ), hintText: 'Enter your email', errorText: _isEmail ? null : "Email must not be empty", ), ) ], ), SizedBox(height: 20.0), Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Password', style: TextStyle( fontWeight: FontWeight.w600, fontSize: 16.0, fontFamily: "Graphik", ), ), SizedBox(height: 8.0), TextFormField( controller: passwordInput, obscureText: !isPasswordVisible, decoration: InputDecoration( contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 10), border: OutlineInputBorder(), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.grey) ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.blue) ), errorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red), ), hintText: 'Enter your password', errorText: _isPassword ? null : "Password must not be empty", suffixIcon: GestureDetector( onTap: () { setState(() { isPasswordVisible = !isPasswordVisible; }); }, child: Icon( isPasswordVisible ? Icons.visibility : Icons.visibility_off, ), ), ), ) ], ), SizedBox(height: 50.0), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () { Navigator.pushNamed(context, '/forgot-password'); }, child: Text( 'Forgot password?', style: TextStyle( color: Colors.blue, ) ) ) ), MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () { Navigator.pushNamed(context, '/privacy-policy'); }, child: Text( 'Privacy policy', style: TextStyle( color: Colors.blue, ) ) ) ), ] ), SizedBox(height: 20.0), ElevatedButton( onPressed: () { setState(() { if(emailInput.text == ""){_isEmail = false;} else{_isEmail = true;} if(passwordInput.text == ""){_isPassword = false;} else{_isPassword = true;} if(_isEmail && _isPassword) {Navigator.pushNamed(context, '/sign-in-code');} }); }, child: Text( "Sign in", style: TextStyle( fontSize: 14.0, fontWeight: FontWeight.normal, color: Colors.white ), ), style: ButtonStyle( shape: MaterialStateProperty.all<RoundedRectangleBorder>( RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)) ), minimumSize: MaterialStateProperty.all(Size.fromHeight(60.0)), backgroundColor: MaterialStateProperty.all(Colors.blue), shadowColor: MaterialStateProperty.all(Colors.transparent) ), ) ] ) ), ) ); } } ``` I have tried to change the color in the ternary operator and realized that the Color seems to stuck in false value [1]: https://i.stack.imgur.com/KQLrU.png
it depends on how many bg images you have specified .box { background-image: url(image1.png), url(image2.png); background-color: blue; } in the above there are 3 bg layers
You can use ModuleType: from types import ModuleType a = ModuleType("some") # name of obj a.foo = 123 print(a.foo) print(a.__name__) # some a.__dict__ # {'__name__': 'some', '__doc__': None, '__package__': None, '__loader__': None, '__spec__': None, 'foo': 123} Though name will be mandatory, but you can replace it by some placeholder: a = ModuleType(".") b = ModuleType(".")
`psycopg2.errors.UndefinedObject: operator class "gin_trgm_ops" does not exist for access method "gin"` Hello everybody, this is the whole message when I try to run pytest on my project which is written in Python/Django + db is postgresql and all sitting inside docker. I build a project on docker with django-cookiecutter template, all settings are default. I put a gin index to one of my string fields, migrations running successfully, `pg_trgm` extention is being created successfully, but if I try to test my project with pytest I got this error. Here is my `pytest.ini` ``` [pytest] DJANGO_SETTINGS_MODULE = config.settings.test ``` Here is my test settings file's database configuration: `test.py` ``` DATABASES['test'] = { # noqa 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'test', 'PASSWORD': 'test', 'USER': 'test', 'HOST': 'localhost', 'PORT': 5454, } ``` This is part of the migration which creates the extention `pg_trim` and puts an index to the field given ``` migrations.AddIndex( model_name='<model_name>', index=django.contrib.postgres.indexes.GinIndex(fields=['field_name'], name='field_name_gin_idx', opclasses=['gin_trgm_ops']), ), ``` And this is the whole traceback which I am getting: ``` self = <django.db.backends.utils.CursorWrapper object at 0xffff7244dbb0> sql = 'CREATE INDEX "bank_name_gin_idx" ON "financing_graincreditagrobankworksheet" USING gin ("bank_name" gin_trgm_ops)', params = None ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0xffff7d096b80>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0xffff7244dbb0>}) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: # params default might be backend specific. > return self.cursor.execute(sql) E psycopg2.errors.UndefinedObject: operator class "gin_trgm_ops" does not exist for access method "gin" /usr/local/lib/python3.9/site-packages/django/db/backends/utils.py:82: UndefinedObject The above exception was the direct cause of the following exception: request = <SubRequest '_django_setup_unittest' for <TestCaseFunction test_correct_insurance_company_name>> django_db_blocker = <pytest_django.plugin._DatabaseBlocker object at 0xffff7fe702b0> @pytest.fixture(autouse=True, scope="class") def _django_setup_unittest( request, django_db_blocker: "_DatabaseBlocker", ) -> Generator[None, None, None]: """Setup a django unittest, internal to pytest-django.""" if not django_settings_is_configured() or not is_django_unittest(request): yield return # Fix/patch pytest. # Before pytest 5.4: https://github.com/pytest-dev/pytest/issues/5991 # After pytest 5.4: https://github.com/pytest-dev/pytest-django/issues/824 from _pytest.unittest import TestCaseFunction original_runtest = TestCaseFunction.runtest def non_debugging_runtest(self) -> None: self._testcase(result=self) try: TestCaseFunction.runtest = non_debugging_runtest # type: ignore[assignment] > request.getfixturevalue("django_db_setup") /usr/local/lib/python3.9/site-packages/pytest_django/plugin.py:490: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/local/lib/python3.9/site-packages/pytest_django/fixtures.py:122: in django_db_setup db_cfg = setup_databases( /usr/local/lib/python3.9/site-packages/django/test/utils.py:179: in setup_databases connection.creation.create_test_db( /usr/local/lib/python3.9/site-packages/django/db/backends/base/creation.py:74: in create_test_db call_command( /usr/local/lib/python3.9/site-packages/django/core/management/__init__.py:181: in call_command return command.execute(*args, **defaults) /usr/local/lib/python3.9/site-packages/django/core/management/base.py:398: in execute output = self.handle(*args, **options) /usr/local/lib/python3.9/site-packages/django/core/management/base.py:89: in wrapped res = handle_func(*args, **kwargs) /usr/local/lib/python3.9/site-packages/django/core/management/commands/migrate.py:244: in handle post_migrate_state = executor.migrate( /usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py:117: in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) /usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py:147: in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) /usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py:227: in apply_migration state = migration.apply(state, schema_editor) /usr/local/lib/python3.9/site-packages/django/db/migrations/migration.py:126: in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) /usr/local/lib/python3.9/site-packages/django/db/migrations/operations/models.py:761: in database_forwards schema_editor.add_index(model, self.index) /usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/schema.py:218: in add_index self.execute(index.create_sql(model, self, concurrently=concurrently), params=None) /usr/local/lib/python3.9/site-packages/django/db/backends/base/schema.py:145: in execute cursor.execute(sql, params) /usr/local/lib/python3.9/site-packages/django/db/backends/utils.py:66: in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) /usr/local/lib/python3.9/site-packages/django/db/backends/utils.py:75: in _execute_with_wrappers return executor(sql, params, many, context) /usr/local/lib/python3.9/site-packages/django/db/backends/utils.py:84: in _execute return self.cursor.execute(sql, params) /usr/local/lib/python3.9/site-packages/django/db/utils.py:90: in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <django.db.backends.utils.CursorWrapper object at 0xffff7244dbb0> sql = 'CREATE INDEX "bank_name_gin_idx" ON "financing_graincreditagrobankworksheet" USING gin ("bank_name" gin_trgm_ops)', params = None ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0xffff7d096b80>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0xffff7244dbb0>}) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: # params default might be backend specific. > return self.cursor.execute(sql) E django.db.utils.ProgrammingError: operator class "gin_trgm_ops" does not exist for access method "gin" /usr/local/lib/python3.9/site-packages/django/db/backends/utils.py:82: ProgrammingError ``` I want to run tests with pytest and got this problem which is actually not causing any problem while project is running, gin index is actually working. But only when I run a test no matter its django's `manage.py test` or `pytest` it fails with the error above. If I comment out the part of migration which should generate an index it works.
operator class "gin_trgm_ops" does not exist for access method "gin"
|django|indexing|pytest|pytest-django|pg-trgm|
null
I am trying to convert string of mathematical expression to lambda function in C++17. How can I do this type of conversion with function? std::function<void()> str2lambda(const std::string& str) { // Conversion // return lambda function } Example: > Input Mathematical function: > "x^2+1" > > Output Lambda Function: > `auto func = [](float x) -> float { return pow(x, 2) + 1; }; `
what's the meaning of new_image[new_image] in this image img in index what does it mean? and specify what img in index returns my image in this is gray scale [img](https://i.stack.imgur.com/umMGp.png)
null
sorry for maybe the stupid question but can't wrap my head around this one. I want to create a smooth linear plot or a histogram, for my 8 samples looking at the distribution of length of their gene transcription (x axis), and how frequently this length appears in each of the samples (y). I've binned the log10 of my gene lengths, but then I'm stuck. I cant plot a histogram as then it just says they're all the same (all the genes appear in all of the samples), and I'm not sure how to include the expression value for the experiments in this. Any suggestions would be appreciated! Example of dataframe ``` Gene.ID Length ND_R1 ND_R2 NP_R1 NP_R2 dD_R1 dD_R2 dP_R1 dP_R2 log10_length log10_length_bin 1 ENSG00000273901 7999 44 48 122 15 79 61 74 107 3.903036 1 2 ENSG00000165392 23499 1246 1851 1065 106 1755 1787 1291 2169 4.371049 3 3 ENSG00000110172 44999 646 969 945 68 1252 1278 1515 2566 4.653203 4 4 ENSG00000148498 9499 21 33 49 3 135 139 113 202 3.977678 1 5 ENSG00000123473 11499 271 460 381 35 585 560 512 892 4.060660 2 6 ENSG00000081721 229335 4461 6963 6068 467 6211 6198 5674 9733 5.360470 7 ``` ``` df <- mutate(df, log10_length_bin = cut(log10_length, breaks = seq(3.75, 5.5, by = 0.25), labels = FALSE)) df <- filter(df, log10_length >= 3.75 & log10_length <= 5.5) df_long <- tidyr::pivot_longer(df, cols = starts_with(c("ND_", "dD_", "NP_", "dP_")), names_to = "Sample", values_to = "Expression") counts <- df_long %>% group_by(Sample, log10_length_bin) %>% summarise(Count = n(), .groups = "drop") ggplot(df, aes(x = log10_length)) + geom_histogram(binwidth = 0.1, aes(fill = ND_R1), position = "dodge") + labs(x = "Log10 of DoG Length", y = "Frequency", title = "Distribution of Log10 DoG Lengths") + scale_fill_discrete(name = "Sample") + theme_minimal() ```
Excel - Visual Basic, macro with autofill "1"
|excel|vba|
null
Since version 1.17 go no longer loads the entire module graph, but, with the introduced concept of pruned graph, only a part of it. A pruned graph can be viewed using `go mod graph`. However, when I want to see the selected module version within that pruned graph using `go list -m all`, it traverses the entire graph and prints the selected versions for all modules (including the ones that are not part of the pruned graph). Is there a way to get/print selected versions **only for the modules inside (within) the pruned graph**? Any go command/tool. Thank you!
Is there a way to get a list of selected module versions, but only for modules within the pruned graph?
|go|
The list you shared as output is not valid as list cannot be a key value pair. Did you mean this - a dict of dicts? { 1: { "B4": 14, "B5": 12 }, 2: { "B4": 58, "B5": 54 }, } To get that - import json with open("file/path.json") as file: data = json.load(file) # Output a list of dict dict_with_index = dict(zip(range(1,len(data) + 1), data))
You terminate a process by calling [`TerminateProcess()`](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-terminateprocess). Doing so will terminate the target process if the caller holds sufficient privileges. This works for any process, not just child processes. But before you go there, you first need to understand how [`CreateProcessW()`](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw) works. The documentation explains the semantics in detail. The return value, in particular, differs from what the code in question assumes.
Client-side caching is usually done in memory for speed. If your data can't fit in memory, then you'll need to write it to the local drive or send it to the back-end. Since the local file storage is unavailable in the Unity3D Web Player, you'll have to either send it to some sort of back-end or develop and in-memory store by hand.
I'm using the code example by [David Hamrick][1] to monitor a file using GCD. int fildes = open("/path/to/config.plist", O_RDONLY); dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE,fildes, DISPATCH_VNODE_DELETE | DISPATCH_VNODE_WRITE | DISPATCH_VNODE_EXTEND | DISPATCH_VNODE_ATTRIB | DISPATCH_VNODE_LINK | DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE, queue); dispatch_source_set_event_handler(source, ^ { //Reload the config file }); dispatch_source_set_cancel_handler(source, ^ { //Handle the cancel }); dispatch_resume(source); [1]: https://web.archive.org/web/20170725014550/http://www.davidhamrick.com/2011/10/10/handling-filesystem-events-with-gcd.html I want to use to monitor a change of a plist. I get a notification after the first change but not for the following changes. Why?
Background service not starting after device restart in Android
|java|android|broadcastreceiver|android-reboot|
null
I recommend using `usePathname` in `next/navigation`.
I have a page similar to this: File: `[pid].tsx` type ProblemPageProps = { problem: Problem }; const ProblemPage:React.FC<ProblemPageProps> = ({problem}) => { ... return ( <div> <Workspace problem={problem} /> </div> ); } export default ProblemPage; export async function getStaticPaths() { const paths = Object.keys(problems).map((key) => ({ params: {pid:key} })) return { paths, fallback: false } } export async function getStaticProps({params}: {params: {pid: string}}) { const {pid} = params; const problem = problems[pid]; if (!problem) { return { notFound: true } } return { props: { problem } } } In `Workspace` I have something like this - gets triggered on a click of a button: const handleCodeReset = () => { setUserCode(problem.starterCode); }; And I have one function to push to the **same** `[pid].tsx` page but with a different PID: const handlePreviousProblemChange = () => { router.push(`/problems/my_second_problem`); } Being triggered by: <div onClick={() => handlePreviousProblemChange()}> BLA BLA BLA </div> When that happens, `problem` is pointing to `my_second_problem` which is exactly what I need but during `onClick` event, `problem.starterCode` still points to the previous `pid`. What can I do to make sure `problem.startedCode` gets referenced in the right way?
Next.js not updating state on OnClick after router.push
|typescript|next.js|
I tried to simplify your code, and ended up with: import vobject s = 'BEGIN:VCARD\r\nFN:John Smith\r\nN:Smith;John;;;\r\nEND:VCARD' vobj = vobject.readOne(s) vobj.add('bday') vobj.prettyPrint() vobj.bday.value = '1931-02-10' vobj.prettyPrint() which produced: > python test.py VCARD FN: John Smith N: John Smith BDAY: VCARD FN: John Smith N: John Smith BDAY: 1931-02-10 > which seems to be what was expected. **Question 1** There's not generally a need for arbitrary names in vObjects, because the specifications dictate what values are required, and they're all handled by the *vobject* code. A common pattern when adding a value is to save a reference to the added attribute, and access it directly, like: notes = vobj.add("NOTES") notes.value = "The content of my notes" or, just do it inline: vobj.add("NOTES").value = "Notes in one line" Or you can access it directly: vobj.notes.value = "New notes content" **Question 2** The problem here is nothing to do with *vobject*, but rather with Python. In Python, `eval` only works for *expressions*. To dynamically compile and execute a *statement* (like your `stmnt2`), you need to use `exec`. If you change eval(stmnt2) to exec(stmnt2) your example code sets the BDAY property without an exception. See https://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile for a full explanation. **Question 3** Yes, it matters. The type of values of the various attributes of a vObject are determined by the specifications. Some have a single value, others are (optionally) a set of values. *vobject* doesn't enforce this, currently.
Getting those warnings are completely fine, if you still want to remove it than install [PostCSS Language Support][1] plugin for VSCode [1]: https://marketplace.visualstudio.com/items?itemName=csstools.postcss
There are multiple mistakes in your attempt… Try the following for small screen devices *(I have used a random color that you will replace with the right desired one)*: ``` css /* For larger screens (first) */ .woocommerce-info { background-color: #000000 !important; } /* For smaller screens (after) */ @media screen and (max-width: 782px) { .woocommerce-info { background-color: #AA00B6 !important; } } ``` Code goes in *style.css* file of your active child theme (or active theme). Tested and works. You may try without `!important`, to see if it works... On small screen devices, you will get something like: [![enter image description here][1]][1] On larger screen devices, you will get the default behavior like: [![enter image description here][2]][2] ------- In some cases, you may insert those CSS rules after all existing ones using: ```php add_action('wp_head', 'wp_head_custom_css', 99999); function wp_head_custom_css() { ?> <style> /* For larger screens (first) */ .woocommerce-info { background-color: #000000 !important; } /* For smaller screens (after) */ @media screen and (max-width: 782px) { .woocommerce-info { background-color: #AA00B6 !important; } } </style> <?php } ``` Code goes in functions.php file of your active child theme (or active theme). Tested and works. [1]: https://i.stack.imgur.com/euyc3.png [2]: https://i.stack.imgur.com/vu6oB.png
{"Voters":[{"Id":1940850,"DisplayName":"karel"},{"Id":269970,"DisplayName":"esqew"},{"Id":1599751,"DisplayName":"PeterJ"}]}
I created a short python application in a Google Colab notebook, that works fine. I am trying to move the application from Google Colab into a local Docker-Python-Application. But whenever **I run the application with Docker and do in a .py file** ``` from llama_parse import LlamaParse ``` **My application fails with the following error:** ``` pdf-compare-mvp1-web-1 | File "/usr/local/lib/python3.8/site-packages/llama_parse/base.py", line 386, in LlamaParse pdf-compare-mvp1-web-1 | def get_images(self, json_result: list[dict], download_path: str) -> List[dict]: pdf-compare-mvp1-web-1 | TypeError: 'type' object is not subscriptable ``` **here is the functional notebook code** ``` !pip install -q llama-index !pip install -q openai !pip install -q transformers !pip install -q accelerate import os os.environ["OPENAI_API_KEY"] = "..." from IPython.display import Markdown, display from llama_index.llms.openai import OpenAI from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_parse import LlamaParse parser = LlamaParse( api_key="...", result_type="markdown" ) document1 = await parser.aload_data("data/some.pdf") # some more code ``` **Following the not working local Docker application:** To build and run the application locally on my machine, I created Python flask app with the following relevant files: **Dockerfile** ``` # Use an official Python runtime as a parent image FROM python:3.8-slim # Set the working directory in the container WORKDIR /app # Copy the current directory contents into the container at /app COPY . /app # Install any needed packages specified in requirements.txt RUN pip install --no-cache-dir -r requirements.txt # Make port 5000 available to the world outside this container EXPOSE 5000 # Define environment variable ENV FLASK_APP=app.py # Run app.py when the container launches CMD ["flask", "run", "--host=0.0.0.0"] ``` **docker-compose.yml** ``` version: '3.8' services: web: build: . volumes: - .:/app ports: - "5002:5000" environment: - FLASK_ENV=development ``` **requirements.txt** ``` Flask==2.1.2 python-dotenv==0.20.0 boto3==1.24.12 Werkzeug==2.2.0 PyMuPDF llama-index openai llama-parse # transformers # accelerate ``` **processor.py** ``` import fitz # PyMuPDF import os from config import Config # from llama_parse import LlamaParse # import nest_asyncio # nest_asyncio.apply() from llama_index.llms.openai import OpenAI from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_parse import LlamaParse ``` The last line from llama_parse import LlamaParse result in the error. **Whenever this line is present/not present, the application is functional/ functional**