Thursday, September 16, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Destructuring array elements inside the for loop in javascript

Posted: 16 Sep 2021 08:20 AM PDT

Let's assume that I have a code structure as below,


const fruits = [ apple, banana, orange ];

for ( let i = 0; i < fruits.length; i++ ) {

const res = fruits[ i ];  console.log ( res );  

}


I want to destructure the

const res = fruits[ i ];

is it possible and I can use forEach also but I want to achieve the same within for loop.

Thanks in advance.

Android Studio Arctic Fox AVD Launch Error 'emulator process for .. has terminated'

Posted: 16 Sep 2021 08:20 AM PDT

Error: The emulator process for ... has terminated

Android Studio: Android Studio Arctic Fox | 2020.3.1 Patch 2

Desktop: GNOME, Fedora Linux

enter image description here

How to render bunch of strings in React native

Posted: 16 Sep 2021 08:20 AM PDT

Am building a small react native app where users can read about some of the tax laws. I hold the data (bunch of strings) on data.js which I render on the App tabs. But the App becomes too slow when navigating from Home Page to the tab, maybe, because of the bunch of strings that I'm rendering. Please, is there a better way on how to render huge strings (not list) in react native and the app will be fast?

Here's sample of the tab:

import dataOne from './data';  function TabOneContents(){      return(        <ScrollView>          <MyDivider>          <Text>About Finance Act 2019</Text>          <MyDivider/>                    <View>            <Text>{dataOne.pgOne[1]}</Text>            <Text>{dataOne.pgOne[2]}</Text>              {dataOne.pgOne.slice(3,8).map((item, index)=>{                return  <Text key={`${index}+unique1`}>                          {`\u2022 ${item}`}                        </Text>              })            }                  </View>          <View>            <Text>{dataOne.pgOne[8]}</Text>            <Text>{dataOne.pgOne[9]}</Text>            <Text>{dataOne.pgOne[10]}</Text>            {dataOne.pgOne.slice(11,15).map((item, index)=>{              return <Text key={`${index}+unique2`}>{`\u2022 ${item}`}</Text>            })}            <Text>{dataOne.pgOne[15]}</Text>            {dataOne.pgOne.slice(16,20).map((item, index)=>{              return <Text key={`${index}+unique3`} style={styles.cont1Text2}>{`\u2022 ${item}`}</Text>            })}             <Text>{dataOne.pgOne[20]}</Text>            <Text>{dataOne.pgOne[21]}</Text>            {dataOne.pgOne.slice(22,26).map((item, index)=>{              return <Text key={`${index}+unique4`}>{`\u2022 ${item}`}</Text>            })}            <Text style={{paddingBottom: 5, paddingTop:10}}>{dataOne.pgOne[26]}</Text>            {dataOne.pgOne.slice(27,31).map((item, index)=>{              return <Text key={`${index}+unique5`} style={styles.cont1Text2}>{`\u2022 ${item}`}</Text>            })}                 </View>          <MyDivider/>            <View style={[styles.container1,{backgroundColor: '#ff23'}]}>            <Text style={styles.cont1Text1}>{dataOne.pgOne[31]}</Text>            {dataOne.pgOne.slice(32,35).map((item, index)=>{              return <Text key={`${index}+unique6`} style={styles.cont1Text2}>{`\u2022 ${item}`}</Text>            })}               </View>          <MyDivider/>        </ScrollView>    )  }    export {TabOneContents};  

Python - Convert Json Array into Pandas Data frame for specific columns

Posted: 16 Sep 2021 08:20 AM PDT

I'm new to DataFrames and want to create one from my json but only include the columns itemId and value.

The json:

[  {    "orderId": 30303232,    "lines": [      {        "itemId": 433511,        "value": 11.50      },      {        "itemId": 64312,        "value": 12.42      }    ]  },    {    "orderId": 10320202,    "lines": [      {        "itemId": 533211,        "value": 11.50      },      {        "itemId": 653312,        "value": 12.42      }    ]  },  

At the moment, I have the following code which will simply read all. I want to be able to specify which columns:

JsonFilePath = "orders.json"  df=pd.read_json(JsonFilePath)    #I know for read_csv we can use usecols=col_list  

Expected result

itemId  value   433511  11.50  64312   12.42  533211  11.50  653312  12.42  

Nginx Container: no "ssl_certificate_key" is defined for certificate

Posted: 16 Sep 2021 08:20 AM PDT

I am trying to run a private docker registry using this tutorial. But after I did everything and run the docker-compose, I get the following error from the nginx container

no "ssl_certificate_key" is defined for certificate "/home/user/registry/nginx/ssl/key.pem"

Here is the registry.conf file:

upstream docker-registry {      server registry:5000;  }    server {      listen 80;      server_name example.com;      return 301 https://example.com$request_uri;  }    server {      listen 443 ssl http2;      server_name privatesecurereg.netspan.com;        ssl_certificate /home/user/registry/nginx/ssl/csr.pem;      ssl_certificate /home/user/registry/nginx/ssl/key.pem;        # Log files for Debug      error_log  /var/log/nginx/error.log;      access_log /var/log/nginx/access.log;        location / {          # Do not allow connections from docker 1.5 and earlier          # docker pre-1.6.0 did not properly set the user agent on ping, catch "Go *" user agents          if ($http_user_agent ~ "^(docker\/1\.(3|4|5(?!\.[0-9]-dev))|Go ).*$" )  {              return 404;          }            proxy_pass                          http://docker-registry;          proxy_set_header  Host              $http_host;          proxy_set_header  X-Real-IP         $remote_addr;          proxy_set_header  X-Forwarded-For   $proxy_add_x_forwarded_for;          proxy_set_header  X-Forwarded-Proto $scheme;          proxy_read_timeout                  900;      }    }  

What is the rpobelom and how to fix it ?

Regex: need first a occurrence of a non blank characters

Posted: 16 Sep 2021 08:20 AM PDT

I want to match first( only one occurrence of a character.) this case its a ; in regex101 it will match many times.

/(?<=^.*?;)/mg  

How to add test files to a linting script

Posted: 16 Sep 2021 08:20 AM PDT

I currently have this command in my package.json:

  "lint-staged": {      "{src}/**/*.{js,jsx,ts,tsx}": [        "prettier-eslint --write"      ]    }  

How can I add testing files to this? Currently SampleComponent.test.tsx does not get this command invoked on it, but SampleComponent.tsx does. Thanks!

ccxt FTX long/short position

Posted: 16 Sep 2021 08:20 AM PDT

i am trying to open and close short positions on FTX using ccxt with python. I do not find any kind of information or examples about how to do this.

Does anyone know how to do that, or has any example on opening and closing short positions using ccxt over FTX?

Thank you so much!

David

Chart.js sciptable options: accessing the values of the data object?

Posted: 16 Sep 2021 08:20 AM PDT

I am collecting data from an API.

Comes in JSON format:

[{'time':'08h00','magnitude':25, 'temper':12.6},{'time':'09h00','magnitude':39, 'temper': 5.3}]

Making my chart:

const ctx = document.getElementById('chart').getContext('2d');      const chart = new Chart(ctx, {          type: 'line',          data: {              datasets: [{                  label: "Line Graph",                  data: [],                  parsing: {                      xAxisKey: 'time',                      yAxisKey: 'temper'                  },                  borderColor: function(context) {                      var index = context.dataIndex;                      var value = context.dataset.data[index];                      console.log(value);                      return value > 10 ? 'red' : 'green';                  },                                }]          },          options: {              scales: {                  x: {                      type: 'time',                      time: {                          unit: 'day',                      },                  },              },              responsive: 'true',          }      });  

Then I populate it:

function addData(chart, data) {      for (x in data) {          chart.data.datasets[0].data.push(data[x]);      }      chart.update();  }    $.getJSON("https://8.0.0.85/last_48_hours", function (data) {          addData(chart, data)      });  

My issue is with this, which comes right out of the docs:

 borderColor: function(context) {                      var index = context.dataIndex;                      var value = context.dataset.data[index];                      console.log(value);                      return value > 10 ? 'red' : 'green';                  },  

because value is the whole Object {'time':'08h00','magnitude':25, 'temper':12.6}

var value = context.dataset.data[index].temper; and var value = context.dataset.data[index]['temper'];

and all manner of do not work. How can I reference value['temper']?

PowerMock,Mockito and javassist version conflict

Posted: 16 Sep 2021 08:20 AM PDT

I have faced with a problem that when I am trying to run my unit tests on this versions. Note: Problem exists only in Eclipse when I try to run on local on higher env it is working fine. And some of the test case which do not use closeablehttpclient are running fine.

PowerMock - powermock-mockito-release-full-1.6.4-full, powermock-module-testng-1.6.6 javaassist - javassist-3.24.0-GA java8

StackTrace-

javassist.CannotCompileException: [source error] cannot find constructor org.apache.http.protocol.RequestUserAgent(java.lang.String)  at javassist.expr.NewExpr.replace(NewExpr.java:235)  at org.powermock.core.transformers.impl.MainMockTransformer$PowerMockExpressionEditor.edit(MainMockTransformer.java:418)  at javassist.expr.ExprEditor.loopBody(ExprEditor.java:217)  at javassist.expr.ExprEditor.doit(ExprEditor.java:96)  at javassist.CtClassType.instrument(CtClassType.java:1541)  at org.powermock.core.transformers.impl.MainMockTransformer.transform(MainMockTransformer.java:74)  at org.powermock.core.classloader.MockClassLoader.loadMockClass(MockClassLoader.java:252)  at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:180)  at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:70)  at java.lang.ClassLoader.loadClass(ClassLoader.java:357)  at java.lang.Class.forName0(Native Method)  at java.lang.Class.forName(Class.java:344)  

What can I do if I get "overflow encountered in power" to execute sigmoid function?

Posted: 16 Sep 2021 08:20 AM PDT

When I run these code then I am getting these errors. I couldn't trace anything. I am trying to Implement a logistic regression with Iris data. I am getting problem to obtain accuracy.

import numpy as np    def sigmoid(x):      return 1 / (1 + np.e ** (-x))    dataset = np.loadtxt("iris.data", delimiter=',', dtype=str)  dataset = dataset[:100]    #array replace element  dataset = np.where(dataset == 'Iris-setosa', 1, dataset)  dataset = np.where(dataset == 'Iris-versicolor', -1, dataset)    #data type casting  m = dataset.astype(float)    #suffle  np.random.shuffle(m)    #select the first 30 samples for test (70 samples are training data).  testX = m[:30]  testY = m[:30,-1]      trainX = m[30:100]  trainY = m[30:100,-1]    #initialization  w = np.zeros(5)  b = 0  #learning rate  lr = 0.05    # GD  for i in range(1000):      w_diff = np.dot(np.transpose(trainY - sigmoid(np.dot(trainX, w))), trainX)      w = w + lr * w_diff    print("w: ", w)  # test  print(sum(np.round(sigmoid(np.dot(testX, w))) == testY)/np.size(testY))  

The error is following:

  return 1 / (1 + np.e ** (-x))  w:  [ -658.80023765  1572.88332431 -4295.61240946 -1716.37312787    3374.58205697]  0.03333333333333333  

How to handle endpoint calls testing with different permissions

Posted: 16 Sep 2021 08:20 AM PDT

I have an Laravel app with about 30 permissions. App also uses plenty of endpoints.

Now I want to write feature tests for each endpoint, checking every permission on it.

There is my question: Should I write separate method for each permission like that:

  public function test_if_user_can_create_article_having_articles_index_permission()  {      $user = $this->makeUserWithSuchPermisssion();      $this->actingAs($user)->post('/articles')->assertStatus(403)  }    public function test_if_user_can_create_article_having_articles_create_permission()  {      $user = $this->makeUserWithSuchPermisssion();      $this->actingAs($user)->post('/articles')->assertStatus(201)  }    public function test_if_user_can_create_article_having_users_index_permission()  {      $user = $this->makeUserWithSuchPermisssion();      $this->actingAs($user)->post('/articles')->assertStatus(403)  }    

and so on

or should I do it by looping through every permission within action test like that

  public function test_if_user_can_create_article()  {      foreach($invalid_permissions as $permission)      {          $user = $this->makeUserWithSuchPermisssion($permission);          $this->actingAs($user)->post('/articles')->assertStatus(403)      }              foreach($ok_permissions as $permission)      {          $user = $this->makeUserWithSuchPermisssion($permission);          $this->actingAs($user)->post('/articles')->assertStatus(201)      }        }    

or should I do it in another way? If yes, how you are solving that? I dont want to make multiple manual calls to each endpoint with every permission like that because it will become highly unmaintanable.

  public function test_if_user_can_create_article()  {      $route = '/articles';        $this->actingAs($this->createUserWithPermission('article.index'))->post($route)->assertStatus(403);      $this->actingAs($this->createUserWithPermission('users.index'))->post($route)->assertStatus(403);      $this->actingAs($this->createUserWithPermission('users.update'))->post($route)->assertStatus(403);      $this->actingAs($this->createUserWithPermission('article.create'))->post($route)->assertStatus(201)->assertJson(['aaa' => 'bbb']);        }    

Abstract struct for Driver Wrapper in C

Posted: 16 Sep 2021 08:19 AM PDT

I wanna ask, if this is a valid approach for my driver wrapper encapsulation or if there is a better way. My target is to hide the handle of the underlying driver, so the header does not include the driver library.

//wrapper_foo.h  typedef struct WrapperCtrl WrapperCtrl;  typedef WrapperCtrl *WrapperHandle;    WrapperHandle wrapper_open_device();  
  //wrapper_foo.c  #include "wrapper_foo.h"  #include "driver.h"  #include <stdint.h>        struct WrapperCtrl {      uint8_t wrapper_specific_parameter;      driver_handle handle;  };    static WrapperCtrl wrapper_cfg;        WrapperHandle wrapper_open_device() {      WrapperHandle w_handle = &wrapper_cfg;      w_handle->handle = driver_open_device();       if (w_handle->handle == NULL) {          return NULL;      } else {          return w_handle;      }  }  

Thanks for help and advise!

PQClear in other threa lag the main thread gui

Posted: 16 Sep 2021 08:19 AM PDT

I use libpq 13 (safe thread) 64 bit to connect pg13, I do huge result query , when I free the result using PQClear it took a long time to free, not bad until now, but I passed the statement result to another thread to free it in background.

While PQClear is executed in that thread , my gui desktop application is lagging, i made simple application in Delphi and Lazarus to test, keey lagging until PQClear finish it,

For more testing I used to to allocate a huge pieces random memory and free it in a thread, no lagging, that prove it is not my application memory manager, both took 25% of cpu, but PQClear is lagging.

Also I moved the whole query inside a thread, still lagging at PQClear.

I use PostgreSQL api directly with my own wrapper of, so it is not classes of Delphi/Lazarus

Any tip to see why PQClear is slowing down my desktop app? I use PG13, Windows10/8

Example to produce huge result for query:

   select left(md5(i::text), 10), md5(random()::text), md5(random()::text), md5(random()::text), md5(random()::text), left(md5(random()::text), 4)     from generate_series(1, 2000000) s(i)  

Is there armasm on mac?

Posted: 16 Sep 2021 08:19 AM PDT

I just started to learn ARM assembly and I know that there are mainly two toolchains to assemble ARM assembly, armasm and gnu. I am not able to use KEIL/IAR since I am using mac. Is there anyway I can add the armasm assembler to some IDEs on mac? I currently have vscode, stm32cube,and segger embedded studio.

Can I decompile a WebAssembly module?

Posted: 16 Sep 2021 08:20 AM PDT

Does Spring getWebServiceTemplate().marshalSendAndReceive(url,request) activate JAXB required tag during marshalling?

Posted: 16 Sep 2021 08:20 AM PDT

I am trying to confirm an validation issue. As far as I know, SAX marshaling can validate XML Schema via required fields via ValidationEventHandler. A sample code can be found under this link: http://www.java2s.com/Code/Java/XML/UseMarshalValidation.htm

I am trying to figure out if this is set in Spring WebServiceTemplate. As far as I know, there used to be a requirement to set a validator bean to activate such funcionality, however in this case the response is from a client and it is created via JAXB generation. Hence, I cannot add the validation on bean without heavy manipulation.

I am trying to confirm whether if the validation is working out-of-the-box with WebServiceTemplate.marshalSendAndReceive(uri, request).

A small sample is as:

@XmlRootElement(name = "Person")  public class Person{        @XmlElement(name = "Name", required = true)      private String name;  

I am trying to figure out if

 Person person = (Person) getWebServiceTemplate().marshalSendAndReceive(uri, request);  

would trigger a violation if 'name' field is null/not set on response.

Any meaningful feedback is welcome.

Python mock a method from a class that was not imported

Posted: 16 Sep 2021 08:19 AM PDT

Take this example, func_to_test_script.py

from module import ClassA    def func_to_test():      instance_b = ClassA.method_a()      foo = instance_b.method_b()  

method_a returns an instance of class ClassB.

I want to mock the calls of methods method_a and method_b, so I do

@mock.patch("func_to_test_script.ClassA", ClassAMock)  @mock.patch("func_to_test_script.ClassB", ClassBMock)  def test_func_to_test(self):      # test  

I can do this with ClassA (that was imported in func_to_test's file), but with ClassB I get the error

AttributeError: <module 'module' from 'func_to_test_script.py'> does not have the attribute 'ClassB'  

Are there analogues to Java's Collection interfaces in C++?

Posted: 16 Sep 2021 08:21 AM PDT

I'm trying to make a doubly linked list in C++, and I'm trying to do it right. Therefore, I thought I should adhere to any interface structure recommended by any "official" C++ guideline, such as an interface. In Java, there are such interfaces which one is free to use and which sort of standardise abstract data types (such as https://docs.oracle.com/javase/8/docs/api/java/util/List.html).

My question: Is there anything like this in C++? Startpageing found me this link:

https://en.cppreference.com/w/cpp/container/list

But it doesn't seem to use any inheritance.

Generate a list of all possible combinations

Posted: 16 Sep 2021 08:20 AM PDT

I want to generate a list of all possible number combinations within a set of seven numbers using all numbers from 0 through 9. The set of combinations can be repeated and it may look as following; 4,6,1,1,6,0,9 or just 7,7,7,7,7,7,7 So, I'd appreciate it if somebody could provide a solution/script.

WITH RECOMPILE in StoredProc after seting Parameters

Posted: 16 Sep 2021 08:20 AM PDT

I want to use the WITH RECOMPILE in a stored procedure after the declared parameter are filled with values. Where do I have to put it? I want to do something like this:

CREATE PROCEDURE sp_dosomething @AdrID INT = '32'        AS  select @AdrID = Select max(ID) FROM Address     WITH RECOMPILE    Select Streetname from Workadress where ID = @AdrID  Select Streetname from Homeadress where ID = @AdrID    GO  

So I want to set the parameter and then recompile the execution plan for the rest of the stored procedure every time it is executed.

What would be the right way to do it? Please help me.

How to re-render a component after clicking a bootstrap modal button in React.js

Posted: 16 Sep 2021 08:19 AM PDT

So I want to delete a user from my database, for just to confirm a user's action, I'm showing a warning on modal, If user will click the Delete button on modal, the delete function will be called. All works good except one thing, after deletion, my component is not re-rendering, for that purpose I need to use window.location.reload() which causes the whole page reload, to show the updated list of the users, but I don't want a full page reload, just want that specific component to be updated.

Here's the button which is calling the modal and updating value in a use state hook

<i                          data-toggle="modal"                          data-target="#exampleModal"                          style={{ cursor: "pointer" }}                          onClick={() => setDelUser(val.userEmail)}                          className="fas fa-trash-alt"                        ></i>  

Here's the button on the modal which is dismissing the modal and calling the delete function

<button                    type="submit"                    data-dismiss="modal"                    onClick={handleDelete}                    type="button"                    class="btn btn-primary"                  >                    Delete                  </button>  

And here's the delete function

const handleDelete = async () => {  if (delUser === admin) {    toast.error("Cannot delete the default admin!");    return;  } else {    try {      const result = await Http.post(`${Config.apiUrl}/users/delete`, {        email: delUser,      });      setDelUser("");    } catch (ex) {      if (ex.response && ex.response.status === 404) {        toast.error(ex.response.data);      }    }  }  

};

Why no code is executed after mainloop tkinter python

Posted: 16 Sep 2021 08:21 AM PDT

I know what is the purpose of mainloop (or at least i think), also i know that code placed after mainloop can be executed using after(), but why is like that? Why is mainloop blocking it?

Why does OpenGL buffer unbinding order matter?

Posted: 16 Sep 2021 08:19 AM PDT

I'm in the process of learning OpenGL (3.3) with C++, I can draw simple polygons using Vertex Buffer Objects, Vertex Array Objects, and Index Buffers, but the way I code them still feels a little like magic, so I'd like to understand what's going on behind the scenes.

I have a basic understanding of the binding system OpenGL uses. I also understand that the VAO itself contains the bound index buffer (as specified here), and if I'm not mistaken the bound vertex buffer too.

By this logic, I first bind the VAO, then create my VBO (which behind the scenes is bound "inside" the VAO?), I can perform operations on the VBO, and it will all work. But then when I come to unbind the buffers I used after I'm done setting up things, it seems that I must unbind the VAO first, then the vertex & index buffers, so the unbinding occurs in the same order as the binding, and not in reverse order.

That is extremely counter intuitive. So my question is, why does the order of unbinding matter?

(to clarify, I am rebinding the VAO anyway before calling glDrawElements, so I don't think I even need to unbind anything at all. it's mostly for learning purposes)

Here's the relevant code:

GLuint VAO, VBO, IBO;    glGenVertexArrays(1, &VAO);  glBindVertexArray(VAO);    glGenBuffers(1, &VBO);  glBindBuffer(GL_ARRAY_BUFFER, VBO);  glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);    glGenBuffers(1, &IBO);  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);  glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);  glEnableVertexAttribArray(0);    glBindVertexArray(0); //unbinding VAO here is fine  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);  glBindBuffer(GL_ARRAY_BUFFER, 0);  //if I unbind VAO here instead, it won't render the shape anymore      while (!glfwWindowShouldClose(window)) {      glfwPollEvents();        glUseProgram(shaderProgram);      glBindVertexArray(VAO);      glDrawElements(GL_TRIANGLES, 9, GL_UNSIGNED_INT, 0);        glfwSwapBuffers(window);  }  

macOS Docker Desktop with ElasticSearch 7.10.0 not running - ERROR: [1] bootstrap checks failed, exit code 78

Posted: 16 Sep 2021 08:21 AM PDT

It stops automatically after running for a couple seconds with the error below:

ERROR: [1] bootstrap checks failed    ERROR: Elasticsearch did not exit normally - check the logs at /usr/share/elasticsearch/logs/docker-cluster.log  

Many posts say it's because I need to increase vm.max_map_count to at least 262144, including the official doc for ElasticSearch: https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html#docker-cli-run-prod-mode

But I am unable to run docker-machine ssh, and I'm not sure why all of a sudden I need to use docker machine? I'm getting this error: Error: No machine name(s) specified and no "default" machine exists

Nor could I do: screen ~/Library/Containers/com.docker.docker/Data/vms/0/tty

tty does not exist in this directory, so the screen is terminating.

I can't just straight up do sysctl -w vm.max_map_count=262144 like many posts from and before the year 2018. This is what I'm getting: sysctl: unknown oid 'vm.max_map_count'

And this https://stackoverflow.com/a/41065159/14985824 doesn't work either, I do not have a sysctl.config file in that directory.

I'm not sure why this person is running a debian container, or maybe it's just because I don't really understand what is happening with method 1: https://stackoverflow.com/a/63595817/14985824

I'm looking at the Images on disk section on docker desktop, it tells me Total size: 1.11 GB, and they are all in use. Wondering if it has anything to do with this issue?

I have been struggling for a long time, please send help, thank you!

Edit: After trying to increase docker memory from 2GB to 3GB, I'm getting the following:

ERROR: [1] bootstrap checks failed    [1]: the default discovery settings are unsuitable for production use; at least one of [discovery.seed_hosts, discovery.seed_providers, cluster.initial_master_nodes] must be configured    ERROR: Elasticsearch did not exit normally - check the logs at /usr/share/elasticsearch/logs/docker-cluster.log  

Configure jacocoTestReport to read multiple .exec files as input

Posted: 16 Sep 2021 08:21 AM PDT

In my gradle build I have 2 test tasks like this:

task testAAA(type: Test) {      filter {            includeTestsMatching "*AAA*"      }        finalizedBy jacocoTestReport  }  

and

task testBBB(type: Test) {      filter {            includeTestsMatching "*BBB*"      }        finalizedBy jacocoTestReport  }  

This generates 2 .exec files in build/jacoco:

  • testAAA.exec

  • testBBB.exec

I want to generate a single coverage report that takes input from BOTH/ALL of the .exec files, I tried this:

jacocoTestReport {      executionData fileTree(project.rootDir.absolutePath).include("**/build/jacoco/*.exec")        reports {          xml.enabled true      }    }  

When I try that I get this error:

Execution failed for task ':Project1:jacocoTestReport'.  > Unable to read execution data file Project1/build/jacoco/test.exec    Project1/build/jacoco/test.exec (No such file or directory)    

Why is jacocoTestReport looking for "test.exec" when I explicitly provided an executionData specification?

How to implement recursive mapping using mybatis?

Posted: 16 Sep 2021 08:20 AM PDT

I have a java class

class Node {    String id;    String name;    List<Node> children;  }  

And the tables in MySQL:

NODES:  | ID | NAME |  | 1  | name1 |  | 2  | name2 |  | 3  | name3 |  | 4  | name4 |  

and another table for the relations

RELATIONS:  | PARENT_ID | CHILD_ID |  |    1      |     2    |  |    2      |     3    |  |    2      |     4    |  

Normally we can use left join and collection to wire them together like below

<resultMap id="node" type="org.hello.Node>    <id property="id" column="ID"/>    <result property="name" column="NAME"/>    <collection property="children" ofType="org.hello.Node" resultMap="node"/>  </resultMap>    <select id="select" resultMap="node">   SELECT ID, NAME FROM NODES N   LEFT JOIN RELATIONS R ON N.ID = R.PARENT_ID   LEFT JOIN NODES N1 ON R.CHILD_ID = N1.ID  </select>  

If N1 is just another table with another model, it should work. The question is How can we write mybatis xml configuration to recursively map above structure which refers back to itself?

kivy app stopped responding, message pops up either to wait or quiet forcely

Posted: 16 Sep 2021 08:20 AM PDT

I was trying to make a chatting app through kivy and using twisted with it, a made a kv button that starts a method which contains reactor.connectTCP("") function. when i tested the app after pressing the button, it gets connected to the server but after that it don't changes the screen and it stops responding.

chat.py:-

from twisted.internet import protocol,reactor    class ChatClient(protocol.Protocol):      def connectionMade(self):          self.transport.write("hlo")        def dataReceived(self,data):          print(data)          #user2.sendMsg(data)    class EchoFactory(protocol.ClientFactory):      def buildProtocol(self,addr):          user1.connectuser1()          return ChatClient()        def Conn_network(self):          reactor.connectTCP("localhost",8000,EchoFactory())          reactor.run()      from kivy.app import App  from kivy.uix.relativelayout import RelativeLayout  from kivy.uix.scrollview import ScrollView  from kivy.lang import Builder  from kivy.uix.screenmanager import ScreenManager, Screen, ObjectProperty    Builder.load_file("chat.kv")  Builder.load_file("chat2.kv")      class User1(Screen):      def connectuser1(self):          if self.ids.login_page.text=="akash" and self.ids.Password.text=="hello":              print ("logged in")              self.parent.current="chat_screen"          else:              print("username or password wrong")      class User2(Screen):      #def sendMsg(self,data):       #   self.ids.show_msg.text +=4        def connectuser2(self):          self.ids.show_msg.text +=self.ids.txt_msg.text +'\n'          self.ids.txt_msg.text =''    user1=User1()  sm=ScreenManager()  sm.add_widget(User1(name="login_screen"))  sm.add_widget(User2(name="chat_screen"))  class ChatApp(App,EchoFactory):        def build(self):          return sm  if __name__=="__main__":      ChatApp().run()  

chat.kv

<User1>:      login:login_page      RelativeLayout:            TextInput:              on_parent:self.focus = True              id:login_page              pos_hint:{"center_x": .5, "center_y": .7}              size_hint: .3, .2          TextInput:              on_parent:self.focus = True              id:Password              pos_hint:{"center_x": .5, "center_y": .5}              size_hint: .3, .2          Button:              text:"send"              pos_hint:{"center_x": .5, "center_y": .3}              size_hint: .3, .2              on_press:                  app.Conn_network()  

server.py:-

from twisted.internet import reactor,protocol    class Echo(protocol.Protocol):      def dataReceived(self,data):          print("connected")          self.transport.write(data)    class EchoFactory(protocol.Factory):      def buildProtocol(self,addr):          return Echo()    reactor.listenTCP(8000, EchoFactory())  reactor.run()  

getting error while using logcat for checking logs of an app in linux

Posted: 16 Sep 2021 08:21 AM PDT

I want to know bugs of my android app so i tried to use logcat to see its log and followed these steps:-

You need to use adb server.  1. Connect your android with your laptop/pc   2. Go to developer options and turn on the stay awake and USB debugging options. (Your phone)   3. In your terminal, type "sudo adb kill-server" and then "sudo adb start-server".  4. Type "adb devices" (this should give list of devices connected)      List of devices attached       you_device_name device    5. "cd" to your folder where you have made your build.  6. Type "buildozer android debug deploy run logcat > logcat.txt"  this saves the logs (for the entire process) in a file logcat.txtx in the same folder and also deploys you app on the phone.  Go through it and find your error.  7. keep your phone awake.(do not lock it).  

But when i run the 6th step, a time comes it says:-

error: device 'adb' not found  - waiting for device -  

i have searched many times on the internet and when finally i am posting here to get solution

Wordpress REST API V2 return all posts

Posted: 16 Sep 2021 08:19 AM PDT

I am missing the function to get ALL the posts (or CPT) by using

example.com/wp-json/wp/v2/country/?per_page=-1  

or any similiar. The documentation gives as much info as this:

per_page: Maximum number of items to be returned in result set.

Default: 10

And in another question about the per_page we learn that the allowed range is 1 to 100.

In my case there will be a limited number of posts I need to get, but it will be around 200-300. Are there any workarounds to get them all other than fetching everything page per page and stitching it together?

Additional info if it does matter: I am using angular.js

No comments:

Post a Comment