Sunday, May 30, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Create non-auth api in VueJs

Posted: 30 May 2021 08:12 AM PDT

I'm working with Vuejs and I have a api like this : /api/gateway/captcha, when I enter in login page, this api is call to get captcha. This api is set unauthenticated, access-token = null in header of api. But when this api is called, 401 Unauthorized error is appearance in console tab. Althought I set acceptUnAuth = true in axios. Please help me explain it? Thanks

VBA code to consolidate data in one row from three rows

Posted: 30 May 2021 08:11 AM PDT

I have access data for all card numbers. Each card number have 3 entries in three rows. But I want data for each card number in one row.

enter image description here

I have tried below code but output have 2 lines blank. enter image description here

Could you please suggest any alternate solution to get correct data in one row for every card number.

Sub ConsolidateData()        For i = 2 To 19            'for first row      Sheet3.Range("A" & i) = Sheet2.Range("A" & i)      Sheet3.Range("B" & i) = Sheet2.Range("B" & i)      Sheet3.Range("C" & i) = Sheet2.Range("C" & i)      Sheet3.Range("D" & i) = Sheet2.Range("D" & i)            'for second row      i = i + 1      Sheet3.Range("E" & i - 1) = Sheet2.Range("B" & i)      Sheet3.Range("F" & i - 1) = Sheet2.Range("C" & i)      Sheet3.Range("G" & i - 1) = Sheet2.Range("D" & i)            'for 3rd row      i = i + 1      Sheet3.Range("H" & i - 2) = Sheet2.Range("B" & i)      Sheet3.Range("I" & i - 2) = Sheet2.Range("C" & i)      Sheet3.Range("J" & i - 2) = Sheet2.Range("D" & i)      Next i      End Sub  

Cut an area of a polygone Boost C++

Posted: 30 May 2021 08:11 AM PDT

I'm trying to cut a part of a boost polygon.

Basically i have a polygon

 boost::geometry::read_wkt("POLYGON((-2 -700,-2 -445,100 -455,100 645,1075 645,1075 -145,1300 -145,1300 -700))", b);  

And i want to cut a part of my polygon.

For example, if i have this kind of polygon (in black), i would like to delete the red part enter image description here

I already tried to do something like that,

  boost::geometry::interior_rings(b).resize(1);    append(b, tuple_list_of(200, 200)(200, 500)(600, 600)(500, 200)(200, 200), 0);  

But one line (or several) of my polygon disappear.

I don't necessarily want to cut part of my polygon, I just want that part to no longer be part of the whole and not be detected by withinbecause i'm using

  Point p(x,y);    bg::within(p, poly)  

And I'd like to put in some unverifiable areas.

If anyone have an idea for this, thanks

exctract the beginning from each line

Posted: 30 May 2021 08:11 AM PDT

i need to cancel or delete any text after jpg word from each line and remove duplicate

the text like this

000000057870.jpg# plapla  000000057870.jpg# plapla  000000057870.jpg# plapla  000000222016.jpg# plapla  000000222016.jpg# plapla  000000057870.jpg# plapla  

to be

000000057870.jpg  000000222016.jpg  000000057870.jpg  

the code i'm trying to do it didn't work well

import os  new=open('new.txt','w')  infile=open('output.txt','r')  for line in infile:       if line=='#':           new_line=line.replace('#','')           new.write(new_line)  

Create shapes on canvas that can resized by dragging the corners and moved by dragging the shape - tkinter

Posted: 30 May 2021 08:10 AM PDT

Is there a way to create shapes on a canvas that can be resized by dragging the corners and moved by dragging the shape I know how to create it on a canvas by using .create_shapename but then I can't assign it to a variable (if I am wrong please correct me)

Thanks!

Neo4j multiple level match query with condition

Posted: 30 May 2021 08:10 AM PDT

the query

match (n)-[:friend*0..3]->(b)  where n.salary >= 19999 and n.address="Paris" and b.salary >= 19999 and b.address="Paris" return distinct n.name order by n.name  

doesn't give me what I want:

I'm trying to display all the names of the persons living in Paris for whom all of their friends for 3 level generations also live in Paris and also have a salary higher than 19999.

The above query doesn't do it well, what am I doing wrong ?

for example: if Buddy lives in Paris, earns +20k and all of his friends for 3 level generations also live in Paris and earn +20k then Buddy should be returned. Else he shouldn't be.

How do i inject ConstrainValidator?

Posted: 30 May 2021 08:10 AM PDT

Imagine i have an annotation A

@Target({TYPE})  @Retention(RUNTIME)  @Documented  @Constraint(validatedBy = {Validator.class})  public @interface A {       String value() default "";       String message() default "{javax.validation.constraints.form.customization.message}";       Class<?>[] groups() default {};       Class<? extends Payload>[] payload() default {};  }    

that has a Constraint Validator which is not an implementation of ConstraintValidator rather an extension of one

public interface Validator extends ConstraintValidator<A, Entity> {  }  

And then some implementation of Validator. Is there any way i can make it work with Spring, dependency injection and all that good stuff? Thank you

How to convert custom type definition file to npm type definition file

Posted: 30 May 2021 08:10 AM PDT

I have a custom module definition file for a dependency written in CoffeeScript in my typescript project.

It looks like the following and works great:

src/@types/dependency-name.d.ts

declare module 'dependency-name' {    import EventEmitter from 'eventemitter3';      /**    * omitted    */      interface ICable {      new (channels: Record<string, ISubscription>): ICable;        channels: Record<string, ISubscription>;        channel: (name: string) => ISubscription | undefined;      setChannel: (name: string, channel: ISubscription) => ISubscription;    }    export const Cable: ICable;  }  

So I want to contribute to this project and submit a type definition file.

What I tried is:

  1. Forked the original CoffeeScript project,
  2. Copied the above definition to index.d.ts
  3. Add the following line to pacakge.json:
"typings": "index.d.ts",  
  1. Installed forked repository in my typescript project for testing.

However, it does not recognize the added index.d.ts file. Shows type definition is missing error.

I've seen this post and guessed that the issue is this one:

be written as external modules

But I don't understand it. Can someone guide me to convert my custom typing (module augmentation, I guess?) to correct type definition file for package.json?

Anonymous array becomes undefined when accessed [duplicate]

Posted: 30 May 2021 08:11 AM PDT

Here's where my problem is:

function applyConfig (conf) {      Running = false        ['points', 'pointsz', 'centroids', 'centroidsz'].forEach(          f => console.log(f))  }  

The real functionality has been stripped and replaced with console.log() to narrow things down. The actual problem is that the line with the anonymous array throws either "Cannot read property 'forEach' of undefined" or "Cannot read property 'centroidsz' of undefined".

I can't reproduce this minimally as the crux is the first line, Running = false. There is an animation loop going (yes, yet another k-means demo) contingent on this condition. The function in question is used in an event callback independent of the animation. If I remove that line, leaving the loop running, this works as expected.

There is a simple "fix" which I don't like because I don't understand why it works where the other does not:

function applyConfig (conf) {      Running = false        let fields = ['points', 'pointsz', 'centroids', 'centroidsz']      fields.forEach(f => console.log(f))  }  

Why does this happen?

Unable to change Cloud scheduler timezone for PubSub Cloud Function deploy via CICD

Posted: 30 May 2021 08:10 AM PDT

Suddenly the timezone for scheduler started falling back to default "America/Los_Angelos" Look at below example from firebase docs (ref: https://firebase.google.com/docs/functions/schedule-functions#write_a_scheduled_function)

exports.scheduledFunctionCrontab = functions.pubsub.schedule('0 11 * * *')    .timeZone('America/New_York') // Users can choose timezone - default is America/Los_Angeles    .onRun((context) => {    console.log('This will be run every day at 11:05 AM Eastern!');    return null;  });  

Unfortunately, the timeZone started failing for all new deployment via our CI pipeline and scheduled jobs started running at 11:00 AM Pacific instead of expected 11:00 AM Eastern time.

Tried updating node in CI Pipeline, firebase-admin in package, but nothing helped...

Delphi - Auto incrementing a Firebird field value when using UPDATE OR INSERT INTO

Posted: 30 May 2021 08:10 AM PDT

I have been a Delphi programmer for 25 years, but managed to avoid SQL until now. I was a dBase expert back in the day. I am using Firebird 3.xx SuperServer as a service on a Windows server 2012 box. I run a UDP listener service written in Delphi 2007 to receive status info from a software product we publish.

The FB database is fairly simple. I use the users IP address as the primary key and record reports as they come in. I am currently getting about 150,000 reports a day and they are logged in a txt file.

Rather than insert every report into a table, I would like to increment an integer value in a single record with a "running total" of reports received from each IP address. It would save a LOT of data.

The table has fields for IP address (Primary Key), LastSeen (timestamp), and Hits (integer). There are a few other fields but they aren't important.

I use UPDATE OR INSERT INTO when the report is received. If the IP address does not exist, a new row is inserted. If it does exist, then the the record is updated.

I would like it to increment the "Hits" field by +1 every time I receive a report. In other words, if "Hits" already = 1, then I want to inc(Hits) on UPDATE to 2. And so on. Basically the "Hits" field would be a running total of the number of times an IP address sends a report.

Adding 3 million rows a month just so I can get a COUNT for a specific IP address does not seem efficient at all!

Is there a way to do this?

Thanks,

Brian

Url Xml Parsing In c#

Posted: 30 May 2021 08:10 AM PDT

i want to get a data from a xml site but i want spesific data i want to get USD/TRY, GBP/TRY and EUR/TRY Forex Buying values i dont know how to split those values from the data i have a test console program and the is like this

using System;  using System.Xml;    namespace ConsoleApp1  {      class Program      {          static void Main(string[] args)          {              string XmlUrl = "https://www.tcmb.gov.tr/kurlar/today.xml";              XmlTextReader reader = new XmlTextReader(XmlUrl);              while (reader.Read())              {                  switch (reader.NodeType)                  {                      case XmlNodeType.Element: // The node is an element.                          Console.Write("<" + reader.Name);                            while (reader.MoveToNextAttribute()) // Read the attributes.                              Console.Write(" " + reader.Name + "='" + reader.Value + "'");                          Console.Write(">");                          Console.WriteLine(">");                          break;                      case XmlNodeType.Text: //Display the text in each element.                          Console.WriteLine(reader.Value);                          break;                      case XmlNodeType.EndElement: //Display the end of the element.                          Console.Write("</" + reader.Name);                          Console.WriteLine(">");                          break;                  }              }            }      }  }  

how can i split the values from i want from the xml

I have an error with my TCP nodejs server

Posted: 30 May 2021 08:09 AM PDT

I wanna make an tcp server with nodejs . When i start the server in the terminal it says nothing, and when i start the client the client gets the message but in the server terminal, it prints:

var net = require('net');    var client = new net.Socket();  client.connect(1337, '127.0.0.1', function() {      console.log('Connected');      client.write('Hello, server! Love, Client.');  });    client.on('data', function(data) {      console.log('Received: ' + data);      client.destroy(); // kill client after server's response  });    client.on('close', function() {      console.log('Connection closed');  });  

When i start the client again, the server is still running, i needed to stop the server using killall node. How can i fix this error.

Server:

var net = require('net');    var server = net.createServer(function(socket) {      socket.write('Connected to server !\r\n');      socket.pipe(socket);  });    server.listen(1337, '127.0.0.1');  

Client:

var net = require('net');    var client = new net.Socket();  client.connect(1337, '127.0.0.1', function() {      console.log('Connected');      client.write('Hello, server! Love, Client.');  });    client.on('data', function(data) {      console.log('Received: ' + data);      client.destroy(); // kill client after server's response  });    client.on('close', function() {      console.log('Connection closed');  });  

how to make program for finding greatest number out of n given number using if else in c

Posted: 30 May 2021 08:11 AM PDT

I want to know that how can we make a program for finding greatest number out of n given numbers using if else statement

Getting error While streaming Data from On-prem cassandra cluster to AWS (version:2.1.19)

Posted: 30 May 2021 08:11 AM PDT

I am getting below error while trying to do a rebuild of the source DC on the target DC. I want to replicate source data to target in AWS. Kindly help.

INFO [MemtableFlushWriter:5] 2021-05-29 20:19:40,664 Memtable.java:382 - Completed flushing /data/system_auth/users-473588ad9c7938be8b59e06c10456ba0/system_auth-users-tmp-ka-1-Data.db (0.000KiB) for commitlog position ReplayPosition(segmentId=1622318449434, position=9380187) INFO [STREAM-IN-/10.0.31.101] 2021-05-29 20:19:40,679 StreamResultFuture.java:181 - [Stream #327c5b00-c0bb-11eb-aa90-bb6530dd5190] Session with /10.0.31.101 is complete INFO [STREAM-IN-/10.0.31.101] 2021-05-29 20:19:40,681 StreamResultFuture.java:213 - [Stream #327c5b00-c0bb-11eb-aa90-bb6530dd5190] All sessions completed INFO [HANDSHAKE-/10.0.31.101] 2021-05-29 20:20:37,126 OutboundTcpConnection.java:496 - Handshaking version with /10.0.31.101 INFO [CompactionExecutor:4] 2021-05-29 20:20:50,217 CompactionTask.java:141 - Compacting [SSTableReader(path='/data/system/hints-2666e20573ef38b390fefecf96e8f0c7/system-hints-ka-2-Data.db')] INFO [RMI TCP Connection(36)-127.0.0.1] 2021-05-29 20:21:27,805 StorageService.java:1052 - rebuild from dc: DC1 INFO [RMI TCP Connection(36)-127.0.0.1] 2021-05-29 20:21:28,131 StreamResultFuture.java:87 - [Stream #728af9e0-c0bb-11eb-9dde-0d382aaf9f86] Executing streaming plan for Rebuild INFO [StreamConnectionEstablisher:1] 2021-05-29 20:21:28,132 StreamSession.java:224 - [Stream #728af9e0-c0bb-11eb-9dde-0d382aaf9f86] Starting streaming to /172.0.0.147 INFO [StreamConnectionEstablisher:1] 2021-05-29 20:21:28,134 StreamCoordinator.java:209 - [Stream #728af9e0-c0bb-11eb-9dde-0d382aaf9f86, ID#0] Beginning stream session with /172.0.0.147 INFO [STREAM-IN-/172.0.0.147] 2021-05-29 20:21:28,353 StreamResultFuture.java:167 - [Stream #728af9e0-c0bb-11eb-9dde-0d382aaf9f86 ID#0] Prepare completed. Receiving 15 files(85742295230 bytes), sending 0 files(0 bytes) ERROR [STREAM-IN-/172.0.0.147] 2021-05-29 20:26:18,026 StreamSession.java:512 - [Stream #728af9e0-c0bb-11eb-9dde-0d382aaf9f86] Streaming error occurred java.io.EOFException: null at java.io.DataInputStream.readInt(DataInputStream.java:392) ~[na:1.7.0_151] at org.apache.cassandra.streaming.compress.CompressionInfo$CompressionInfoSerializer.deserialize(CompressionInfo.java:68) ~[apache-cassandra-2.1.19.jar:2.1.19] at org.apache.cassandra.streaming.compress.CompressionInfo$CompressionInfoSerializer.deserialize(CompressionInfo.java:47) ~[apache-cassandra-2.1.19.jar:2.1.19] at org.apache.cassandra.streaming.messages.FileMessageHeader$FileMessageHeaderSerializer.deserialize(FileMessageHeader.java:188) ~[apache-cassandra-2.1.19.jar:2.1.19] at org.apache.cassandra.streaming.messages.IncomingFileMessage$1.deserialize(IncomingFileMessage.java:42) ~[apache-cassandra-2.1.19.jar:2.1.19] at org.apache.cassandra.streaming.messages.IncomingFileMessage$1.deserialize(IncomingFileMessage.java:38) ~[apache-cassandra-2.1.19.jar:2.1.19] at org.apache.cassandra.streaming.messages.StreamMessage.deserialize(StreamMessage.java:56) ~[apache-cassandra-2.1.19.jar:2.1.19] at org.apache.cassandra.streaming.ConnectionHandler$IncomingMessageHandler.run(ConnectionHandler.java:276) ~[apache-cassandra-2.1.19.jar:2.1.19] at java.lang.Thread.run(Thread.java:748) [na:1.7.0_151] INFO [STREAM-IN-/172.0.0.147] 2021-05-29 20:26:18,202 StreamResultFuture.java:181 - [Stream #728af9e0-c0bb-11eb-9dde-0d382aaf9f86] Session with /172.0.0.147 is complete WARN [STREAM-IN-/172.0.0.147] 2021-05-29 20:26:18,203 StreamResultFuture.java:208 - [Stream #728af9e0-c0bb-11eb-9dde-0d382aaf9f86] Stream failed ERROR [RMI TCP Connection(36)-127.0.0.1] 2021-05-29 20:26:18,203 StorageService.java:1075 - Error while rebuilding node org.apache.cassandra.streaming.StreamException: Stream failed at org.apache.cassandra.streaming.management.StreamEventJMXNotifier.onFailure(StreamEventJMXNotifier.java:85) ~[apache-cassandra-2.1.19.jar:2.1.19] at com.google.common.util.concurrent.Futures$4.run(Futures.java:1172) ~[guava-16.0.jar:na] at com.google.common.util.concurrent.MoreExecutors$SameThreadExecutorService.execute(MoreExecutors.java:297) ~[guava-16.0.jar:na] at com.google.common.util.concurrent.ExecutionList.executeListener(ExecutionList.java:156) ~[guava-16.0.jar:na] at com.google.common.util.concurrent.ExecutionList.execute(ExecutionList.java:145) ~[guava-16.0.jar:na] at com.google.common.util.concurrent.AbstractFuture.setException(AbstractFuture.java:202) ~[guava-16.0.jar:na] at org.apache.cassandra.streaming.StreamResultFuture.maybeComplete(StreamResultFuture.java:209) ~[apache-cassandra-2.1.19.jar:2.1.19] at org.apache.cassandra.streaming.StreamResultFuture.handleSessionComplete(StreamResultFuture.java:185) ~[apache-cassandra-2.1.19.jar:2.1.19] at org.apache.cassandra.streaming.StreamSession.closeSession(StreamSession.java:413) ~[apache-cassandra-2.1.19.jar:2.1.19] at org.apache.cassandra.streaming.StreamSession.onError(StreamSession.java:518) ~[apache-cassandra-2.1.19.jar:2.1.19] at org.apache.cassandra.streaming.ConnectionHandler$IncomingMessageHandler.run(ConnectionHandler.java:294) ~[apache-cassandra-2.1.19.jar:2.1.19] at java.lang.Thread.run(Thread.java:748) ~[na:1.7.0_151]

This is my nodetool status

root@e7816844afae:/bin# nodetool status

Datacenter: DC1

Status=Up/Down |/ State=Normal/Leaving/Joining/Moving -- Address Load Tokens Owns (effective) Host ID Rack UN 172.0.0.147 80.31 GB 256 100.0% 38f37d99-496b-4316-bca7-b10a1f161904 RAC1 UN 172.0.0.161 80.45 GB 256 100.0% cfb05b5a-fcbe-4686-873a-be7aaa840784 RAC1 UN 172.0.0.234 80.38 GB 256 100.0% 2b2a5739-df20-4083-8fd0-ab9de8a228c9 RAC1

Datacenter: DC3

Status=Up/Down |/ State=Normal/Leaving/Joining/Moving -- Address Load Tokens Owns (effective) Host ID Rack UN 10.0.3.61 123.34 KB 256 100.0% 1b3299a7-3003-4c98-bd0d-ce2ef8666edc RAC1 UN 10.0.31.101 109.36 KB 256 100.0% d0fb8a71-a38e-4449-b6f4-2ff7448fb263 RAC1 UN 10.0.30.118 160.96 KB 256 100.0% ebe0f32c-9d72-4327-9fc1-bd9a2c7b1b82 RAC1

[root@ip-172-0-0-234 bin]# ./nodetool describecluster Cluster Information: Name: Nagra Default Snitch: org.apache.cassandra.locator.DynamicEndpointSnitch Partitioner: org.apache.cassandra.dht.Murmur3Partitioner Schema versions: 0850c5dc-99c9-3770-9c7c-d23e19d194b6: [172.0.0.147, 172.0.0.161, 10.0.3.61, 10.0.31.101, 10.0.30.118, 172.0.0.234]

cassandra@cqlsh> select * from system.schema_keyspaces;

keyspace_name | durable_writes | strategy_class | strategy_options ---------------------+----------------+------------------------------------------------------+----------------------- user_activity_vault | True | org.apache.cassandra.locator.NetworkTopologyStrategy | {"DC1":"3","DC3":"3"} system_auth | True | org.apache.cassandra.locator.NetworkTopologyStrategy | {"DC1":"3","DC3":"3"} system | True | org.apache.cassandra.locator.LocalStrategy | {} system_traces | True | org.apache.cassandra.locator.NetworkTopologyStrategy | {"DC1":"3","DC3":"3"}

Any help and suggestions to resolve this is highly appreciated

Thanks, Gargee

Why does Rider add an "@" to my public variable?

Posted: 30 May 2021 08:10 AM PDT

I've declared a class like this:

public class Cell : IEquatable<Cell>  {      public int id { get; }      public SetOfCells group;  }  

And each time I want to use group, Rider adds and @ before, like this:

foreach (Cell cell in c1.@group) {      /* blabla */  }  

Precision: c1.@group and c1.group both works. Why is that?

(if you can tell me the right words to google to find a valuable answer I'm interested, because I couldn't find one: "csharp property +"@" doesn't help...")

How to convert EventRecord xml to dictionary includes all parameters - C#

Posted: 30 May 2021 08:11 AM PDT

I have the following xml which include windows event:

<?xml version="1.0"?> -  <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">    <System>      <Provider Name="LMS" />      <EventID Qualifiers="32768">2125</EventID>      <Level>4</Level>      <Task>3</Task>      <Keywords>0x80000000000000</Keywords>      <TimeCreated SystemTime="2021-05-30T14:05:07.077547800Z" />      <EventRecordID>89958</EventRecordID>      <Channel>Application</Channel>      <Computer></Computer>      <Security/>    </System>    <EventData>      <Data> </Data>    </EventData>  </Event>

I wand to convert this XML to dictionary in c#, it's work fine but the problem is that in the "provider Name" and "timeCreated" properties I'm receiving null.

Any idea how can I get the values like: "LMS" and "2021-05-30T14:05:07.077547800Z" ?

Here is the code to converting the XML to dictionary:

var xmlFile = File.ReadAllText(log);  XDocument doc = XDocument.Parse(xmlFile);  Dictionary<string, string > dataDictionary = new Dictionary <string, string >();  foreach(XElement element in doc.Descendants().Where(p => p.HasElements ==false))   {    int keyInt = 0;    string keyName = element.Name.LocalName;    while (dataDictionary.ContainsKey(keyName))    {      keyName = element.Name.LocalName + "_" + keyInt++;    }    dataDictionary.Add(keyName,      element.Value);  }

Replace part of url and loop trough all the pages

Posted: 30 May 2021 08:11 AM PDT

I am working on a script to scrape some pages of my online supermarket. Each page has its own number The url is as follows

https://www.jumbo.com/INTERSHOP/web/WFS/Jumbo-Grocery-Site/nl_NL/-/EUR/ViewOrderHistory-Paging?StatusType=Complete&PageNumber=1&PageableID=5DIKY7MVn2IAAAF5QrIGubww  

The part where the page number is located is Complete&PageNumber=1&PageableID where 1 is the pagenumber. I would like the to go trough al the pages up to page thirteen (I have the max pagenumver stored in a variable PageNo)

I have been messing around with this part of code nested inside a replace function but I can't get the pieces together. The part of code below gives me the pagenumber.

s = url  pattern = "=Complete&PageNumber=(.*?)&PageableID="  substring = re.search(pattern, s).group(1)  print(substring)  

I also been googling around for a bit of time but unfortunately without the desired result...Can you guys help me out again? Thank you very much in advance!

How to show word cloud on map popup using leaflet in r

Posted: 30 May 2021 08:12 AM PDT

I am trying to plot the word cloud of sub-categories of that state in popup window when user clicks on that state in map.

ui <- bootstrapPage(       leafletOutput("mymap", height = 300)    )    server <- function(input, output, session){  output$mymap <- renderLeaflet({      leaflet(Sales) %>%            addTiles() %>%            addCircles(lng = ~longitude, lat = ~latitude,                       popup= popupGraph(p),                       weight = 3,                       radius = ~Sales,                       color=~cof(newdata$Category), stroke = TRUE, fillOpacity = 0.8)) )      })    shinyApp(ui = ui, server = server)  

Here is my leaflet code, I have used it in r shiny. Can anyone please suggest how i render wordcloud on popup when user clicks on a state on map?

Auto submit form on page reload

Posted: 30 May 2021 08:11 AM PDT

I have tried a few different ways, but none seem to work for me. I will enter the methods I have tried after I explain a little. I have a form with the id of 'commentform', I would like to auto submit the users input when the page reloads and the user did not click the submit button. The submit button has a id of 'submit'. The textarea field of the form is 'comment' (I don't think that would be relevant.

Attempt 1: Results: Auto reloads page on visit and gives error to fill in text form.

<script type="text/javascript">  jQuery(window).on('load', function() {  jQuery('#submit').click();  });  </script>  

Attempt 2: Results: Nothing happens.

<script type="text/javascript">      window.onbeforeunload = function () {      jQuery('#submit').click();      });      </script>  

Attempt 3: Results: Nothing happens.

<script type="text/javascript">      window.onload = function () {      jQuery('#commentform').click();      });      </script>  

Attempt 4: Results: Nothing happens.

<script type="text/javascript">      jQuery(window).on('beforeunload', function() {      jQuery('#commentform').click();      });      </script>  

Attempt 5: Results: Nothing happens.

<body onbeforeunload ='checkRequest(event)'>  //form is here  <script type="text/javascript">              function checkRequest(event){                  var __type= event.currentTarget.performance.navigation.type;                  if(__type === 1 || __type === 0){                      document.getElementById('commentform').submit();                  }              }          </script>  </body>  

Attempt 6: Results: Nothing

<script type="text/javascript">          window.onbeforeunload = refreshCode;  function refreshCode(){     document.getElementById("commentform").submit();     return null;  }          </script>  

Attempt 7: Results: Nothing

<script type="text/javascript">          window.onload = function(){    document.forms['commentform'].submit();  }          </script>  

Importing fastai in GoogleColab

Posted: 30 May 2021 08:11 AM PDT

I am trying to import this module in googlecolab for my code. As I want to run my code with GPU but even when I do pip install fastai or pip3 intall fastai , it says requirement satisfied but gives me error when I run these:

from fastai.vision.all import *  import gc     ModuleNotFoundError: No module named 'fastai.vision.all'  

Docker-Swarm, a problem that does not work when deploying with multiple labels in a distributed environment

Posted: 30 May 2021 08:10 AM PDT

Set up two servers, one as a manager node and one as a worker node.

The worker node is labeled role_1=true .

The manager node is labeled role_2, role_3.

$ docker node update --label-add role_1=true node_1  node_1    $ docker node update --label-add role_2=true node_2  node_2    $ docker node update --label-add role_3=true node_2  node_2    $ docker node inspect node_1 --pretty  ID:                     rdnmlf1m0ge  Labels:   - role_1=true    $ docker node inspect node_2 --pretty  ID:                     td1cq8oxxrk2a  Labels:   - role_2=true   - role_3=true    

The main.go file, Dockerfile is:

main.go

package main    import (          "net/http"  )    func main() {          http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {                  w.Write([]byte("Hello World!"))          })            err := http.ListenAndServe(":8080", nil)          if err != nil {                  return          }  }    

dockerfile

FROM golang:latest    ENV GO111MODULE=off    WORKDIR /go/src/app  COPY . /go/src/app    RUN go build -o simple_program    ENTRYPOINT ["/go/src/app/simple_program"]    

Write docker-compose file as below. Add only the label of the manager node to constraints .

version: '3.7'    services:    api_server:      image: simple_program      deploy:        mode: global        placement:          constraints:            - node.labels.role_2 == true            - node.labels.role_3 == true      ports:        - 8080:8080    

It works as expected.

$ docker stack deploy --compose-file docker-compose.yml simple_http_server  Creating network simple_http_server_default  Creating service simple_http_server_api_server    $ docker service ls  ID                 NAME                                MODE      REPLICAS   IMAGE                      PORTS  2vksfee0e4ef   simple_http_server_api_server   global        1/1         simple_program:latest   *:8080->8080/tcp    

If it is distributed to both the manager node and the worker node or distributed only to the worker node, the service does not come up.

version: '3.7'    services:    api_server:      image: simple_program      deploy:        mode: global        placement:          constraints:            - node.labels.role_1 == true            - node.labels.role_3 == true      ports:        - 8080:8080    
$ docker service ls  ID                  NAME                               MODE      REPLICAS   IMAGE                       PORTS  rhto667wd9lb   simple_http_server_api_server   global       0/0         simple_program:latest   *:8080->8080/tcp    

Nothing shows up in service logs either.

$ docker service ps --no-trunc simple_http_server_api_server  ID        NAME      IMAGE     NODE      DESIRED STATE   CURRENT STATE   ERROR     PORTS    $ docker service logs simple_http_server_api_server  $    

I read the stackoverflow questions and answers below, but it didn't help.

Multiple label placement constraints in docker swarm

How to show child table in Django REST Framework API view

Posted: 30 May 2021 08:10 AM PDT

I'm using Django as Backend, PostgresSQl as DB and HTML, CSS and Javascript as Frontend. I want to show Children Table in DJANGO REST FRAMEWORK, as I'm using Multi Table Inheritance. enter image description here

As we can see in above image, that only Product list is been displayed but not the children table. I want to show all the data which is selected by customer. I'm showing Cart Product in DRF

views.py

class AddToCartView(TemplateView):      template_name = "status.html"        def get_context_data(self, **kwargs):          context = super().get_context_data(**kwargs)          product_id = self.kwargs['pk']          product_obj = Product.objects.get(id = product_id)          cart_id = self.request.session.get("cart_id", None)          if cart_id:              cart_obj = Cart.objects.get(id = cart_id)              this_product_in_cart = cart_obj.cartproduct_set.filter(product = product_obj)                        if this_product_in_cart.exists():                  cartproduct = this_product_in_cart.last()                  cartproduct.quantity += 1                  cartproduct.subtotal += product_obj.price                  cartproduct.save()                  cart_obj.total += product_obj.price                  cart_obj.save()              else:                  cartproduct = CartProduct.objects.create(                      cart = cart_obj, product = product_obj, rate = product_obj.price, quantity = 1, subtotal = product_obj.price)                  cart_obj.total += product_obj.price                  cart_obj.save()           else:              cart_obj = Cart.objects.create(total=0)              self.request.session['cart_id'] = cart_obj.id              cartproduct = CartProduct.objects.create(                  cart = cart_obj, product = product_obj, rate = product_obj.price, quantity = 1, subtotal = product_obj.price)              cart_obj.total += product_obj.price              cart_obj.save()            return context  

API View (views.py)

@api_view(['GET'])  def showproduct(request):      result = CartProduct.objects.all()      serialize = productserializers(result, many = True)      return Response(serialize.data)  

models.py

class Product(models.Model):      name = models.CharField(max_length=1330)      image_src = models.URLField(max_length=1330,null=True, blank=True)      link_href = models.URLField(max_length=1330,null=True, blank=True)      brand = models.CharField(max_length = 1330, null=True, blank=True)      price = models.DecimalField(max_digits=15, decimal_places=2)      created = models.DateTimeField(auto_now_add=True)        class Meta:          ordering = ('-created',)      class Refrigerator(Product):      series = models.CharField(max_length = 300, null=True, blank=True)      model = models.CharField(max_length = 300, null=True, blank=True)      ...    class Cart(models.Model):      customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)      total = models.PositiveIntegerField(default=0)      created_at = models.DateTimeField(auto_now_add=True)        def __str__(self):          return "Cart: " + str(self.id)      class CartProduct(models.Model):      cart = models.ForeignKey(Cart, on_delete=models.CASCADE)      product = models.ForeignKey(Product, on_delete=models.CASCADE)      rate = models.PositiveIntegerField()      quantity = models.PositiveIntegerField()      subtotal = models.PositiveIntegerField()        def __str__(self):          return "Cart: " + str(self.cart.id) + " CartProduct: " + str(self.id)  

I want to show refrigerator details aslo in DRF which is been selected by customer.

serializer.py

class productserializers(serializers.ModelSerializer):      class Meta:          model = CartProduct          fields = "__all__"          depth = 2  

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte in Socket Programming

Posted: 30 May 2021 08:12 AM PDT

Hello so I've been doing a Python Socket Programming. What I want to do is send a string variable called "option" to server.

This is the Client code

option = "4"  client.send(option.encode())  

I got the 'error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte'.

So here is my server code.

option = client.recv(512).decode()  

The option in server should received a String that has a value as "4" but like I said I got an error. Could anyone know how to solve this ? Thanks in advance.

Initializing a pydantic dataclass from json

Posted: 30 May 2021 08:11 AM PDT

I'm in the process of converting existing dataclasses in my project to pydantic-dataclasses, I'm using these dataclasses to represent models I need to both encode-to and parse-from json.

Here's an example of my current approach that is not good enough for my use case, I have a class A that I want to both convert into a dict (to later be converted written as json) and to read from that dict. But the only way I can find to parse the json back into a model gives me back the underlying BaseModel and not the dataclass.

note that I'm using the asdict function to convert the dataclass to a dict as it's what the pydantic_encoder uses to convert the dataclass to json, and using the pydantic_encoder what the documentation recommends to convert a pydantic-dataclass to json: https://pydantic-docs.helpmanual.io/usage/dataclasses/

from dataclasses import asdict  from pydantic.dataclasses import dataclass  from pydantic import BaseModel    @dataclass  class A:      x: str    a = A("string")  a_dict = asdict(a)  parsed_a = A.__pydantic_model__.parse_obj(a_dict)    print(f"type of a: {type(a)}")  print(f"type of parsed_a: {type(parsed_a)}")    print(f"a is instance of A: {isinstance(a, A)}")  print(f"parsed_a is instance of A: {isinstance(parsed_a, A)}")    print(f"a is instance of BaseModel: {isinstance(a, BaseModel)}")  print(f"parsed_a is instance of BaseModel: {isinstance(parsed_a, BaseModel)}")  

output:

type of a: <class '__main__.A'>  type of parsed_a: <class '__main__.A'>  a is instance of A: True  parsed_a is instance of A: False  a is instance of BaseModel: False  parsed_a is instance of BaseModel: True  

Is there maybe a way to initialize A from the parsed BaseModel?

How to use cakephp 2 with custom database connection and raw queries

Posted: 30 May 2021 08:10 AM PDT

I have to work with an Oracle database using the old database driver (ora_logon ) which is not supported by cakephp. I cant use the oci driver instead.

Right now I do the follow: Every method of every model connects to the database and retrieve data

class SomeClass extends Model {      public function getA(){          if ($conn=ora_logon("username","password"){              //make the query              // retrieve data              //put data in array and return the array          }      }        public function getB(){          if ($conn=ora_logon("username","password"){              //make the query              // retrieve data              //put data in array and return the array          }      }  }  

I know that it is not the best way go. How could I leave cakephp manage opening and closing of the connection to the database and have models only retrieve data? I'm not interested in any database abstraction layer.

Difference between := and = operators in Go

Posted: 30 May 2021 08:10 AM PDT

What is the difference between the = and := operators, and what are the use cases for them? They both seem to be for an assignment?

Timezone conversion

Posted: 30 May 2021 08:10 AM PDT

I need to convert from one timezone to another timezone in my project.

I am able to convert from my current timezone to another but not from a different timezone to another.

For example I am in India, and I am able to convert from India to US using Date d=new Date(); and assigning it to a calendar object and setting the time zone.

However, I cannot do this from different timezone to another timezone. For example, I am in India, but I am having trouble converting timezones from the US to the UK.

How do I enable choosing a row of a h:dataTable using JSF 2.0?

Posted: 30 May 2021 08:12 AM PDT

I'm starting a small project, using JSF 2.0. I'm having problems right in the start, in the CRUD of the first model implemented.

What I want to do is pretty simple:

The page has some filters to search, and using ajax, it populates a h:dataTable with the results. The user should now select the line with the result he wants to see/edit. But I just can't find a way to make the line selectable.

This is my table:

<h:dataTable var="aluno" value="#{alunoController.resultado}" >    <h:column>       #{aluno.id}    </h:column>    <h:column>       #{aluno.nome}    </h:column>    <h:column>       <!-- radiobutton, commandLink/Action goes gere -->    </h:column>  </h:dataTable>  

First I tried having a radiobutton on each line, then I learned that I can't have a radiogroup inside a table.

Then I tried having a radio group inside the first cell of each line, and handling selection with a little bit of JavaScript. Somehow, the databinding doesn't work, and I cant get the selected model back in my ManagedBean.

So I tried having a commandButton/Link, which sends the model via parameter.... not. It just refresh the page.

The I tried using query parameters, sending the id of that row and getting the model from de database again, but I cant find a way to tell which method should be called in the ManagedBean.

So I came here for my very first time, looking for suggestions. What should I do? Am I missing some information?

I just don't want to believe what I want to do is too advanced.

Call Ruby class over java with jruby

Posted: 30 May 2021 08:11 AM PDT

If I implement a class in ruby and compile it with jrubyc than it is not possible to call it from a java class directly if I start it with java. If I see this right I have to use org.jruby.embed... to implement a wrapper which takes a class name and a method to call my ruby class.

Do I have to do this also if I start the application with jruby? In my current project I start java workflow engine completely with jruby. The workflow has to call a method in a ruby class which it can't find.

Maybe easier to understand:

      [ruby_class]   <-----has to call----.                                            |  jruby [ruby_start_script] --starts--> [java wfe]  

No comments:

Post a Comment