Thursday, July 8, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Unable to get few values such as code, scope and session state from previous request responses to use in corresponding requester parameter (OIDC auth)

Posted: 08 Jul 2021 08:02 AM PDT

Help me on getting the above mentioned values please

enter image description here

Output empty 2d char array (Java)

Posted: 08 Jul 2021 08:02 AM PDT

I've been trying to understand what's happening with the output, when I'm trying to print an empty 2d char array.

import java.util.Arrays;    class Scratch {      public static void main(String[] args) {          char[] tictactoe = new char[9];          tictactoe[0] = '1';          System.out.println(tictactoe);            int[][] new2 = new int[2][2];          new2[0][0] = 2;          System.out.println(new2[0][0]);            char[][] ne3 = new char[3][3];                    System.out.println(ne3);          System.out.print(Arrays.deepToString(ne3));      }  }  

This is the output I get:

100000000  2  [[C@9807454   // what does this mean? where does it come from?  [[ ,  ,  ], [ ,  ,  ], [ ,  ,  ]]   

What I don't understand is, what is being printed if I try to output a 2d char array, which cells has not been initialised? I am specifically referring to code System.out.println(ne3); which gives me following output line [[C@9807454 Can anyone kindly explain? Thanks so much in advance!

Beginner Question: OR operator Not Working?

Posted: 08 Jul 2021 08:02 AM PDT

Just started learning python and I have been doing pet projects. During this one I decided to use the OR operator. When I added it to one of my IF STATEMENTS it worked as intended but when I added it to the other 3 it only ran the first IF STATEMENT.

  while True:            operation = input("What order of operation would you like to use(Addition/A ,Subtraction/S ,Multiplication/M, Division/D)?")            if operation == "Addition" or "a" :          while True:              Set_Number = int(input("Starting Number: "))              counter = Set_Number              print(counter)                            number = int(input("Add:"))              add_count = number              counter += add_count              print(f"Your Answer is " + str(counter))                    if operation == "Multiplication" or "m" :          while True:               Set_Number = int(input("Starting Number: "))              counter = Set_Number              print(counter)                            number = int(input("Multipled By:"))              add_count = number              counter = counter * add_count              print(f"Your Answer is " + str(counter))                if operation == "Division" or "d" :          while True:              Set_Number = int(input("Starting Number: "))              counter = Set_Number              print(counter)                            number = int(input("Divided By:"))              add_count = number              counter = counter/add_count              print(f"Your Answer is " + str(counter))                            if operation == "Subtraction" or "s" :          while True:              Set_Number = int(input("Starting Number: "))              counter = Set_Number              print(counter)                            number = int(input("Subtracted By:"))              add_count = number              counter = counter - add_count              print(f"Your Answer is " + str(counter))  

Result

What order of operation would you like to use(Addition/A ,Subtraction/S ,Multiplication/M, Division/D)?m  Starting Number: 8  8  Add:1  Your Answer is 9  Starting Number:  

Don't know how to fix. Need Help.

How to make the vertical line equal with the vertical line of the article?

Posted: 08 Jul 2021 08:01 AM PDT

Hello I have a question,

I want to know how to make the vertical line equal with the vertical line of the article? Thanks in advance!

enter image description here

This is de css code of the menu:

ul {  box-sizing: border-box;  display: flex;  list-style: none;  justify-content: center;  background-color: #0cee44;  padding: 15px;      }    li {      flex-basis: calc(100%/3);      text-align: center;      border-inline-end: 2px solid #FFF;      padding-inline-start: 5px;      padding-inline-end: 5px;  }    li:last-child {      border-inline-end: none;  }      li:hover {      background-color: #ff0000;  }  

This is de css code of the article

article {      column-count: 3;      column-rule: 1px solid red;  }  

NODE_ENV=development is not recognized as the name of a cmdlet, function, script file, or operable program

Posted: 08 Jul 2021 08:01 AM PDT

console.log(process.env.NODE_ENV) I have got the following error

sass-loader additionalData/prependData/data bloats bundle size

Posted: 08 Jul 2021 08:01 AM PDT

I'm using Vue2 and laravel-mix and I want to have my variables accessible globally. I eventually found this:

mix.webpackConfig({      module: {          rules: [              {                  test: /\.scss$/,                  use: [                      {                          loader:  'sass-loader',                          options: {                              //this might be "data" or "prependData" depening on your version                              additionalData: `@import "./resources/js/styles/variables.scss";`                          }                      }                  ]              }          ]      }  })  

This does make my variables globally accessible, but essentially copies the variables.scss into every single vue component, which massively bloats my bundle size.

How can I prevent this?

Should root element font size affect elements other than text?

Posted: 08 Jul 2021 08:01 AM PDT

Learning about rem and try to make whole website responsive.

According to the value of 1rem, should I be scaling:

  1. Font sizes and margins/paddings around text
  2. margins/paddings/size of elements that do not directly contain text like components and images

Does this depend on the layout?

For example, I have an image in a card component. As user increases the font size, image or space around it might stay small next to a larger font.

Should I let this happen or scale image with the font size? I know the setting in the browser only changes font size. On Facebook, for instance, font size from browser settings does not affect the images or component sizes.

Should I then only worry about text?

Get oldest modified price

Posted: 08 Jul 2021 08:01 AM PDT

I have a table where each rows contains product id (A), price (P) and modification date (D) in YYYYMMDD format.

Here is the table :

WITH temp_table AS (  select 744583 as a, 9.21 as p, 20210706 as d from sysibm.sysdummy1  union all  select 744583 as a, 9.21 as p, 20210630 as d from sysibm.sysdummy1  union all  select 744583 as a, 9.21 as p, 20210628 as d from sysibm.sysdummy1  union all  select 744583 as a, 9.04 as p, 20210604 as d from sysibm.sysdummy1  union all  select 744583 as a, 9.04 as p, 20210201 as d from sysibm.sysdummy1  union all  select 744583 as a, 9.21 as p, 20200407 as d from sysibm.sysdummy1  )  select *  from temp_table  

what i have

What i would like to have is when the price changed for the last time. In this example, the third line : enter image description here

How would you do that ?

Thanks,

Efficiency of non contiguos subarray with python, tensorflow and GPU

Posted: 08 Jul 2021 08:01 AM PDT

I studied by myself a little about CUDA C and coding kernels to run on GPU. From the few things I learned I remember how important is the memory layout of the data for maximum effectiveness use of the different layers of the cache. A single misalign in the array used from the 256bits of data loaded can cause every single thread to make a load call instead of a single one for all the threads, making it time expensive to load all the data needed for the next instruction. Am I wrong?

I'm making a simple Neural Network with Tensorflow and Keras. I feed this Ai with chunks of images elaborated with python. The chunks for now are not contiguous, like 2x2 chunk=[[0,1],[4,5]] from an image 4x4 [0,1,...,14,15]. This array, from python to tensorflow, to Nvidia driver and actual GPU VRAM, will it be copied, elaborated or made contiguous in some way, or the memory layout of the array will be the exact same non contiguous?

I know that there are different options to make the subarray chunk contiguous but I was wondering if it is something I should actually worry about and take care and how much could performance degrade. Does anyone have already measured it?

Connect to FTP server in Angular

Posted: 08 Jul 2021 08:01 AM PDT

I am using Angular 9, and I need to upload files by connecting to an FTP server using an Input element,

I tried using the follwoing modules but non of them are working:

Basic ftp Simple ftp Ftp Client ftp

Is there any way to connect to the ftp server other than that

C++: store N different type of variable in a class and fetch each of them with their type

Posted: 08 Jul 2021 08:00 AM PDT

I am implementing a Storage class for such APIs:

    Storage<float, int, bool> storage(0.05, -1, false);      static_assert(0.05  == storage.get<float>());      static_assert(-1    == storage.get<int>());      static_assert(false == storage.get<bool>());  

The constructor Storage(args...) takes N template parameter and N corresponding value for each type. Then user can fetch each variable by their type, e.g. get<float>() returns the float. (Each type appears no more than once)

And I think I have the interfaces defined:

template <class... TypeList>  class Storage {  public:      explicit Storage(TypeList ... args) {}        template <typename T>      T get() const;  };  

but I have no idea how to implement them. Can somebody give me some hints?

Hard to understand JSONPath containing [?]

Posted: 08 Jul 2021 08:00 AM PDT

In a legacy system I found this JSONPath :
$['data']..['rels'][?]['persons'][*]
I am confused by [?], as I am trying to rebuild the expected JSON that should by like (but it's not) :

{    "tag1": ["VALUE1"],    "data": [      {        "tag2": "VALUE2",        "rels": [          {            "persons": [              {                "uid": "uid12"              }            ],            "tag3": {              "tag4": "tag4"            }          }        ]      }    ]  }  

I used https://jsonpath.com/
Thanks for your help

How do I get rid of flashing box around my card or container?

Posted: 08 Jul 2021 08:00 AM PDT

When I scroll the box flickers black and white. Is it the card or container? How do I get rid of it?

Card(              color: Colors.white,              margin: EdgeInsets.zero,              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(0),),              child: Container(                height: 20,                decoration: BoxDecoration(                  color: Color(0xFF1F305E),                  borderRadius: BorderRadius.only(                    topLeft: Radius.circular(30.0),                    topRight: Radius.circular(30.0),),              ),            ),            ),  

Why doesn't my program enters in my switch case "deleteRegistro" sending and getting with $_POST in PHP?

Posted: 08 Jul 2021 08:00 AM PDT

My problem: I don't know why, my switch case is doesn't working properly and I don't know why if my AJAX status == 'succcess'.

My onClick function is in my button:

$data->acción = "<div class='text-center'><div class='btn-group'><button id='modificar_$data->id' class='btn btn-primary btn-sm btnEditar' value='edit'><i class='material-icons'>edit</i></button><button onclick='Delete($data->id, $tableName, $field)' class='btn btn-danger btn-sm btnBorrar'><i class='material-icons' value='delete'>delete</i></button></div></div>";  

My function:

function Delete(id, tableName, field){      if (confirm("¿Estás seguro que deseas borrar el registro con ID " + id + "?") == true) {          $.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/", {               action: "deleteRegistro",              id: id,              tableName: tableName,              field: field          }, function (data, status){                  if (status === 'error') {                      console.log("Not deleted");                  }                  else if (status === 'success') {                      console.log("Deleted successfully");                                                  }              });      }  }  

My switch case:

switch($_POST['action']){      case 'deleteRegistro':                        $id = $_POST['id'];          $tableName = $_POST['tableName'];          $field = $_POST['field'];              echo "Hello!";          ?>              <script>alert("Hello!");</script>          <?php                     break;  }  

As you can see, my AJAX status == 'succcess':

enter image description here

This is my full code if you need to check it:

<?php        use GuzzleHttp\json_decode;      include_once(DIR_PLUGINS.'/alexcrudgenerator/main.php');        $test = new GenerateCrud($_POST['tableName'], $_POST['id'], $_POST['tableFields']);            if ($_GET['action']){          print_a($_GET['action']);      }        switch($_POST['action']){                    case 'datosTabla': // OK.                            //print_r($_POST['action']);              $res = json_decode($_POST['datos']);              echo json_encode($res, JSON_UNESCAPED_UNICODE);                            break;                    case 'deleteRegistro':                            $id = $_POST['id']; // Quiero obtener estas variables que he enviado desde la función Delete();              $tableName = $_POST['tableName']; // Quiero obtener estas variables que he enviado desde la función Delete();              $field = $_POST['field']; // Quiero obtener estas variables que he enviado desde la función Delete();                            echo "Hello!";              ?>                  <script>alert("Hello!");</script>              <?php                             break;                        case 'showtable': // OK.                $res = getEntireTable($_POST['tableName'], $_POST['id'], $_POST['tableFields']);              $tableName = $_POST['tableName'];              $tableName = json_encode($tableName);                $field = json_decode($_POST['tableFields'],1)[0];              //print_r($tableName);              //print_r('<br>');              //print_r($campo);                            foreach ($res as $data){                                  $data->acción = "<div class='text-center'><div class='btn-group'><button id='modificar_$data->id' class='btn btn-primary btn-sm btnEditar' value='edit'><i class='material-icons'>edit</i></button><button onclick='Delete($data->id, $tableName, $field)' class='btn btn-danger btn-sm btnBorrar'><i class='material-icons' value='delete'>delete</i></button></div></div>";                   $resultados['data'][] = $data;              }                                       $resultados = json_encode($resultados); // 7 PROPIEDADES                            foreach(json_decode($_POST['tableFields']) as $columnsDB){                  $fields[] = array('data'=>$columnsDB);              }                $fields[]['data'] = 'acción';              $fields = json_encode($fields);                ?>              <head>                  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">              </head>                            <div class="container caja">                  <div class="row">                      <div class="col-lg-12 col-sm-12">                          <div>                              <table id="tablaUsuarios" class="table table-striped table-bordered table-condensed hover" style="width:100%" >                                  <thead class="text-center">                                      <tr>                                          <?php                                              foreach (json_decode($_POST['tableFields']) as $columnsTH){                                                   echo '<th>' . strtoupper($columnsTH) . '</th>';                                              }                                              echo '<th>ACCIÓN</th>';                                          ?>                                      </tr>                                  </thead>                                  <tbody>                                  </tbody>                              </table>                          </div>                      </div>                  </div>              </div>                <script>                    function Delete(id, tableName, field){                      if (confirm("¿Estás seguro que deseas borrar el registro con ID " + id + "?") == true) {                          $.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/", {                               action: "deleteRegistro",                              id: id,                              tableName: tableName,                              field: field                          }, function (data, status){                                  if (status === 'error') {                                      console.log("Not deleted");                                  }                                  else if (status === 'success') {                                      console.log("Deleted successfully");                                                                  }                              });                      }                  }                                        $(document).ready(function() {                      var datos= <?=$resultados?>;                      var dynamicColumns = <?=$fields?>;                      datos = JSON.stringify(datos);                                            $('#tablaUsuarios').DataTable({                          "language": {"url": "https://cdn.datatables.net/plug-ins/1.10.25/i18n/Spanish.json"},                          "paging": true,                          "lengthChange": true,                          "searching": true,                          "info": true,                          "autoWidth": true,                          "scrollX": true,                            "ajax":{                              "url": '<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/',                              "method": 'POST',                              "data":{action: "datosTabla", datos: datos}                          },                            "columns": dynamicColumns                      });                  })              </script>  <?php          break;        }  ?>  

Can someone give me a hand? I really don't understand.

If the status == 'success', it means that the POST request has been sent successfully, so I should go into my case switch and print a "Hello!".

What am I doing wrong?

How to set the color in IText via rgb?

Posted: 08 Jul 2021 08:02 AM PDT

Is it possible to set the color in IText via rgb?
I set the color this way:

canvas.SetFillColor(ColorConstants.BLUE);  

I would like to set the color more accurately.

Is a member initialization list without a value defined? [duplicate]

Posted: 08 Jul 2021 08:02 AM PDT

Say I have :

class Foo  {  public:    int x;    Foo() : x() {}  }   

Would it be UB to read x after the constructor has ran? More specifically, what type of initialization is this, zero, direct or default initialization?

I know if instead we'd have:

Foo() : x(42) {}  

x would be direct-initialized to 42 but I'm not so sure for the snippet above and I don't want to get bit by the UB wolf if this turns out to be default-initialized.

How to solve Caused by: java.net.SocketTimeoutException: Read timed out

Posted: 08 Jul 2021 08:01 AM PDT

This is my send mail code. It was working just now, but when I turned off the computer and turned it on, I encountered this error. At first there was no code in this line prop.setProperty("mail.smtp.timeout.enable", "25000");, I saw it on another site and added it, but it still gives an error.

 import javax.mail.*;   import javax.mail.internet.InternetAddress;   import javax.mail.internet.MimeMessage;   import java.util.Properties;        public class SendEmail {    public static void sendAsync(String toEmail, String text, String subject) {            new Thread(() -> {          send(toEmail, text, subject);      }).start();        }    public static void send(String toEmail, String text, String subject) {            final String username = "anar.memmedov1501@gmail.com";      final String password = "password";        Properties prop = new Properties();      prop.put("mail.smtp.host", "smtp.gmail.com");      prop.put("mail.smtp.port", "587");      prop.put("mail.smtp.auth", "true");      prop.put("mail.smtp.starttls.enable", "true");       prop.setProperty("mail.smtp.timeout.enable", "25000");        Session session = Session.getInstance(prop,              new javax.mail.Authenticator() {          @Override          protected PasswordAuthentication getPasswordAuthentication() {              return new PasswordAuthentication(username, password);          }      });        try {            Message message = new MimeMessage(session);          message.setFrom(new InternetAddress(username));          message.setRecipients(                  Message.RecipientType.TO,                  InternetAddress.parse(toEmail)          );          message.setSubject(subject);          message.setText(text);            Transport.send(message);        } catch (MessagingException e) {          e.printStackTrace();      }  }  

}

Unable to load asset:

Posted: 08 Jul 2021 08:01 AM PDT

here is the erros massage:
Unable to load asset: assets/images/waiting.png

When the exception was thrown, this was the stack Image provider: AssetImage(bundle: null, name: "assets/images/waiting.png") Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#e3e67(), name: "assets/images/waiting.png", scale: 1.0)

here is my pubspec.yaml

flutter:    uses-material-design: true      # To add assets to your application, add an assets section, like this:    assets:      - assets/images/waiting.png  

How can I solve inner join problem between these two tables?

Posted: 08 Jul 2021 08:02 AM PDT

I have this code working perfectly

<?php        require'dbehrpdo.php';      $seen = "2";      $count = 1;      $total = 0;            $t1 = strtotime($datea." 00:00:00");      $t2 = strtotime($dateb." 23:59:59");            foreach($conepdo->query("SELECT COUNT(id), school FROM waitinglist WHERE seen = '$seen' AND timeseen BETWEEN $t1 AND $t2 GROUP by school ORDER BY COUNT(id) DESC") as $row) {            echo "<tr>";       echo "<td width='10%'>" . $count . "</td>";      echo "<td width='70%'>" . $row['school'] . "</td>";      echo "<td width='20%'>" . $row['COUNT(id)'] . "</td>";      echo "</tr>";             $count = $count + 1;            $total = $total + $row['COUNT(id)'];            }    ?>  

the column 'school' store abbreviation like NG, USA but I have another table 'schools' where I have

id, name, and abr as full name and abbreviation.

why is this code not working?

<?php        require'dbehrpdo.php';      $seen = "2";      $count = 1;      $total = 0;            $t1 = strtotime($datea." 00:00:00");      $t2 = strtotime($dateb." 23:59:59");            foreach($conepdo->query("SELECT COUNT(waitinglist.id), schools.name FROM waitinglist INNER JOIN schools ON waitinglist.school = schools.abr WHERE seen = '$seen' AND timeseen BETWEEN $t1 AND $t2 GROUP by school ORDER BY COUNT(id) DESC") as $row) {            echo "<tr>";       echo "<td width='10%'>" . $count . "</td>";      echo "<td width='70%'>" . $row['schools.name'] . "</td>";      echo "<td width='20%'>" . $row['COUNT(id)'] . "</td>";      echo "</tr>";             $count = $count + 1;            $total = $total + $row['COUNT(id)'];            }    ?>  

BigQuery - Query for each elements

Posted: 08 Jul 2021 08:01 AM PDT

I would like to loop over several elements for a query.

Here is the query :

SELECT    timestamp_trunc(timestamp, DAY) as Day,    count(1) as Number  FROM `table`  WHERE user_id="12345" AND timestamp >= '2021-07-05 00:00:00 UTC' AND timestamp <= '2021-07-08 23:59:59 UTC'  GROUP BY 1  ORDER BY Day  

So I have for the user "12345" a row counter per each day between two dates, this is perfect.

But I would like to do this query for each user_id of my table, and if possible I would like each day on column, so each row is a user and the number available for each column (which is a day).

Result wanted :

User   | 2021-07-05 | 2021-07-06 | 2021-07-07  ---------------------------------------------  user_1 | 345        | 16         | 41  user_2 | 555        | 53         | 26  

Thank you very much

Getting input from another window in tkinter

Posted: 08 Jul 2021 08:00 AM PDT

I am having a little trouble with this project that I am working on. My project is this GUI application. In my test.py file, I call another file that contains instructions for another GUI window. This is where I am having trouble. In the test.py file, if you click run, a small window will appear. Click TEST in the small window. Then another window will appear that contains text fields if you enter numbers into the text fields for the window and then click enter. My IDE gets these error messages. It says that " ValueError: could not convert string to float: ' ' " My question is how do I fix this so that I do not get this error message? It is supposed to print the input that was entered into the window. I have two files, test.py, and model_objects.py. If you run model_objects.py by itself, it works perfectly. But when I try to import this file into test.py, it does not want to work right. This is programmed in Python. Also, my model_objects.py file is placed in a folder called util in the project. The values that I entered are floating-point values. I am having trouble with this. If you can help, I would greatly appreciate it.

Here is my code:

model_objects.py (This is in a folder called util in the project.)

  import tkinter as tk  from tkinter import ttk  from tkinter.ttk import Style    import numpy as np    from util import InputData      class Harmonic_Oscillator:      def __init__(self):          self.type = 0          self.name = "Harmonic Oscillator"          self.nparam = 2          self.label = ["\u03BC", "k"]          self.param = np.zeros(self.nparam, float)        def set_param(self, param_list):          for i in range(self.nparam):              self.param[i] = param_list[i]          return      class Morse_Oscillator:      def __init__(self):          self.type = 1          self.name = "Morse Oscillator"          self.nparam = 3          self.label = ["\u03BC", "De", "a"]          self.param = np.zeros(self.nparam, float)        def set_param(self, param_list):          for i in range(self.nparam):              self.param[i] = param_list[i]          return      class Test_Oscillator:      def __init__(self):          self.type = 2          self.name = "Test Oscillator"          self.nparam = 4          self.mu = 0          self.label = ["a", "b", "c", "d"]          self.param = np.zeros(self.nparam, float)        def set_param(self, param_list):          for i in range(self.nparam):              self.param[i] = param_list[i]          return      def model_prompt(potential_model):      window1 = tk.Tk()      style = Style()      window1.title('PyFGH Parameters')      box_length = 103      for q in range(3):          box_length = box_length + 33 * potential_model[q].nparam      box_len_str = '300x' + str(box_length)      window1.geometry(box_len_str)        entries = []      qvar = np.empty(3, dtype=list)      for i in range(3):          qvar[i] = []      j = 0      y = 5        for q in range(3):          for qparam in range(potential_model[q].nparam):              qvar[q].append(tk.StringVar())                ttk.Label(window1, text=potential_model[q].label[qparam] + " for Q:" + str(q + 1) + ":",                        font=("Times New Roman", 15)).place(x=50, y=y)              # set text variable as q1var[j] , each entry will have separate index in the list              a1 = ttk.Entry(window1, textvariable=qvar[q][qparam], font=("Times New Roman", 10)).place(x=140, y=y)                j += 1              y += 35        def enter_button():          for q in range(3):              param_list = []              for qparam in range(potential_model[q].nparam):                  param_list.append(qvar[q][qparam].get())              potential_model[q].set_param(param_list)  # This is giving me error. Not working properly!!!            for q in range(3):              for qparam in range(potential_model[q].nparam):                  print(potential_model[q].param[qparam])            InputData.output.items.model_data = potential_model          print(InputData.output.items.model_data)          window1.destroy()        enter = tk.Button(window1, text='Enter', bd='20', bg='green', fg='white',                        command=enter_button).place(x=110, y=y)        window1.mainloop()      def output2():      sections = []      for i in range(3):          if InputData.output.items.v[i] == "Model-Harmonic Oscillator":              sections.append(Harmonic_Oscillator())          elif InputData.output.items.v[i] == "Model-Morse Oscillator":              sections.append(Harmonic_Oscillator())          elif InputData.output.items.v[i] == "Model-Test Oscillator":              sections.append(Harmonic_Oscillator())      #test = [Harmonic_Oscillator(), Morse_Oscillator(), Test_Oscillator()]  #model_prompt(test)  

Here is another file called test.py

from util import InputData  from util import model_objects  from util import model_objects  from util.model_objects import Harmonic_Oscillator, Morse_Oscillator, Test_Oscillator, model_prompt  import tkinter as tk      def write_slogan():      test = [Harmonic_Oscillator(), Morse_Oscillator(), Test_Oscillator()]      model_prompt(test)      root = tk.Tk()  frame = tk.Frame(root)  frame.pack()    button = tk.Button(frame,                     text="QUIT",                     fg="red",                     command=quit)  button.pack(side=tk.LEFT)  slogan = tk.Button(frame,                     text="TEST",                     command=write_slogan)  slogan.pack(side=tk.LEFT)    root.mainloop()  

Update method doesn't work in Codeigniter 4

Posted: 08 Jul 2021 08:02 AM PDT

I have a table that contains some website configs. And its model class like:

<?php    namespace App\Models;    use CodeIgniter\Model;    class WebsiteConfig extends Model  {      protected $table = 'website_config';      protected $id = 'id';      protected $allowedFields = [          'config_name', 'config_value', 'updated_date'      ];  }  

And the table looks: Table Screenshot

I want to update 'title' on this table. And codeigniter 4 documentation shows:

$data = [      'title' => $title,      'name'  => $name,      'date'  => $date,  ];    $builder->where('id', $id);  $builder->update($data);  

But, when i use this usage, error occurs. My code:

    class Home extends BaseController      {          public function index()          {              $websiteConfig = new WebsiteConfig();              try {                  $websiteConfig                      ->where('config_name', 'title')                      ->update('test');              } catch (\ReflectionException $e) {              }              exit;          }      }  

And the error: Error Screenshot

When i use the update method with set('config_value','test') function, the code is working without errors. But i want to update as shown on documentation. What can i do? Thanks for helping.

Failed to execute 'send' on 'WebSocket': Still in CONNECTING state

Posted: 08 Jul 2021 08:00 AM PDT

I am new in react js development and try to integrate WebSocket un my app.

but got an error when I send messages during connection.

my code is

  const url = `${wsApi}/ws/chat/${localStorage.getItem("sID")}/${id}/`;        const ws = new WebSocket(url);      ws.onopen = (e) => {      console.log("connect");    };      ws.onmessage = (e) => {      const msgRes = JSON.parse(e.data);      setTextMessage(msgRes.type);      // if (msgRes.success === true) {      //   setApiMessagesResponse(msgRes);      // }      console.log(msgRes);    };    // apiMessagesList.push(apiMessagesResponse);      // console.log("message response", apiMessagesResponse);    ws.onclose = (e) => {      console.log("disconnect");    };      ws.onerror = (e) => {      console.log("error");    };      const handleSend = () => {      console.log(message);      ws.send(message);    };    

and got this error

Failed to execute 'send' on 'WebSocket': Still in CONNECTING state  

Is there a way to get numbers as characters in C and validate them?

Posted: 08 Jul 2021 08:00 AM PDT

I want to get a string of numbers up to 50(i.e. the limit on characters is 50) and validate them. For example - 123456789 is valid but 123sadfd456789 is not.

I could only figure out a way to get integer numbers through char.

Here's the code:

#include<stdio.h>  #include<stdlib.h>    int conToInteger(int n){      char ch[50];      printf("Enter a string: ");      gets(ch);      n=atoi(ch);      printf("Answer is: %d",n);  }    int main(){    int n;    conToInteger(n);    return 0;   }  

Can anybody help me out?? Thanks.

QR code generating but not working on device

Posted: 08 Jul 2021 08:01 AM PDT

I haven't had any issues running our mini app on device in the past, but i have been experiencing issues from today where I upload our code, publish and generate a QR code successfully, however when trying to scan the QR code via the vodapay app to test on device it either just doesn't scan or the app crashes.

I have asked two other members in our team and they have the same experience. So that eliminates my device. Any pointers on what the issue might be?

Thanks

Is there a lower-level C API than glibc on Linux? [duplicate]

Posted: 08 Jul 2021 08:01 AM PDT

If we want to create native Linux apps, we need to use glibc C APIs. If I'm correct the glibc APIs themselves call the Linux C APIs. Now I have two questions:

  1. Is that Linux C API available for programmers or is the glibc the lowest we can go? (lowest in C, not the assembly language)

  2. What do other higher-level frameworks use? (.NET Core, Java, Python, etc) Do they use glibc APIs or do they directly talk to the Kernel? (like glibc itself)

How do I create an endpoint with deliveryPolicy in Azure from JSON?

Posted: 08 Jul 2021 08:02 AM PDT

I have lots of rules in my Azure CDN Storage Endpoint Rules Engine. I want to copy these rules for a second endpoint. I don't want to have to manually recreate the rules.

If I look at the JSON view of this, I can see the rules in deliveryPolicy. Now this JSON does not contain things needed for an ARM template such as schema. So how can I use this template to create a new endpoint? Or, alternatively, update an existing endpoint? Happy to use CLI or Powershell.

Why the package level pointer variable is not assigned? [closed]

Posted: 08 Jul 2021 08:01 AM PDT

In the following code, router is package level variable that points to a struct. This pointer is initialized in main function. But the pointer is still nil in initializeRoutes function.

go version go1.14.6 windows/amd64

package main    import (      "github.com/gin-gonic/gin"      "net/http"  )      var router *gin.Engine    func main() {      router := gin.Default()      router.LoadHTMLGlob("templates/*")      initializeRoutes()      router.Run()  }    func initializeRoutes() {      fmt.Println(router)      // here the router is nil  }    

creating a custom argument matcher confusing implementation

Posted: 08 Jul 2021 08:00 AM PDT

I have seen someone creating a custom argument matcher like the following. However, I am having difficulty understanding how it works.

What I can understand its a method that takes a parameter and returns a ArgumentMatcher which is an interface that has a type of List<Person>. And the overriden method is the matcher that uses a lambda. I think the body part is the most confusing, if anyone can explain that.

private ArgumentMatcher<List<Person> personListSize(final int size) {          return argument -> argument.personList().size() == size;  }  

This is the way I would normally do something like this, which to me is easier to understand, just wondering how can I get the following to look like the above?

public class CustomArgumentMatcher implements ArgumentMatcher<List<Person>> {        @Override      public boolean matches(List<Person> argument) {          return argument.size() == size;      }  }  

Just starting to understand, this works:

 private ArgumentMatcher<String> stringMatcher = new ArgumentMatcher<String>() {          @Override          public boolean matches(String argument) {              return argument.contains("");          }      };  

However, If I add a parameter to pass in like this:

 private ArgumentMatcher<String> stringMatcherArgs(final String name) = new ArgumentMatcher<String>() {  }  

I get a error message saying unexpected token just wondering to pass in a parameter in the above?

Camel RabbitMQ DLQ implementation with autoAck true

Posted: 08 Jul 2021 08:01 AM PDT

I have a very simple requirement of

  1. On some exceptions, requeue the message
  2. On certain other exceptions, send to DLQ

My route is RabbitMQ → POJO validations → database validations → destination RabbitMQ

For case 1, my Camel exception route is:

onException(IOException.class)                  // Requeue for processing again                  .setHeader("rabbitmq.REQUEUE", constant(Boolean.TRUE))                  .removeHeaders("*")                  .bean(<do some stuff>)                  .handled(true)                  .end();  

For case 2, my Camel exception route is

onException(JsonPathException.class, PathNotFoundException.class)                  .setHeader("rabbitmq.REQUEUE", constant(Boolean.FALSE))                  .handled(true)                  .end()  

My basic Camel route is something like:

from(eventConsumerEndpoint)                  .filter().method(<validation>)                  .bean(<db fetch>)                  .filter().method(<db validation>)                  .removeHeaders("*")                  .to(eventConsumerDestination)                  .end();  

Now I have not used autoAck=false anywhere. My URI is something like:

rabbitmq://localhost:5672/events?autoDelete=false&deadLetterExchange=events&deadLetterExchangeType=topic&deadLetterQueue=dlq.xxx.yyy&deadLetterRoutingKey=evt.xxx.dead&exchangeType=topic&password=xxxxxx&queue=central-queue&username=guest&vhost=%2F  

So neither of my cases works - no requeue on IOException, no DLQ on JsonPath exception. So is this all because of autoAck? I don't want to handle acknowledgement at all, so is it possible to do this with autoAck false?

No comments:

Post a Comment