2021-12-31

How can we use/access/read file contents of files placed in a private gitlab repository in our java code

I want to use/access/read file contents of files (excel, properties file, etc.) placed in a private gitlab repository in my java code, which would be creating a CSV file as output using the contents of the files from the private gitlab repository.



from Recent Questions - Stack Overflow https://ift.tt/3HlpMry
https://ift.tt/eA8V8J

How to sort array of objects based on order of another array

I have an ArrayList of Strings in a certain particular order

ArrayList<String> sortedkeys

And I have an unordered set of objects

Set<Skugroup> unsortedSet

Where SkuGroup contains a key to be used for sorting

Class SkuGroup {
   private String sortkey;
   private String name; 
}

I need to copy all the SkuGroup objects into a new array in the same order of sortedSkus, where the sortedkey value is the same as the SkuGroup->sortkey

How can I accomplish this?



from Recent Questions - Stack Overflow https://ift.tt/3zdhQWn
https://ift.tt/eA8V8J

IntelliJ, .jar executable not behaving properly "java.lang.reflect.InvocationTargetException"

I have a JavaFX program that I need to make executable. I'm currently trying to do it with IntelliJ IDEA, it does create the .jar, but when I try to click on a clickable item that should pop a window it doesn't and instead in the console it prints this error:

Screenshot of the error I get

If it can be helpful this is a screenshot of the internal structure of the project + whats inside the manifest

I should also specify that I imported the javaFX library in Project Structure -> Artifacts.

(I already made a .jar executable for another project and worked fine there, but it didn't had any pop-up windows nor multiple .fxml / controllers... so I think that might be whats making it crash, but I'm not sure)

Edit: Also I forgot to say that the problem i reported above only happens in the .jar, if i debug the program/run it through the IDE it works perfectly fine.

Edit (Error code copy-pasted):

    Dec 30, 2021 6:51:43 PM javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 16 by JavaFX runtime of version 11.0.2
java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
        at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1787)
        at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1670)
        at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
        at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
        at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
        at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
        at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
        at javafx.event.Event.fireEvent(Event.java:198)
        at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3564)
        at javafx.scene.Scene$ClickGenerator.access$8200(Scene.java:3492)
        at javafx.scene.Scene$MouseHandler.process(Scene.java:3860)
        at javafx.scene.Scene$MouseHandler.access$1200(Scene.java:3579)
        at javafx.scene.Scene.processMouseEvent(Scene.java:1849)
        at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2588)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:397)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
        at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:434)
        at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:390)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:433)
        at com.sun.glass.ui.View.handleMouseEvent(View.java:556)
        at com.sun.glass.ui.View.notifyMouse(View.java:942)
        at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
        at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:568)
        at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:76)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:568)
        at com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:273)
        at com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:83)
        at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1782)
        ... 31 more
Caused by: java.lang.IllegalStateException: Location is not set.
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2459)
        at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2435)
        at Controllers.Home.LWELencoClick(Home.java:521)
        ... 43 more


from Recent Questions - Stack Overflow https://ift.tt/3HohmQh
https://ift.tt/eA8V8J

how to download an audio instead of play it in crefsharp(winform)

If I open an audio link using cefsharp browser, for example:

mp3

It will play it in the browser.

I am wondering how to make cefsharp download it if the link is an audio.

One solution is to check the link and use System.Net.WebClient to save the link to a file, but if the link isn't end with mp3,wav,...etc I still need to download it to check the file type.



from Recent Questions - Stack Overflow https://ift.tt/3mKOM3v
https://ift.tt/eA8V8J

Route 53 and Certificate Manager Issues

Is anyone else having issues getting a route 53 domain name certified using the certificate manager? I'm following the documentation very closely and am running into a block where I request a certificate through DNS and then create the records in route 53, but I'm stuck pending validation for days. When I click the "Create Records in Route 53 button" the records are created in route 53, but nothing else happens. Does anyone know what the issue could be?

The hosted zone is firstlast.com and I'm trying to certify www.firstlast.com and firstlast.com (not actually firstlast, some other name haha).

I followed this documentation: https://docs.aws.amazon.com/acm/latest/userguide/dns-validation.html

I've also tried email validation but they don't give you a CNAME and it's unclear how to integrate with route 53.



from Recent Questions - Stack Overflow https://ift.tt/3eE8Ksw
https://ift.tt/eA8V8J

macOS disk image - create in terminal with password

macOS 12.1 here. In the man page for hdiutil there is this example for creating a disk image with a password.

Creating an encrypted single-partition image without user interaction:
       printf pp|hdiutil create -encryption -stdinpass -size 9m sp.dmg

This works. It creates a 9MB .dmg file with a password but I don't get to see what the password is. I know the "printf" is supposed to show something but I don't know what the "pp" that follows that does?



from Recent Questions - Stack Overflow https://ift.tt/3EEE199
https://ift.tt/eA8V8J

2021-12-30

How to invoke a lambda after create/update in terraform?

I'm creating/updating a lambda function using terraform and I need to run it AFTER it is created or updated. I know there is a terraform data source aws_lambda_invocation but it runs BEFORE the lambda function created/updated. Is there any way to achieve this in terraform?



from Recent Questions - Stack Overflow https://ift.tt/3eCy2Hg
https://ift.tt/eA8V8J

jMeter: load file content on http request body

I'm trying to inject file content into the request body:

enter image description here

I'm using:

${__FileToString(${__eval(${bundle})},,)}

I've configured the bundle variable using the directory listing plugin:

enter image description here

When I perform the test, I'm getting:

enter image description here

Logs is getting me:

2021-12-28 16:33:53,853 WARN o.a.j.f.FileToString: Could not read open: /patient-bundle-0193.json

According to my configuration, __FileToString should read from /home/jeusdi/projects/workarea/salut/mpi/jsons/bundles/extractions/10000/bundles instead from /...

Any ideas?



from Recent Questions - Stack Overflow https://ift.tt/3zdn050
https://ift.tt/3HiDICE

How can I put a Console Write Command to String [closed]

Maybe this question is silly, but I hope someone can help me out. I'm trying to get the output of this command to a string.

 for (int i = 48; i < 123; i++)
 {
    int keyState = GetAsyncKeyState(i);

    if (keyState == 32769)
    {
       Console.Write((char)i);
    }
 }

The plan behind this is to get the string and do a regex. The regex should check the string and if the regex matches with the string it should execute a command.



from Recent Questions - Stack Overflow https://ift.tt/3EHxqe2
https://ift.tt/eA8V8J

Why Eigen C++ with MKL doesn't use multi-threading for this large matrix multiplication?

I am doing some calculations that include QR decomposition of a large number(~40000 in each execution) of 4x4 matrix with complex double elements (chosen from a random distribution). I started with directly writing the code using Intel MKL functions. But after some research, it seems like working with Eigen will be much simpler and result in easier to maintain code. (Partly because I find it difficult to work with 2d arrays in intel MKL & care needed for memory management).

Before shifting to Eigen, I started with some performance checks. I took a code(from an earlier similar question on SO) for multiplications of a 10000x100000 matrix with another 100000x1000 matrix (large size chosen to have the effect of parallelization ). I run it on a 36 core node . When I checked the stat, Eigen without Intel MKL directive (but compiled with -O3 -fopenmp) used all the cores and completed the task within ~7 sec.

On the other hand with,

#define EIGEN_USE_MKL_ALL
#define EIGEN_VECTORIZE_SSE4_2

the code takes 28 s & uses an only a single core. Here is my compilation instruction

g++ -m64 -std=c++17 -fPIC -c -I. -I/apps/IntelParallelStudio/mkl/include -O2 -DNDEBUG -Wall -Wno-unused-variable -O3 -fopenmp -I /home/bart/work/eigen-3.4.0 -o eigen_test.o eigen_test.cc
g++ -m64 -std=c++17 -fPIC -I.  -I/apps/IntelParallelStudio/mkl/include -O2 -DNDEBUG -Wall -Wno-unused-variable -O3 -fopenmp -I /home/bart/work/eigen-3.4.0 eigen_test.o -o eigen_test  -L/apps/IntelParallelStudio/linux/lib/intel64 -lmkl_intel_lp64 -lmkl_intel_thread -lmkl_rt -lmkl_core -liomp5 -lpthread

The code is here,

//#define EIGEN_USE_MKL_ALL // Determine if use MKL
//#define EIGEN_VECTORIZE_SSE4_2

#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
int main()
{

  int n_a_rows = 10000;
  int n_a_cols = 10000;
  int n_b_rows = n_a_cols;
  int n_b_cols = 1000;

  MatrixXi a(n_a_rows, n_a_cols);

  for (int i = 0; i < n_a_rows; ++ i)
      for (int j = 0; j < n_a_cols; ++ j)
        a (i, j) = n_a_cols * i + j;

  MatrixXi b (n_b_rows, n_b_cols);
  for (int i = 0; i < n_b_rows; ++ i)
      for (int j = 0; j < n_b_cols; ++ j)
        b (i, j) = n_b_cols * i + j;

  MatrixXi d (n_a_rows, n_b_cols);

  clock_t begin = clock();

  d = a * b;

  clock_t end = clock();
  double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
  std::cout << "Time taken : " << elapsed_secs << std::endl;

}

In the previous question related to this topic, the difference in speed was found to be turbo boost (& difference was not such huge). I know for small matrices Eigen may work better than MKL. But I can't understand why Eigen+MKL refuses to use multiple cores even when I pass -liomp5 during compilation.

Thank you in advance . (CentOS 7 with GCC 7.4.0 eigen 3.4.0)



from Recent Questions - Stack Overflow https://ift.tt/340T2FL
https://ift.tt/eA8V8J

Is there a way to reference a parameter value within the same PSD1 file?

Let's say that I have a PSD1 file, with the following code:

@{
    AllNodes = @(
    @{
        NodeName = $env:COMPUTERNAME
        Tags = @{
            Environment = "dev"
            Datacenter = "east 1"
        }
        Data = @{
            ConfigName = [Tags.Environment]-[Tags.Datacenter.replace(" ","-")]
        }
    })
}

See how I am trying to reference the "Tags" section later on in the same file? Is there some way to do that, or do I simply need to do so within a separate PS1 file?



from Recent Questions - Stack Overflow https://ift.tt/3JvDQR5
https://ift.tt/eA8V8J

Is there a way to list super primes between 1 and n in NumPy

Is there a way to list super primes (primes in a prime position wikipedia article) between 1 and n using NumPy.



from Recent Questions - Stack Overflow https://ift.tt/3JvZ01M
https://ift.tt/eA8V8J

Prevent data refresh in React-Query by data hash matching

The API that I hit with React-Query returns a set of data and a hash key for this data in a form like so:

{
orders:[{order1},{order2},....]
dataHash:number
}

I Use this dataHash to check if the request results are equal inside useQuery() options to make it easy for reach-query to compare big datasets on it's own like so:

isDataEqual:(oldData, newData)=>oldData?.dataHash === newData.dataHash, //do not refresh page if hashes are equal

The API also has a feature that allows not to send a dataset if the dataHash matches with the one in a request. In such case it only returns the following:

{
orders:[] //empty array here
dataHash:number
}

But since my compare function only looks at dataHash the new data will not be used and everything will work as expected.

The problem I have currently is that I cannot seem to find a built-in way in react-query to save the dataHash from the old request so that it is being passed as a parameter into the new one. Ideally I would like to see react-query passing the old data into the request function so I can compare it myself but this is not an option.

I also found that it passes some sort of metadata object into the request query, but I have not found a way to mutate this object for any particular request. Am I missing Something here?

  const getOrders = async (metadata:any): Promise<ShowOrdersResponse> => {
    console.log(metadata) //this holds the "meta" object and query keys
   
    const request: ShowOrdersRequest = {
      searchParam: mySearchParam,
      dataHash: 12//dataHash
    };

    const {data} = await secureAxios.post<ShowOrdersResponse>(ApiEndpoints.ShowOrders, request)
    return data;
  }

  const {data} = useQuery<ShowWorkOrdersResponse>(['workorders', mySearchParam], getOrders, {
    cacheTime: 30000,
    refetchInterval: 5000,
    isDataEqual:(oldData, newData)=>oldData?.dataHash === newData.dataHash, //do not refresh page if hashes are equal, this works as charm
    meta:{dataHash:555}  //I am able to pass this "meta" object into the request query, but cannot mutate it
  });

Edit1: I implemented the proposed solution but it still does not solve the problem completely. Currently I am saving the returned dataHash from server inside the component state like so:

onSuccess: (data) => setDataHash(data?.data.dataHash)

Later I call useQuery() with different search params, which it considers as a totally different request, yet since I'm sending the same hash I get no results back. isDataEqual() returns false and updates the data with empty result.

I think I need an ability to save the dataHash per-request(starting with undefined) but this means that queryFn needs to have access to "oldData.data.dataHash" to send it in. and currently i do not see how this can be done.



from Recent Questions - Stack Overflow https://ift.tt/3sI9V25
https://ift.tt/eA8V8J

How do I split a string with two different delimiters in Ruby and convert it to two arrays?

I have a string

"Param 1: 1, Some text: 2, Example3: 3, Example4: 4"

and I'd like to convert it into an arrays:

["Param 1","Some text","Example3","Example4"]
[1,2,3,4]

How?



from Recent Questions - Stack Overflow https://ift.tt/3JtO1pc
https://ift.tt/eA8V8J

how to fix the problem of the missing color pieces in the colorbox in gnuplot

I met a problem that when I draw a map using gnuplot, there would be a colorbox near the map which looks very weird. I blew up the colorbox and found that there were pieces with missing color, the picture is below. How can I fill the color for the colorbox? colorboxpicture

Here are the terminal type and the palette I used in in gnuplot. set terminal postscript portrait color enhanced 12. set palette defined (-6.0 "#1B66B1",
-4.8 "#1B66B1",
-4.8 "#2A85DF",
-3.6 "#2A85DF",
-3.6 "#5FA3E7",
-2.4 "#5FA3E7",
-2.4 "#95C2EF",
-1.2 "#95C2EF",
-1.2 "#C9E0F7",
-0.120000 "#C9E0F7",
0.0 "#FFFFFF",
0.0 "#FFFFFF",
0.120000 "#F6D5CB",
1.2 "#F6D5CB",
1.2 "#EDAB96",
2.4 "#EDAB96",
2.4 "#E48062",
3.6 "#E48062",
3.6 "#DC562E",
4.8 "#DC562E",
4.8 "#AE3F1E",
6.0 "#AE3F1E")



from Recent Questions - Stack Overflow https://ift.tt/3JuYOQ0
https://ift.tt/3z8NiVO

2021-12-29

Execute function for every subfolder

I have a folder named students_projects that contains 10 subfolders. Each subfolder has project1.c and project2.c, each one prints a value. I made a bash script function that check those numbers and save them to a txt file. I tested it with 2 .c files named project1 and project2 in Desktop and not in the folder. I made sure that i worked fine but when i went to run it for all the subfolders it keeps saving the values that are in desktop files.

My function:

function test () {
  gcc project1.c
  p1=$(./a.out)
  if (( $p1 == 20 ));
  then
    v1=30
  else
    v1=0
  fi
  gcc project2.c
  p2=$(./a.out)
  if (($p2 == 10 ));
  then
    v2=70
  else
    v2=0
  fi
  sum=$(( $v1 + $v2 ))
  on="cut -d' ' -f1 report.txt"
  onoma=$(eval "$on")
  temp="cut -d' ' -f2 report.txt"
  am=$(eval "$temp")
  printf "$onoma $am project1: $v1 project2: $v2 total_grade: $sum\n" >> grades.txt
}

Then i do

for FILE in students_projects/* ; do
  test
done


from Recent Questions - Stack Overflow https://ift.tt/3FAXXLf
https://ift.tt/eA8V8J

Expand row from grid to use free space left by a max-height row

Given a grid body and these 3 panes:

┌───┬───┐
│   │ B │
│ A ├───┤
│   │ C │
└───┴───┘

I'm trying to have A and B/C columns to be 50% 50% viewport width ; A to be 100% viewport height, B 60vh and C 40vh.
But also C to be max-height of its max-content, and so B to take the remaining place left by C if C's max-content is lower than 40vh.
All panes have overflow-y: auto and A & B always have scrollable content.

So starting with this

body {
    display: grid;
    grid-template-columns: 50% 50%;
    grid-template-rows: 60% 40%;
}
.a {
    grid-row: 1 / 3;
}

which work appart for the C's max-height part, I tried to replace grid-template-rowswith 60% minmax(40%, max-content), or even to use fixed height (say 16em) instead of max-content minmax(60%, calc(100% - 16em)) minmax(40%, 16em), but I'm definitely missing something here.



from Recent Questions - Stack Overflow https://ift.tt/33YrbG1
https://ift.tt/eA8V8J

I am only able to control the first out of four 8x8 led matrices powered by Max7219

I have 4 8x8 led matrices that are serial connected and I communicate with the using the SPI protocol.

And after rewriting a few libraries (python implementation, rust implementation, c implementation), because it just does not work on my system and my code works at least a bit I am only able to control the first out of the four connected displays.

Here is my code to display a target like image on the first display:

Matrix Object:

#![allow(dead_code)]
use spidev::Spidev;
use std::io::prelude::*;

// Maximum number of displays connected in series supported
const MAX_DISPLAYS: u8 = 8;

// Digits per addr
const MAX_DIGITS: u8 = 8;

// Possible command register values on the addr chip.
#[derive(Clone, Copy)]
pub enum Command {
    Noop = 0x00,
    Digit0 = 0x01,
    Digit1 = 0x02,
    Digit2 = 0x03,
    Digit3 = 0x04,
    Digit4 = 0x05,
    Digit5 = 0x06,
    Digit6 = 0x07,
    Digit7 = 0x08,
    DecodeMode = 0x09,
    Intensity = 0x0A,
    ScanLimit = 0x0B,
    Power = 0x0C,
    DisplayTest = 0x0F,
}

pub struct Matrix {
    pub spi: Spidev,
    pub devices: u8,
}
impl Matrix {
    pub fn init(&mut self) -> std::io::Result<()> {
        for device in 0..self.devices {
            self.send_bytes([device, Command::ScanLimit as u8, 0x07])?; // to scan for 8 digits or in this case columns
            self.send_bytes([device, Command::DecodeMode as u8, 0x00])?; // No Decode Mode for matrix
            self.send_bytes([device, Command::DisplayTest as u8, 0x00])?; // no displaytest desired
            self.send_bytes([device, Command::Power as u8, 0x01])?; // powers on the display
        }

        Ok(())
    }
    pub fn power_off(&mut self) -> std::io::Result<()> {
        for addr in 0..self.devices {
            self.send_bytes([addr, Command::Power as u8, 0x00])?;
        }
        Ok(())
    }
    pub fn send_command(&mut self, addr: u8, command: Command, value: u8) -> std::io::Result<()> {
        self.send_bytes([addr, command as u8, value])?;
        Ok(())
    }
    pub fn draw_raw(&mut self, addr: u8, data: [u8; 8]) -> std::io::Result<()> {
        let mut digit: u8 = 1; // column
        for b in data {
            self.send_bytes([addr, digit, b])?;
            digit += 1;
        }
        Ok(())
    }
    pub fn clear_display(&mut self, addr: u8) -> std::io::Result<()> {
        for col in 1..=MAX_DIGITS {
            self.send_bytes([addr, col, 0x00])?;
        }
        Ok(())
    }

    /// range 0 to 15
    pub fn set_intensity(&mut self, addr: u8, intesity: u8) -> std::io::Result<()> {
        self.send_bytes([addr, Command::Intensity as u8, intesity])?;
        Ok(())
    }

    fn send_bytes(&mut self, bytes: [u8; 3]) -> std::io::Result<()> {
        self.spi.write(&bytes)?;
        Ok(())
    }
}

main.rs

use spidev::{Spidev, SpidevOptions, SpiModeFlags};
use std::thread::sleep;
use std::time::Duration;

mod matrix;
use matrix::*;

fn create_spi() -> std::io::Result<Spidev> {
    let mut spi = Spidev::open("/dev/spidev0.0")?;
    let options = SpidevOptions::new()
         .bits_per_word(8)
         .max_speed_hz(20_000)
         .mode(SpiModeFlags::SPI_MODE_0)
         .build();
    spi.configure(&options)?;
    Ok(spi)
}

fn main() {
    println!("running");

    let spi = create_spi().unwrap();
    let mut matrix = Matrix{
        spi,
        devices: 4,
    };

    matrix.init().unwrap();

    matrix.draw_raw(0x01,
        [
            0b11111111,
            0b10000001,
            0b10000001,
            0b10011001,
            0b10011001,
            0b10000001,
            0b10000001,
            0b11111111
        ])
        .unwrap();

    sleep(Duration::from_secs(3));
    matrix.power_off().unwrap();
}

Just looking at the first display everything works just right, but these are the problems:

  • on the second display every pixel is lit
  • the third display is fully unlit just as expected
  • the "bitmap" is drawn on display 1 and 4

I think the problem is how I send the data via SPI but I am not sure.

What do I have to for it to work?



from Recent Questions - Stack Overflow https://ift.tt/3z5zlYJ
https://ift.tt/eA8V8J

Apply for loop or sapply on multiple columns in R

I have data like wherein A* represents the place with time format (01:01) as column names and the row names like 1C or 9D represent the individual ID.

structure(list(V1 = c("1C", "9D", "9F", "9H", "9S", "9T", "9Y"
), `A*01:01` = c(NA, NA, "1", NA, NA, NA, NA), `A*02:01` = c(NA, 
NA, "1", NA, NA, NA, NA), `A*02:02` = c(NA, NA, "1", NA, NA, 
NA, NA), `A*02:03` = c(NA, NA, "1", NA, NA, NA, NA), `A*02:05` = c(NA, 
NA, NA, NA, NA, NA, "1"), `A*02:06` = c(NA, NA, NA, NA, NA, NA, 
"1"), `A*03:01` = c(NA, NA, "1", NA, NA, NA, NA), `A*11:01` = c(NA, 
NA, NA, NA, NA, NA, "1"), `A*11:02` = c(NA, NA, NA, NA, NA, NA, 
"1"), `A*23:01` = c(NA, NA, NA, NA, "1", NA, NA), `A*23:02` = c(NA, 
NA, NA, NA, "1", NA, NA), `A*24:02` = c(NA, NA, NA, NA, "1", 
NA, NA), `A*24:03` = c(NA, NA, NA, NA, "1", NA, NA), `A*25:01` = c(NA, 
NA, NA, NA, NA, NA, "1"), `A*26:01` = c(NA, NA, NA, NA, NA, NA, 
"1"), `A*29:01` = c(NA, NA, NA, NA, NA, "1", NA), `A*29:02` = c(NA, 
NA, NA, NA, NA, "1", NA), `A*30:01` = c(NA, NA, NA, NA, "1", 
NA, NA), `A*30:02` = c(NA, NA, NA, NA, "1", NA, NA), `A*31:01` = c(NA, 
NA, NA, NA, NA, "1", NA), `A*32:01` = c(NA, NA, "1", NA, NA, 
NA, NA), `A*33:01` = c(NA, NA, NA, NA, NA, "1", NA), `A*33:03` = c(NA, 
NA, NA, NA, NA, "1", NA), `A*34:01` = c(NA, NA, NA, NA, NA, NA, 
"1"), `A*34:02` = c(NA, NA, NA, NA, NA, NA, "1"), `A*36:01` = c(NA, 
NA, "1", NA, NA, NA, NA), `A*43:01` = c(NA, NA, NA, NA, NA, NA, 
"1"), `A*66:01` = c(NA, NA, NA, NA, NA, NA, "1"), `A*66:02` = c(NA, 
NA, NA, NA, NA, NA, "1"), `A*68:01` = c(NA, NA, NA, NA, NA, NA, 
"1"), `A*68:02` = c(NA, NA, NA, NA, NA, NA, "1"), `A*69:01` = c(NA, 
NA, NA, NA, NA, NA, "1"), `A*74:01` = c(NA, NA, "1", NA, NA, 
NA, NA), `A*80:01` = c(NA, NA, "1", NA, NA, NA, NA), `B*07:02` = c(NA, 
NA, NA, NA, NA, NA, "1"), `B*07:03` = c(NA, NA, NA, NA, NA, NA, 
"1"), `B*08:01` = c(NA, "1", NA, NA, NA, NA, NA), `B*13:01` = c(NA, 
NA, NA, NA, NA, NA, "1"), `B*13:02` = c(NA, NA, NA, NA, NA, NA, 
"1"), `B*14:01` = c(NA, NA, NA, NA, NA, NA, "1"), `B*14:02` = c(NA, 
NA, NA, NA, NA, NA, "1"), `B*14:05` = c(NA, NA, NA, NA, NA, NA, 
"1"), `B*14:06` = c(NA, NA, NA, NA, NA, NA, "1"), `B*15:01` = c(NA, 
NA, NA, NA, NA, NA, "1"), `B*15:02` = c(NA, NA, NA, NA, NA, NA, 
"1"), `B*15:03` = c(NA, NA, NA, NA, NA, NA, "1"), `B*15:10` = c(NA, 
NA, NA, NA, NA, NA, "1"), `B*15:11` = c(NA, NA, NA, NA, NA, NA, 
"1"), `B*15:12` = c(NA, NA, NA, NA, NA, NA, "1"), `B*15:13` = c(NA, 
NA, NA, NA, NA, NA, "1"), `B*15:16` = c(NA, NA, NA, NA, NA, NA, 
"1"), `B*15:18` = c(NA, NA, NA, NA, NA, NA, "1"), `B*18:01` = c(NA, 
NA, NA, "1", NA, NA, NA), `B*27:03` = c(NA, NA, NA, "1", NA, 
NA, NA), `B*27:05` = c(NA, NA, NA, "1", NA, NA, NA), `B*27:08` = c(NA, 
NA, NA, "1", NA, NA, NA), `B*35:01` = c(NA, NA, NA, NA, NA, NA, 
"1"), `B*35:08` = c(NA, NA, NA, NA, NA, NA, "1"), `B*37:01` = c(NA, 
NA, NA, "1", NA, NA, NA), `B*38:01` = c(NA, NA, NA, NA, NA, NA, 
"1"), `B*39:01` = c(NA, NA, NA, NA, NA, NA, "1"), `B*39:05` = c(NA, 
NA, NA, NA, NA, NA, "1"), `B*40:01` = c(NA, NA, NA, "1", NA, 
NA, NA), `B*40:02` = c(NA, NA, NA, "1", NA, NA, NA), `B*40:05` = c(NA, 
NA, NA, "1", NA, NA, NA), `B*40:06` = c(NA, NA, NA, "1", NA, 
NA, NA), `B*41:01` = c(NA, NA, NA, "1", NA, NA, NA), `B*41:02` = c(NA, 
NA, NA, "1", NA, NA, NA), `B*42:01` = c(NA, NA, NA, NA, NA, NA, 
"1"), `B*44:02` = c(NA, NA, NA, NA, NA, NA, "1"), `B*44:03` = c(NA, 
NA, NA, NA, NA, NA, "1"), `B*45:01` = c(NA, NA, NA, "1", NA, 
NA, NA), `B*46:01` = c(NA, NA, NA, NA, NA, NA, "1"), `B*47:01` = c(NA, 
NA, NA, NA, NA, NA, "1"), `B*48:01` = c(NA, NA, NA, NA, NA, NA, 
"1"), `B*49:01` = c(NA, NA, NA, "1", NA, NA, NA), `B*50:01` = c(NA, 
NA, NA, "1", NA, NA, NA), `B*51:01` = c(NA, NA, NA, NA, NA, NA, 
"1"), `B*51:02` = c(NA, NA, NA, NA, NA, NA, "1"), `B*52:01` = c(NA, 
NA, NA, NA, NA, NA, "1"), `B*53:01` = c(NA, NA, NA, NA, NA, NA, 
"1"), `B*54:01` = c(NA, NA, NA, NA, NA, NA, "1"), `B*55:01` = c(NA, 
NA, NA, NA, NA, NA, "1"), `B*56:01` = c(NA, NA, NA, NA, NA, NA, 
"1"), `B*57:01` = c(NA, NA, NA, NA, NA, NA, "1"), `B*57:03` = c(NA, 
NA, NA, NA, NA, NA, "1"), `B*58:01` = c(NA, NA, NA, NA, NA, NA, 
"1"), `B*59:01` = c(NA, NA, NA, NA, NA, NA, "1"), `B*67:01` = c(NA, 
NA, NA, NA, NA, NA, "1"), `B*73:01` = c(NA, NA, NA, "1", NA, 
NA, NA), `B*78:01` = c(NA, NA, NA, NA, NA, NA, "1"), `B*81:01` = c(NA, 
NA, NA, NA, NA, NA, "1"), `B*82:01` = c(NA, NA, NA, NA, NA, NA, 
"1"), `B*82:02` = c(NA, NA, NA, NA, NA, NA, "1"), `C*01:02` = c("1", 
NA, "1", NA, NA, NA, NA), `C*02:02` = c("1", NA, NA, NA, NA, 
NA, "1"), `C*02:10` = c("1", NA, NA, NA, NA, NA, "1"), `C*03:02` = c(NA, 
NA, NA, NA, NA, NA, "1"), `C*03:03` = c(NA, NA, NA, NA, NA, NA, 
"1"), `C*03:04` = c(NA, NA, NA, NA, NA, NA, "1"), `C*04:01` = c(NA, 
NA, NA, NA, "1", NA, NA), `C*04:03` = c(NA, NA, NA, NA, NA, NA, 
"1"), `C*05:01` = c("1", NA, NA, NA, NA, NA, "1"), `C*06:02` = c("1", 
"1", NA, NA, NA, NA, NA), `C*07:01` = c("1", "1", NA, NA, NA, 
NA, NA), `C*07:02` = c("1", "1", NA, NA, NA, NA, NA), `C*07:04` = c("1", 
"1", NA, NA, NA, NA, NA), `C*08:01` = c("1", NA, NA, NA, NA, 
NA, "1"), `C*08:02` = c("1", NA, NA, NA, NA, NA, "1"), `C*12:02` = c("1", 
NA, NA, NA, NA, NA, "1"), `C*12:03` = c("1", NA, NA, NA, NA, 
NA, "1"), `C*14:02` = c("1", NA, NA, NA, "1", NA, NA), `C*15:02` = c("1", 
NA, NA, NA, NA, NA, "1"), `C*16:01` = c("1", NA, NA, NA, NA, 
NA, "1"), `C*17:01` = c(NA, NA, NA, NA, NA, NA, "1"), `C*18:01` = c("1", 
"1", NA, NA, NA, NA, NA), `C*18:02` = c("1", "1", NA, NA, NA, 
NA, NA)), row.names = c("1C", "9D", "9F", "9H", "9S", "9T", "9Y"
), class = "data.frame")

I am using the following code to process the data, which is working fine for column 2. But I have 16000 columns and 400 rows in my real data. I want to use "for loop" or "sapply" in R to perform processing. A quick solution is much appreciated.

LA <- dat[!is.na(dat[,2]),]
LA<-LA[,1]
res <- gsub("[[:digit:]]","",LA)
pos <- gsub("[[:alpha:]]","",LA)
LA_sep <- data.frame(res, pos)
LA_sep$res <- paste0(LA_sep$res, "&")
LA_sep$pos <- paste0(LA_sep$pos, "&")
LA_sep <- as.data.frame(t(LA_sep))
LA_sep <- apply(LA_sep[1:ncol(LA_sep)], 1, function(x) paste(na.omit(x), collapse = "")) ## nrow(ma) ## ncol(ma) ## NCOL(1:12) ## NROW(1:12)
write.csv(LA_sep, "2.csv")

When I run the above code on big data, I got the following output for 2nd column. So, it is very difficult to do this for each column manually or without a loop for big data. Every output should be saved as column names as a separate file.

res F&K&M&Q&E&R&A&R&N&A&N&N&H&N&M&H&S&A&N&T&N&N&G&T&G&T&T&TL&D&I&I&Y&F&R&D&M&I&K&K&R&A&H&H&A&H&A&R&R&R&G&D&G&P&I&E&L

pos 9&44&45&62&63&65&69&65&66&69&66&66&70&66&67&70&71&76&77&80&77&77&79&80&79&80&80&80&81&90&95&97&99&109&114&116&138&142&144&144&145&149&151&151&152&151&152&156&163&163&167&166&167&193&194&275&276



from Recent Questions - Stack Overflow https://ift.tt/3qurvnx
https://ift.tt/eA8V8J

Pyinstaller and pygubu's calendar frame cause a problem

I made a pygubu python application, and decided I wanted to freeze it, after troubleshooting some simple problems, I ran into something I couldn't fix:

Traceback (most recent call last):
  File "main.py", line 138, in <module>
  File "pygubu\__init__.py", line 30, in __init__
  File "main.py", line 38, in _create_ui
  File "pygubu\builder\__init__.py", line 166, in get_object
  File "pygubu\builder\__init__.py", line 215, in _realize
  File "pygubu\builder\__init__.py", line 215, in _realize
  File "pygubu\builder\__init__.py", line 225, in _realize
Exception: Class "pygubu.builder.widgets.calendarframe" not mapped
[13108] Failed to execute script 'main' due to unhandled exception!

I even imported a bunch of pyugubu modules to try to fix this, and it still didn't work:

from pygubu import builder
from pygubu.builder import ttkstdwidgets
from pygubu.builder import widgets
from pygubu.widgets import calendarframe
from pygubu import widgets

This probably doesn't matter, but I froze it with auto-py-to-exe. I've tried making it a console application, folder application, and both at the same time, but it still didn't work.

Thank you in advance.



from Recent Questions - Stack Overflow https://ift.tt/3HedNfd
https://ift.tt/eA8V8J

Setting tabBarAppearance makes it so UITabBarItem doesn't respect `imageInsets`

When I set the UITabBar's appearance, it makes it so the UITabBarItem's imageInsets and titlePositionAdjustment aren't respected anymore on iOS 15. Removing the line [UITabBar appearance].standardAppearance = tabBarAppearance; makes it so the image and label lineup but the background color can't be set. Has anyone run into something like this and solved it?

Code:

UITabBarAppearance *tabBarAppearance = [[UITabBarAppearance alloc] init];
[tabBarAppearance configureWithOpaqueBackground];
[UITabBar appearance].standardAppearance = tabBarAppearance;
[UITabBar appearance].scrollEdgeAppearance = tabBarAppearance;

static let tabBarImageInsets: UIEdgeInsets = UIEdgeInsets(top: 4.0, left: 0, bottom: -4.0, right: 0)
static let titlePositionAdjustmentValue: UIOffset = UIOffset(horizontal: 0.0, vertical: -8.0)
tabBarItem.imageInsets = tabBarImageInsets
tabBarItem.titlePositionAdjustment = titlePositionAdjustmentValue

Images:

Tab Bar with appearance and misaligned label

Tab Bar without appearance, properly aligned label and image, and no background



from Recent Questions - Stack Overflow https://ift.tt/3mrtAQ5
https://ift.tt/eA8V8J

2021-12-28

Google Chrome Error Message: "Uncaught (in promise) DOMException: play()"

In Google Chrome, I get this error:

Uncaught (in promise) DOMException: play()

My php code:

<a href="javascript:void(0);" onclick="aj('player')"></a>

My js code:

case "player":
    var request = new XMLHttpRequest(); 
    var fileId = info.match(/\/view\/([a-zA-Z0-9]+)/g)[0].substr(6),
        request.onload = successListener;  
        function successListener() {  
    var data = JSON.parse(this.responseText);  
    var player = '<iframe width="668" height="100" autoplay="true" frameBorder="0" src="https://'music.com/getEmbedPlayer/'+ fileId +'?width=668&autoplay=true&date='+ data.uploadDate +'"></iframe>';


from Recent Questions - Stack Overflow https://ift.tt/311Wyym
https://ift.tt/eA8V8J

Exclude null values from GraphQL query

Disclaimer, I am still a noob in GraphQL.

Apologies for the long post, but I need to give as much information as possible to explain my issue.

I am currently trying to query my Neo4j using GraphQL and then tabulate the data using ReTool.

I managed to do most of the work but when I query the database, I also get the null values.

You can access the sandbox below to test yourself a probable solution. https://codesandbox.io/s/great-marco-coy3k

The query I am using is the following:

query {
  people{
    child{
      firstname{
        name
      }
      middlename{
        name
      }
      lastname{
        name
      }
      phone{
        name
      }
      email{
        name
      }
      dob{
        name
      }
      eid{
        name
      }
    }
  }
}

Response

As you can see, I get back a mixture of null and none-null values.

What I would like to get back is the children that has data in them and ignore the null ones. The reason for that is when I try to populate my table, the null values appear there too.

I need to stress on the fact that I'd still need to retrieve "child" even if one or more of the objects are null as depicted in the image below:

The middlename is null which is completely fine

While doing some research, I noticed that other people have the same problem I am facing (example), but most replies said there is no direct solution to this problem, many talked about adjusting the resolver which I am not sure how to do. The resolver file was already set by Neo4j Sandbox automatically and I don't know how to adjust it.

To provide more information regarding the root cause of the problem, you can check the Neo4j schema below:

Neo4j Schema

As you can see, the two-person nodes that have the relationship MASTER_OF and CHILD_OF are similar. When I query people{child{firstname name}...} I get the value of the node that has a IN CHILD_OF relationship and null for the node that has IN MASTER_OF relationship.



from Recent Questions - Stack Overflow https://ift.tt/3sKe6ue
https://ift.tt/3pxM0Re

How are nodes and edges connected in GraphQL?

I am using https://arrows.app/ to create a basic network:

enter image description here

And the resulting GraphQL it creates is:

type Person {
  Name: Dante Alighieri
  wroteBook: Book @relationship(type: "WROTE", direction: OUT)
}

type Book {
  Title: The Inferno
  personWrote: Person @relationship(type: "WROTE", direction: IN)
  personReviewed: Person @relationship(type: "REVIEWED", direction: IN)
  personRead: Person @relationship(type: "READ", direction: IN)
}

type Person {
  Name: Harold Bloom
  reviewedBook: Book @relationship(type: "REVIEWED", direction: OUT)
  reviewedBook: Book @relationship(type: "REVIEWED", direction: OUT)
}
...

How do we know in GraphQL that these two relationships are 'linked'?

type Person {
  Name: Dante Alighieri
  wroteBook: Book @relationship(type: "WROTE", direction: OUT)
}
type Book {
  Title: The Inferno
  personWrote: Person @relationship(type: "WROTE", direction: IN)
}

Does sequential ordering in GraphQL imply a relationship, as there is no ID or mention of 'The Inferno' in the 'Person[@Name=Dante Alighieri].wroteBook' entry. How do we know, for example, that it doesn't refer to a later entry, such as:

type Book {
  Title: The Tempest
  personWrote: Person @relationship(type: "WROTE", direction: IN)
}


from Recent Questions - Stack Overflow https://ift.tt/3ptkxQt
https://ift.tt/3ExHSov

AttributeError: can't set attribute when trying to increment X value of a circle in sympy[2] I want 3Pattern

I want 3Pattern ①②➂

https://docs.sympy.org/latest/modules/geometry/points.html#sympy.geometry.point.Point2D.x

AttributeError: can't set attribute when trying to increment X value of a circle in sympy

from sympy import Point, Circle
def myPointSubs(PT,x,y):
    return PT.translate(x=-PT.x+x,y=-PT.y+y)
test_center=Point (1,2)
test_circle=Circle(myPointSubs(test_center,2,test_center.y), 1)
# test_circle=Circle(myPointSubs(test_center,2,), 1) #① I want Circle(Point2D(2,2), 1)
# test_circle=Circle(myPointSubs(test_center,,1), 1) #② I want Circle(Point2D(1,1), 1)
# test_circle=Circle(myPointSubs(test_center,, ), 1) #➂ I want Circle(Point2D(1,2), 1)
print("#",test_circle)
# Circle(Point2D(2, 2), 1)

test_circle=Circle(myPointSubs(test_center,2,), 1)

TypeError: myPointSubs() missing 1 required positional argument: 'y'

(2021-12-28)

from sympy import Point
def change(pt,x=None,y=None):
    return pt.func(pt.x if x is None else x, pt.y if y is None else y)
print("#",change(Point(1, 2), y=3))
print("#",change(Point(1, 2), x=3))
print("#",change(Point(1, 2), 3))
print("#",change(Point(1, 2), 2, 1))
print("")
print("#1",change(Point(1, 2)   ))
# print("#2",change(Point(1, 2),, ))         #SyntaxError: invalid syntax
# print("#3",change(Point(1, 2),,4))         #SyntaxError: invalid syntax
print("#4",change(Point(1, 2), x=3,y=4))
print("#5",change(Point(1, 2), y=4,x=3))
print("#6",change(Point(1, 2),3,))

# Point2D(1, 3)
# Point2D(3, 2)
# Point2D(3, 2)
# Point2D(2, 1)

#1 Point2D(1, 2)
#     print("#2",change(Point(1, 2),, ))         #SyntaxError: invalid syntax
#                                   ^
# SyntaxError: invalid syntax
#     print("#3",change(Point(1, 2),,4))         #SyntaxError: invalid syntax
#                                   ^
# SyntaxError: invalid syntax
#4 Point2D(3, 4)
#5 Point2D(3, 4)
#6 Point2D(3, 2)

google > python none default argument

from sympy import *
def change(pt,x=None,y=None):
    return pt.func(pt.x if x is None else x, pt.y if y is None else y)
test_center =Point (1,2)
test_circle =Circle(change(test_center,2,test_center.y), 1)
test_circle1=Circle(change(test_center,x=2),1) #① I want Circle(Point2D(2,2), 1)
test_circle2=Circle(change(test_center,y=1),1) #② I want Circle(Point2D(1,1), 1)
test_circle3=Circle(change(test_center    ),1) #➂ I want Circle(Point2D(1,2), 1)
print("# ",test_circle )
print("#1",test_circle1)
print("#2",test_circle2)
print("#3",test_circle3)

#  Circle(Point2D(2, 2), 1)
#1 Circle(Point2D(2, 2), 1)
#2 Circle(Point2D(1, 1), 1)
#3 Circle(Point2D(1, 2), 1)


from Recent Questions - Stack Overflow https://ift.tt/3HeFeFU
https://ift.tt/eA8V8J

AfxBeginThread no work when attatch it in VC6 [closed]

I have a problem about thread. I develop a dll and try useing AfxbeginThread in VC6.

AfxBeginThread(ReciveImg, (LPVOID)this,THREAD_PRIORITY_NORMAL,0,0,NULL);

and ReciveImg function

ReciveImg()
{
   while(1)
   {
     //Recive image...
   }
}

but ReciveImg fucntion no work when I attached a process. Anybody can help me? Thank you.



from Recent Questions - Stack Overflow https://ift.tt/3EuoVD3
https://ift.tt/eA8V8J

Why application crashes when using express-rate-limit?

I'm using express-rate-limit package version 6.0.1 to limit hits of request an I also had used express-rate-limit documentation found on https://www.npmjs.com/package/express-rate-limit

However when I use this in my app, my application crashes. I"m not understanding what is going on here. I have search allot for a conclusion but without any results. Can someone give me an idea of what I'm doing wrong???

...

//Load env vars
dotenv.config({ path: "./config/config.env" });

//Connect to database
connectDB();

const app = express();

//Set Static folder
app.use(express.static(path.join(__dirname, "public")));

// Body Parser
app.use(express.json());

// Cookie parser
app.use(cookieParser());

//Dev logging middleware
if (process.env.NODE_ENV === "development") {
  app.use(morgan("dev"));
}

// File uploading
app.use(fileUpload());

// Sanitize data
app.use(mongoSanitize());

// Set security headers
app.use(helmet());

// Prevent XSS attacks
app.use(xss());

//Rate limiting
const limiter = rateLimit({
  windowMs: 10 * 60 * 1000, // 10 mins
  max: 1,
});

app.use(limiter);

// Prevent http param pollution
app.use(hpp());

app.use(errorHandler);

const PORT = process.env.PORT || 5000;

const server = app.listen(
  PORT,
  console.log(
    `Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold
  )
);

//Handle unhandled promise rejections
process.on("unhandledRejection", (err, promise) => {
  console.log(`Error: ${err.message}`.red);
  // Close server & exit process
  server.close(() => process.exit(1));
});

Screenshot of error message

Merry Christmas gurus and keep on coding!!!



from Recent Questions - Stack Overflow https://ift.tt/3szpx8d
https://ift.tt/3mY4xob

SwiftUI: Filtered list indices are not corresponding to new list

I have a Country model and then a JSON list of countries. I have creating the list by using a ForEach. If the search box is empty, the value of filteredCountries is just the whole list, otherwise the list only contains countries that include whats in the search box.
The problem is that when the list is filtered and I click to favorite an item, the wrong country is favorited. The indices don't match the filtered items, they still go in sequential order: 0,1,2,3 etc.

Country

import Foundation

struct Country: Codable, Identifiable {
    var id: String {image}
    let display_name: String
    let searchable_names: [String]
    let image: String
    var favorite: Bool
    var extended: Bool
}

ContentView

var filteredCountries : [Country] {
    if (searchText.isEmpty) {
        return countries;
    } else {
        return countries.filter { $0.display_name.contains(searchText) }
    }
}

          NavigationView {
                ScrollView {
                    ForEach(Array(filteredCountries.enumerated()), id: \.1.id) { (index,country) in
                        
                        LazyVStack {
                            ZStack(alignment: .bottom) {
                                Image("\(country.image)-bg")
                                    .resizable()
                                    .scaledToFit()
                                    .edgesIgnoringSafeArea(.all)
                                    .overlay(Rectangle().opacity(0.2))
                                    .mask(
                                        LinearGradient(gradient: Gradient(colors: [Color.black, Color.black.opacity(0)]), startPoint: .center, endPoint: .bottom)
                                    )
                                
                                
                                HStack {
                                    NavigationLink(
                                        destination: CountryView(country: country),
                                        label: {
                                            HStack {
                                                Image(country.image)
                                                    .resizable()
                                                    .frame(width: 50, height: 50)
                                                Text(country.display_name)
                                                    .foregroundColor(Color.black)
                                                    .padding(.leading)
                                                Spacer()
                                            }
                                            .padding(.top, 12.0)
                                            
                                        }
                                    ).buttonStyle(FlatLinkStyle())
                                    if country.favorite {
                                        Image(systemName: "heart.fill").foregroundColor(.red).onTapGesture {
                                            print(country)
                                            countries[index].favorite.toggle()
                                        }
                                        .padding(.top, 12)
                                    } else {
                                        Image(systemName: "heart").foregroundColor(.red).onTapGesture {
                                            print(country)

                                            countries[index].favorite.toggle()
                                        }
                                        .padding(.top, 12)
                                    }
                                    
                                }
                                .padding(.horizontal, 16.0)
                            }
                        }
                        .padding(.bottom, country.extended ? 220 : 0)
                        .onTapGesture {
                            withAnimation(.easeInOut(duration: 0.4)) {
                                self.countries[index].extended.toggle();
                                
                            }
                        }
                    }
                }
                .frame(maxWidth: bounds.size.width)
                .navigationTitle("Countries")
                .font(Font.custom("Avenir-Book", size: 28))


            }
            .navigationViewStyle(StackNavigationViewStyle())
            .searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always), prompt: "Search Country")           


from Recent Questions - Stack Overflow https://ift.tt/3z5Qm4V
https://ift.tt/eA8V8J

Template function with template argument parametrized over int

Without using the features of C++11 and higher (I will accept them but would prefer C++98),

I have to write a template function with argument T which is an STL container of ints. It receives such a container along with another int which it tries to search for,

Right now I have this but it doesn't compile:

template <template<int> class T>
T::iterator easyfind(T &container, int val)
{
    T::iterator it = container.begin();
    for ( ; it != container.end(); it++)
        if (val == *it)
            break ;
    return (it);
}

I wonder if I can somehow force the T parameter to always be a class template that is parametrized over integers... I tried writing T<int> but it still doesn't compile.



from Recent Questions - Stack Overflow https://ift.tt/343GFZx
https://ift.tt/eA8V8J

Using buttons in Bottom navigation crashes app

App Crashes when using button, link and .isGone function. It was working before but error occurred when switched to bottom navigation and fragments.

Could anyone explain what is happening.

Error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.dmat.zerowaste, PID: 14673
    java.lang.NullPointerException
        at com.dmat.zerowaste.OrganicWasteFragment.onCreate(OrganicWasteFragment.kt:41)
        at androidx.fragment.app.Fragment.performCreate(Fragment.java:2949)
        at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:475)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:278)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
        at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:524)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:245)
        at android.app.ActivityThread.main(ActivityThread.java:8004)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:631)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:978)

File:

package com.dmat.zerowaste

import android.content.Intent
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView

import androidx.core.view.isGone
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.organic_waste_fragment_page.*

class OrganicWasteFragment : Fragment(R.layout.activity_recycle_page) {

    /*override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.organic_waste_fragment_page, container, false)
    }*/

    /*override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?): View? {
        val rootView = inflater.inflate(R.layout.organic_waste_fragment_page, container, false)
        return rootView
    }*/


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


        val compost_butt: Button = view?.findViewById(R.id.compost_butt)!!
        val animal_feed_butt: Button = view?.findViewById(R.id.animal_feed_butt)!!
        val animal_feed_content: View? = view?.findViewById(R.id.animal_feed_content)
        val rendering_butt: Button = view?.findViewById(R.id.rendering_butt)!!
        val rendering_content: View? = view?.findViewById(R.id.rendering_content)!!
        //val rapid_fermentation_butt: Button = view?.findViewById(R.id.fermentation_butt)!!
        val fermentation_link: TextView = view?.findViewById(R.id.fermentation_link)!!

        fermentation_link.setMovementMethod(LinkMovementMethod.getInstance())

        /*animal_feed_content.isGone = true
        rendering_content!!.isGone = true*/

        /*compost_butt.setOnClickListener {
            val compostIntent = Intent(context, composting_page::class.java)
            startActivity(compostIntent)

            animal_feed_butt.setCompoundDrawablesRelativeWithIntrinsicBounds(
                R.drawable.animal_feed_icon,
                0,
                R.drawable.plus,
                0
            )

            rendering_butt.setCompoundDrawablesRelativeWithIntrinsicBounds(
                R.drawable.rendering_icon,
                0,
                R.drawable.plus,
                0
            )

            animal_feed_content.isGone = true
            rendering_content.isGone = true

        }*/

        /*animal_feed_butt.setOnClickListener {
            animal_feed_butt.setCompoundDrawablesRelativeWithIntrinsicBounds(
                R.drawable.animal_feed_icon,
                0,
                R.drawable.minus_icon,
                0
            )

            animal_feed_content.isGone = false
            rendering_content.isGone = true

            rendering_butt.setCompoundDrawablesRelativeWithIntrinsicBounds(
                R.drawable.rendering_icon,
                0,
                R.drawable.plus,
                0
            )
        }

        rendering_butt.setOnClickListener {
            rendering_butt.setCompoundDrawablesRelativeWithIntrinsicBounds(
                R.drawable.rendering_icon,
                0,
                R.drawable.minus_icon,
                0
            )

            rendering_content.isGone = false
            animal_feed_content.isGone = true

            animal_feed_butt.setCompoundDrawablesRelativeWithIntrinsicBounds(
                R.drawable.animal_feed_icon,
                0,
                R.drawable.plus,
                0
            )
        }*/

    }
}


from Recent Questions - Stack Overflow https://ift.tt/32A04R2
https://ift.tt/eA8V8J

Automatically update local Git repository

I want to clone a GitHub repository that's not mine, and keep this local cloned repository always up to date, that is, whenever a new commit is made upstream, my local repository is also updated automatically.

My use case is CI/CD, I need to clone repositories several times in my jobs, if I had a local GitHub cache it'd be way faster.

Is this possible?



from Recent Questions - Stack Overflow https://ift.tt/3EC8Nzj
https://ift.tt/eA8V8J

parallelStream for time consuming methods [closed]

I have something like this:

// sequential version
for(var t: tasks){ 
    // run() is a time consuming method (approx. 20-30 seconds)
    t.run();
}

I have approx. 1000 (independent) tasks and the above needs approx. 1000 x 25 seconds. The run()-method is only CPU intensive (there are no I/O Operations involved).

I switched to parallelStream:

// parallel version
tasks.parallelStream().forEach(Task:run);

and measured that with parallelStream each task.run() needs approx. 15-20 seconds. So it's definitely a little faster than using the sequential version.

Can I use parallelStream (with its fork-join) for such long running operations (each task.run() needs approx. 15-20 seconds) or would it be better to use executorServices with custom thread pools (for example, because of system stability, performance, etc.)?

What I want to know if there is any harm when using parallelStream (fork-join) for such long running tasks. I have thought that fork-join should only be used for very short running tasks (max. 1-2 seconds), but I am not sure if so and why.



from Recent Questions - Stack Overflow https://ift.tt/3HhdrVq
https://ift.tt/eA8V8J

2021-12-27

How to convert XML to String with JAXB and spring-boot?

When I run a mvn spring-boot:run on the folder that has the pom.xml file the application starts and serializes a POJO into a XML correctly, but when I do it by going to the target folder and starting it by using java -jar in the jar file I get javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath caused by .java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory.

In my maven I have the following JAXB dependencies:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>

<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.3.1</version>
    <scope>runtime</scope>
</dependency>

Here's the method that serializes a POJO into XML:

private static final Pattern REMOVE_HEADER = Pattern.compile("\\<\\?xml(.+?)\\?\\>");

public static String toXML(final Object data) {
    try {
        final var jaxbMarshaller = JAXBContext.newInstance(data.getClass()).createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        final var sw = new StringWriter();
        jaxbMarshaller.marshal(data, sw);
        return XMLUtils.REMOVE_HEADER.matcher(sw.toString()).replaceAll(StringUtils.EMPTY).strip();
    } catch (final JAXBException e) {
        XMLUtils.LOGGER.error("Error while converting POJO to XML. ERROR: {}.", e.getMessage(), e);
    }

    return "";
}

Here's the log when I start the application with java -jar:

javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:278)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:421)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
    at br.com.site.system.shared.util.XMLUtils.toXML(XMLUtils.java:56)
    at br.com.site.system.shared.util.FinanTokenEncoderUtils.encodeBase64(FinanTokenEncoderUtils.java:41)
    at br.com.site.system.converter.PlanConverter.lambda$convert$0(PlanConverter.java:84)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1654)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ReduceOps$ReduceTask.doLeaf(ReduceOps.java:952)
    at java.base/java.util.stream.ReduceOps$ReduceTask.doLeaf(ReduceOps.java:926)
    at java.base/java.util.stream.AbstractTask.compute(AbstractTask.java:327)
    at java.base/java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:746)
    at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
    at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.helpCC(ForkJoinPool.java:1115)
    at java.base/java.util.concurrent.ForkJoinPool.awaitJoin(ForkJoinPool.java:1687)
    at java.base/java.util.concurrent.ForkJoinTask.doInvoke(ForkJoinTask.java:411)
    at java.base/java.util.concurrent.ForkJoinTask.invoke(ForkJoinTask.java:736)
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateParallel(ReduceOps.java:919)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:233)
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
    at br.com.site.system.converter.PlanConverter.convert(PlanConverter.java:90)
    at br.com.site.system.converter.OperationConverter.lambda$convert$0(OperationConverter.java:59)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1654)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.Nodes$SizedCollectorTask.compute(Nodes.java:1886)
    at java.base/java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:746)
    at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
    at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
    at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
    at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
    at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177)
Caused by: java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:122)
    at javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:155)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:276)
    ... 35 common frames omitted

Here's an image of the generated spring-boot fat jar with the JAXB dependencies:

JAXB dependencies

And finally here's my dependency tree:

--- maven-dependency-plugin:3.2.0:tree (default-cli) @ system-infrastructure ---
br.com.site.system:system-infrastructure:jar:0.0.1-SNAPSHOT
+- br.com.site.system:system-core:jar:0.0.1-SNAPSHOT:compile
|  +- org.apache.commons:commons-lang3:jar:3.12.0:compile
|  +- javax.validation:validation-api:jar:2.0.1.Final:compile
|  +- javax.xml.bind:jaxb-api:jar:2.3.1:compile
|  |  \- javax.activation:javax.activation-api:jar:1.2.0:compile
|  \- org.glassfish.jaxb:jaxb-runtime:jar:2.3.5:runtime
|     +- org.glassfish.jaxb:txw2:jar:2.3.5:runtime
|     +- com.sun.istack:istack-commons-runtime:jar:3.0.12:runtime
|     \- com.sun.activation:jakarta.activation:jar:1.2.2:runtime
+- io.projectreactor:reactor-test:jar:3.4.12:test
|  \- io.projectreactor:reactor-core:jar:3.4.12:compile
|     \- org.reactivestreams:reactive-streams:jar:1.0.3:compile
+- org.junit.jupiter:junit-jupiter-api:jar:5.8.1:test
|  +- org.opentest4j:opentest4j:jar:1.2.0:test
|  +- org.junit.platform:junit-platform-commons:jar:1.8.1:test
|  \- org.apiguardian:apiguardian-api:jar:1.1.2:test
+- org.mockito:mockito-inline:jar:4.0.0:test
|  \- org.mockito:mockito-core:jar:4.0.0:test
|     +- net.bytebuddy:byte-buddy:jar:1.11.22:test
|     +- net.bytebuddy:byte-buddy-agent:jar:1.11.22:test
|     \- org.objenesis:objenesis:jar:3.2:test
+- org.pitest:pitest-junit5-plugin:jar:0.15:test
+- org.springframework.boot:spring-boot-starter-test:jar:2.6.1:test
|  +- org.springframework.boot:spring-boot-starter:jar:2.6.1:compile
|  |  +- org.springframework.boot:spring-boot:jar:2.6.1:compile
|  |  |  \- org.springframework:spring-context:jar:5.3.13:compile
|  |  |     +- org.springframework:spring-aop:jar:5.3.13:compile
|  |  |     \- org.springframework:spring-expression:jar:5.3.13:compile
|  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:2.6.1:compile
|  |  +- org.springframework.boot:spring-boot-starter-logging:jar:2.6.1:compile
|  |  |  +- ch.qos.logback:logback-classic:jar:1.2.7:compile
|  |  |  |  \- ch.qos.logback:logback-core:jar:1.2.7:compile
|  |  |  +- org.apache.logging.log4j:log4j-to-slf4j:jar:2.14.1:compile
|  |  |  |  \- org.apache.logging.log4j:log4j-api:jar:2.14.1:compile
|  |  |  \- org.slf4j:jul-to-slf4j:jar:1.7.32:compile
|  |  +- jakarta.annotation:jakarta.annotation-api:jar:1.3.5:compile
|  |  \- org.yaml:snakeyaml:jar:1.29:compile
|  +- org.springframework.boot:spring-boot-test:jar:2.6.1:test
|  +- org.springframework.boot:spring-boot-test-autoconfigure:jar:2.6.1:test
|  +- com.jayway.jsonpath:json-path:jar:2.6.0:test
|  |  +- net.minidev:json-smart:jar:2.4.7:test
|  |  |  \- net.minidev:accessors-smart:jar:2.4.7:test
|  |  |     \- org.ow2.asm:asm:jar:9.1:test
|  |  \- org.slf4j:slf4j-api:jar:1.7.32:compile
|  +- jakarta.xml.bind:jakarta.xml.bind-api:jar:2.3.3:compile
|  |  \- jakarta.activation:jakarta.activation-api:jar:1.2.2:compile
|  +- org.assertj:assertj-core:jar:3.21.0:test
|  +- org.hamcrest:hamcrest:jar:2.2:test
|  +- org.junit.jupiter:junit-jupiter:jar:5.8.1:test
|  |  +- org.junit.jupiter:junit-jupiter-params:jar:5.8.1:test
|  |  \- org.junit.jupiter:junit-jupiter-engine:jar:5.8.1:test
|  |     \- org.junit.platform:junit-platform-engine:jar:1.8.1:test
|  +- org.mockito:mockito-junit-jupiter:jar:4.0.0:test
|  +- org.skyscreamer:jsonassert:jar:1.5.0:test
|  |  \- com.vaadin.external.google:android-json:jar:0.0.20131108.vaadin1:test
|  +- org.springframework:spring-core:jar:5.3.13:compile
|  |  \- org.springframework:spring-jcl:jar:5.3.13:compile
|  +- org.springframework:spring-test:jar:5.3.13:test
|  \- org.xmlunit:xmlunit-core:jar:2.8.3:test
+- org.springframework.boot:spring-boot-starter-actuator:jar:2.6.1:compile
|  +- org.springframework.boot:spring-boot-actuator-autoconfigure:jar:2.6.1:compile
|  |  +- org.springframework.boot:spring-boot-actuator:jar:2.6.1:compile
|  |  \- com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar:2.13.0:compile
|  \- io.micrometer:micrometer-core:jar:1.8.0:compile
|     +- org.hdrhistogram:HdrHistogram:jar:2.1.12:compile
|     \- org.latencyutils:LatencyUtils:jar:2.0.3:runtime
+- org.springframework.boot:spring-boot-starter-validation:jar:2.6.1:compile
|  +- org.apache.tomcat.embed:tomcat-embed-el:jar:9.0.55:compile
|  \- org.hibernate.validator:hibernate-validator:jar:6.2.0.Final:compile
|     +- jakarta.validation:jakarta.validation-api:jar:2.0.2:compile
|     +- org.jboss.logging:jboss-logging:jar:3.4.2.Final:compile
|     \- com.fasterxml:classmate:jar:1.5.1:compile
+- org.springframework.boot:spring-boot-starter-webflux:jar:2.6.1:compile
|  +- org.springframework.boot:spring-boot-starter-json:jar:2.6.1:compile
|  |  +- com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.13.0:compile
|  |  \- com.fasterxml.jackson.module:jackson-module-parameter-names:jar:2.13.0:compile
|  +- org.springframework.boot:spring-boot-starter-reactor-netty:jar:2.6.1:compile
|  |  \- io.projectreactor.netty:reactor-netty-http:jar:1.0.13:compile
|  |     +- io.netty:netty-codec-http:jar:4.1.70.Final:compile
|  |     |  +- io.netty:netty-common:jar:4.1.70.Final:compile
|  |     |  +- io.netty:netty-buffer:jar:4.1.70.Final:compile
|  |     |  +- io.netty:netty-transport:jar:4.1.70.Final:compile
|  |     |  +- io.netty:netty-codec:jar:4.1.70.Final:compile
|  |     |  \- io.netty:netty-handler:jar:4.1.70.Final:compile
|  |     +- io.netty:netty-codec-http2:jar:4.1.70.Final:compile
|  |     +- io.netty:netty-resolver-dns:jar:4.1.70.Final:compile
|  |     |  +- io.netty:netty-resolver:jar:4.1.70.Final:compile
|  |     |  \- io.netty:netty-codec-dns:jar:4.1.70.Final:compile
|  |     +- io.netty:netty-resolver-dns-native-macos:jar:osx-x86_64:4.1.70.Final:compile
|  |     |  \- io.netty:netty-resolver-dns-classes-macos:jar:4.1.70.Final:compile
|  |     +- io.netty:netty-transport-native-epoll:jar:linux-x86_64:4.1.70.Final:compile
|  |     |  +- io.netty:netty-transport-native-unix-common:jar:4.1.70.Final:compile
|  |     |  \- io.netty:netty-transport-classes-epoll:jar:4.1.70.Final:compile
|  |     \- io.projectreactor.netty:reactor-netty-core:jar:1.0.13:compile
|  |        \- io.netty:netty-handler-proxy:jar:4.1.70.Final:compile
|  |           \- io.netty:netty-codec-socks:jar:4.1.70.Final:compile
|  +- org.springframework:spring-web:jar:5.3.13:compile
|  |  \- org.springframework:spring-beans:jar:5.3.13:compile
|  \- org.springframework:spring-webflux:jar:5.3.13:compile
+- net.logstash.logback:logstash-logback-encoder:jar:7.0.1:compile
|  \- com.fasterxml.jackson.core:jackson-databind:jar:2.13.0:compile
|     +- com.fasterxml.jackson.core:jackson-annotations:jar:2.13.0:compile
|     \- com.fasterxml.jackson.core:jackson-core:jar:2.13.0:compile
+- org.springdoc:springdoc-openapi-webflux-ui:jar:1.6.1:compile
|  +- org.springdoc:springdoc-openapi-webflux-core:jar:1.6.1:compile
|  |  \- org.springdoc:springdoc-openapi-common:jar:1.6.1:compile
|  |     +- io.swagger.core.v3:swagger-models:jar:2.1.11:compile
|  |     +- io.swagger.core.v3:swagger-annotations:jar:2.1.11:compile
|  |     +- io.swagger.core.v3:swagger-integration:jar:2.1.11:compile
|  |     |  \- io.swagger.core.v3:swagger-core:jar:2.1.11:compile
|  |     |     \- com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:jar:2.13.0:compile
|  |     \- io.github.classgraph:classgraph:jar:4.8.116:compile
|  +- org.webjars:swagger-ui:jar:4.1.3:compile
|  \- org.webjars:webjars-locator-core:jar:0.48:compile
\- org.mapstruct:mapstruct:jar:1.4.2.Final:compile

And finally, here are my model classes:

import java.util.Objects;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "finans")
@XmlAccessorType(XmlAccessType.FIELD)
public class FinanTokenDTO {

    @XmlAttribute
    private String pln;

    @XmlAttribute
    private String ope;

    @XmlAttribute
    private String mod;

    @XmlAttribute
    private String mis;

    @XmlAttribute
    private String val;

    @XmlAttribute
    private String car;

    @XmlAttribute
    private String dti;

    @XmlAttribute
    private String dtf;

    @XmlAttribute
    private String ota;

    @XmlElement
    private FinanDTO finan;

    public FinanTokenDTO() {
        super();
    }

    public FinanTokenDTO(final String plnParam, final String opeParam, final String modParam, final String misParam,
            final String valParam, final String carParam, final String dtiParam, final String dtfParam,
            final String otaParam, final FinanDTO finanParam) {
        this();
        this.pln = plnParam;
        this.ope = opeParam;
        this.mod = modParam;
        this.mis = misParam;
        this.val = valParam;
        this.car = carParam;
        this.dti = dtiParam;
        this.dtf = dtfParam;
        this.ota = otaParam;
        this.finan = finanParam;
    }

    public String getPln() {
        return this.pln;
    }

    public void setPln(final String plnParam) {
        this.pln = plnParam;
    }

    public String getOpe() {
        return this.ope;
    }

    public void setOpe(final String opeParam) {
        this.ope = opeParam;
    }

    public String getMod() {
        return this.mod;
    }

    public void setMod(final String modParam) {
        this.mod = modParam;
    }

    public String getMis() {
        return this.mis;
    }

    public void setMis(final String misParam) {
        this.mis = misParam;
    }

    public String getVal() {
        return this.val;
    }

    public void setVal(final String valParam) {
        this.val = valParam;
    }

    public String getCar() {
        return this.car;
    }

    public void setCar(final String carParam) {
        this.car = carParam;
    }

    public String getDti() {
        return this.dti;
    }

    public void setDti(final String dtiParam) {
        this.dti = dtiParam;
    }

    public String getDtf() {
        return this.dtf;
    }

    public void setDtf(final String dtfParam) {
        this.dtf = dtfParam;
    }

    public String getOta() {
        return this.ota;
    }

    public void setOta(final String otaParam) {
        this.ota = otaParam;
    }

    public FinanDTO getFinan() {
        return this.finan;
    }

    public void setFinan(final FinanDTO finanParam) {
        this.finan = finanParam;
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.car, this.dtf, this.dti, this.finan, this.mis, this.mod, this.ope, this.ota, this.pln,
                this.val);
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null || this.getClass() != obj.getClass()) {
            return false;
        }

        final var other = (FinanTokenDTO) obj;
        return Objects.equals(this.car, other.car) && Objects.equals(this.dtf, other.dtf)
                && Objects.equals(this.dti, other.dti) && Objects.equals(this.finan, other.finan)
                && Objects.equals(this.mis, other.mis) && Objects.equals(this.mod, other.mod)
                && Objects.equals(this.ope, other.ope) && Objects.equals(this.ota, other.ota)
                && Objects.equals(this.pln, other.pln) && Objects.equals(this.val, other.val);
    }

    @Override
    public String toString() {
        return new StringBuilder().append("FinanTokenDTO [pln=").append(this.pln).append(", ope=").append(this.ope)
                .append(", mod=").append(this.mod).append(", mis=").append(this.mis).append(", val=").append(this.val)
                .append(", car=").append(this.car).append(", dti=").append(this.dti).append(", dtf=").append(this.dtf)
                .append(", ota=").append(this.ota).append(", finan=").append(this.finan)
                .append('}').toString();
    }

import java.util.Objects;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "finan")
@XmlAccessorType(XmlAccessType.FIELD)
public class FinanDTO {

    @XmlAttribute
    private String prd;

    @XmlAttribute
    private String pkg;

    @XmlAttribute
    private String val;

    @XmlAttribute
    private String fty;

    @XmlAttribute
    private String safetyPay;

    public FinanDTO() {
        super();
    }

    public FinanDTO(final String prdParam, final String pkgParam, final String valParam, final String ftyParam,
            final String safetypayParam) {
        this();
        this.prd = prdParam;
        this.pkg = pkgParam;
        this.val = valParam;
        this.fty = ftyParam;
        this.safetyPay = safetypayParam;
    }

    public String getPrd() {
        return this.prd;
    }

    public void setPrd(final String prdParam) {
        this.prd = prdParam;
    }

    public String getPkg() {
        return this.pkg;
    }

    public void setPkg(final String pkgParam) {
        this.pkg = pkgParam;
    }

    public String getVal() {
        return this.val;
    }

    public void setVal(final String valParam) {
        this.val = valParam;
    }

    public String getFty() {
        return this.fty;
    }

    public void setFty(final String ftyParam) {
        this.fty = ftyParam;
    }

    public String getSafetyPay() {
        return this.safetyPay;
    }

    public void setSafetyPay(final String safetyPayParam) {
        this.safetyPay = safetyPayParam;
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.fty, this.pkg, this.prd, this.safetyPay, this.val);
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null || this.getClass() != obj.getClass()) {
            return false;
        }

        final var other = (FinanDTO) obj;
        return Objects.equals(this.fty, other.fty) && Objects.equals(this.pkg, other.pkg)
                && Objects.equals(this.prd, other.prd) && Objects.equals(this.safetyPay, other.safetyPay)
                && Objects.equals(this.val, other.val);
    }

    @Override
    public String toString() {
        return new StringBuilder().append("FinanDTO [prd=").append(this.prd).append(", pkg=").append(this.pkg)
                .append(", val=").append(this.val).append(", fty=").append(this.fty).append(", safetyPay=")
                .append(this.safetyPay).append('}').toString();
    }
}

I am using java 11 and I am aware that in java 11 JAXB was removed from the SE JDK because it is considered as a EE feature.

I am not able to execute it using mvn spring-boot:run in production environment because of the size of the docker image and security related issues using docker container.

Since Spring Boot generates a fat jar, shouldn't the application run with java -jar applied to the spring boot fat jar generated file the same way as it does with mvn spring-boot:run inside the folder with pom.xml?

EDIT:

After a lot of digging and testing I found that the problem occurs when we try to marshall several valid POJOs using parallel stream instead of stream on the POJOs list. I uploaded the code in java-eleven-jaxb-hell to better understanding, unfortunatelly I cannot change parallelStream to stream because of performance issues. Just to remember, for the problem to happen you have to run java -jar against spring-boot generated fat jar in target folder.



from Recent Questions - Stack Overflow https://ift.tt/3mzDBuz
https://ift.tt/3pul0SH

Xgboost multiclass classification map the probabilities to the labels

I am using the xgboost multiclass classifier as outlined in the example below. For each row in the X_test dataframe the model outputs a list with the list elements being the probability corresponding to each category 'a','b','c' or 'd' e.g. [0.44767836 0.2043365 0.15775423 0.19023092].

How can I tell which element in the list corresponds to which class / cateogry (a,b,c or d)? My goal is to create 4 extra columns on the dataframe a,b,c,d with the matching probability as the row value in each column.

import numpy as np
import pandas as pd
import xgboost as xgb
import random
from sklearn import preprocessing
from sklearn.model_selection import train_test_split

#Create Example Data
np.random.seed(312)
data = np.random.random((10000, 3))
y = [random.choice('abcd') for _ in range(data.shape[0])]

features = ["x1", "x2", "x3"]
df = pd.DataFrame(data=data, columns=features)
df['y']=y

#Encode target variable
labelencoder = preprocessing.LabelEncoder()
df['y_target'] = labelencoder.fit_transform(df['y'])
    
#Train Test Split    
X_train, X_test, y_train, y_test = train_test_split(df[features], df['y_target'], test_size=0.2, random_state=42, stratify=y)

#Train Model
dtrain = xgb.DMatrix(X_train, label=y_train)
dtest = xgb.DMatrix(X_test, label=y_test)

param = {        'objective':'multi:softprob',
                 'random_state': 20,
                 'tree_method': 'gpu_hist',
                 'num_class':4
                }

xgb_model = xgb.train(param, dtrain, 100)

predictions=xgb_model.predict(dtest)

print(predictions)


from Recent Questions - Stack Overflow https://ift.tt/3H9mtDD
https://ift.tt/eA8V8J

Performance of rand() in CUDA host function [closed]

Why is this function that uses rand() slow and what approach would have better performance when used in.cu file?

In my case I would like to replace one function that reads strings from file and fills an array(data) to other function which generate strings and fills the same array. Then this array transfers from host to device.

Would like to replace this function that reads file and fills array:

char* get_data(char* file_name) {
  FILE* f;
  if (!(f = fopen(file_name, "r")))
  {
      printf("Error opening file %s", file_name);
      exit(1);
  }
 
  char* data = (char*)malloc(sizeof(char) * count * str_length);
  if (data == NULL)
  {
      perror("Error allocating memory for list of Strings.\n");
      exit(1);
  }
 
  int index = 0;
  char buf[50];
  while (1)
  {
      if (fgets(buf, str_length + 1, f) == NULL)
          break;
      buf[strlen(buf) - 1] = '\0';
      memcpy(&data[index], buf, str_length);
      index += str_length - 1;
  }
  return data;
 }

To this, that generate strings and fills array:

char* get_data()
{
char* data = (char*)calloc(count * str_length, sizeof(char*));
 
    for (int c = 0; c < count; c++) {
        int index = 0;
        char buf[str_length] = "";
        for (int i = 0; i < (str_length - 1); i++)
        {
            buf[i] = charset[rand() % charset_size];
        }
        strcat(&data[index], buf);
        index += str_length + 1;
    }
 return data;
}

Function "get_data" which use rand() and generates strings works well, but very slow. Performance about 10k strings per second (each string 20 chars long).

Full compillable code posted here - https://pastebin.com/AJrPL7bU

Dear moderator. I have reworked the question. Full code code has only minimal (55 lines) repetitive\compillable code. Tha main question is why my function slow. Thanks.



from Recent Questions - Stack Overflow https://ift.tt/3Fyu0vr
https://ift.tt/eA8V8J

Magento 2.3.7 Problem Forgot Password letters and numbers don't displayed on the page

When the client forgot your password the form is incorrect in the page the letters and numbers of recaptcha are not displayed in the page and the client don't get reset our password.How can I solve this problem? enter image description here



from Recent Questions - Stack Overflow https://ift.tt/32l83Sr
https://ift.tt/eA8V8J

executing "service libvirtd start" from ubuntu:20.04 container in docker results in libvirtd: unrecognized service [duplicate]

Steps taken:

Created a Dockerfile:

FROM ubuntu:20.04
ENV TZ=Europe/Amsterdam
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
RUN apt-get update -y
RUN apt-get install -y build-essential
RUN apt-get install -y qemu-kvm libvirt-daemon-system libvirt-dev
COPY startup.sh /
ENTRYPOINT ["/startup.sh"]

Created startup.sh:

#!/bin/bash
set -eou pipefail

chown root:kvm /dev/kvm
service libvirtd start
service virtlogd start

exec "$@"

Then make it executable and create a docker image build:

chmod +x startup.sh
docker build -t win10-vm:latest -f Dockerfile .

And last running a container from the image:

docker run --privileged -it --name temp-container1 --device=/dev/kvm --device=/dev/net/tun -v /sys/fs/cgroup:/sys/fs/cgroup:rw --cap-add=NET_ADMIN --cap-add=SYS_ADMIN win10-vm:latest bash

Unfortunately when getting to the rule >> service libvirtd start in startup.sh then I'm getting the following error:

  • libvirtd: unrecognized service

Can someone help me to understand or tell me why the libvirtd service is not recognized. Specifically in ubuntu:20.04? Because when I do exactly the same in ubuntu:18.04 then libvirtd is recognized and starts with [OK]



from Recent Questions - Stack Overflow https://ift.tt/310SazR
https://ift.tt/eA8V8J

Need help understanding IDAT header in Png image file

I am trying to make an simple-png image file from scratch, using hex editor. enter image description here

Bytes before the highlighted region are for PNG file header and IHDR. Which states that I am trying to make an

  1. 10 x 10 Png file
  2. Greyscale color space
  3. 1 bit depth (bi-level)
  4. Deflate Compression?
  5. Adaptive Filtering?
  6. No interlace

The bytes highlighted are a placeholder for the future length of the IDAT field.

Question:- Now I am unsure on what (or How?) am I supposed to put the image data in the IDAT field?

I am aware of Pixel values of an image being an matrix of MxN dimensions. Being displayed somewhat like:

[ (255, 255, 255), (255, 255, 255) ... (255, 255, 255)] 
[ (255, 255, 255), (255, 255, 255) ... (255, 255, 255)] 
[ (255, 255, 255), (255, 255, 255) ... (255, 255, 255)]
[ (255, 255, 255), (255, 255, 255) ... (255, 255, 255)] 

The Pixel values of an White RGB image, where top left tuple is the color value of pixel at (0, 0) and bottom right being the one for (m-1, n-1).

Now how am I supposed to code that into the IDAT header's data structure? What I am trying to know is how values like above (pixel values) are transformed into the deflate block?

P.S.:- I am not so literate on the workings of Deflate or the filtering algorithms used wherein the png file. I have read the RFC 2083 and Wikipedia page of the Png file. I have also read all relevant answers on stack exchange.



from Recent Questions - Stack Overflow https://ift.tt/3yXKevw
https://ift.tt/311cPno

2021-12-26

Numpy array indexing: view or copy - depends on scope?

Consider the following array manipulations:

import numpy as np
def f(x):
     x += 1
x = np.zeros(1)
f(x)       # changes `x`
f(x[0])    # doesn't change `x`
x[0] += 1  # changes `x`

Why does x[0] behave differently depending on whether += 1 happens inside or outside the function f?

Can I pass a part of the array to the function, such that the function modifies the original array?


Edit: If we considered = instead of +=, it seems that we would maintain the core of the question while getting rid of some irrelevant complexity.



from Recent Questions - Stack Overflow https://ift.tt/3H6HyP2
https://ift.tt/eA8V8J

routing with webpack encore, symfony5

I am developing with symfony 5.3 and webpack encore and I need to call symfony routes from js code.

In order to integrate symfony routes to javascript, I am following Symfony 4 - Webpack-encore use FosJsRouting : Routing is not defined. With this bundle I should write $.ajax({ url: Routing.generate("route_of_symfony"), .......

I am installing jsrouting-bundle with symfony 5 but I am getting some errors:

Problem 1
    - Root composer.json requires friendsofsymfony/jsrouting-bundle ^3.0 -> satisfiable by friendsofsymfony/jsrouting-bundle[3.0.0].
    - friendsofsymfony/jsrouting-bundle 3.0.0 requires symfony/framework-bundle ^5.4|^6.0 -> found symfony/framework-bundle[v5.4.0, v5.4.1, v6.0.0, v6.0.1] but it conflicts with your root composer.json require (5.3.*).

I asked and got this answer https://github.com/FriendsOfSymfony/FOSJsRoutingBundle/issues/422#issuecomment-999818579 where it is not compatible with 5.3

is there some workarround o other way to get routes from symfony in javascript with webpack encore ?

This is my composer.json

{
    "type": "project",
    "license": "proprietary",
    "minimum-stability": "stable",
    "prefer-stable": true,
    "require": {
        "php": ">=7.2.5",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "composer/package-versions-deprecated": "1.11.99.4",
        "doctrine/annotations": "^1.0",
        "doctrine/doctrine-bundle": "^2.4",
        "doctrine/doctrine-migrations-bundle": "^3.1",
        "doctrine/orm": "^2.10",
        "knpuniversity/oauth2-client-bundle": "^2.8",
        "phpdocumentor/reflection-docblock": "^5.2",
        "sensio/framework-extra-bundle": "^6.2",
        "sonata-project/entity-audit-bundle": "^1.6",
        "stevenmaguire/oauth2-keycloak": "^2.2",
        "symfony/apache-pack": "^1.0",
        "symfony/asset": "5.3.*",
        "symfony/console": "5.3.*",
        "symfony/dotenv": "5.3.*",
        "symfony/expression-language": "5.3.*",
        "symfony/flex": "^1.3.1",
        "symfony/form": "5.3.*",
        "symfony/framework-bundle": "5.3.*",
        "symfony/google-mailer": "5.3.*",
        "symfony/http-client": "5.3.*",
        "symfony/intl": "5.3.*",
        "symfony/mailer": "5.3.*",
        "symfony/mime": "5.3.*",
        "symfony/monolog-bundle": "^3.7",
        "symfony/notifier": "5.3.*",
        "symfony/process": "5.3.*",
        "symfony/property-access": "5.3.*",
        "symfony/property-info": "5.3.*",
        "symfony/proxy-manager-bridge": "5.3.*",
        "symfony/runtime": "5.3.*",
        "symfony/security-bundle": "5.3.*",
        "symfony/serializer": "5.3.*",
        "symfony/string": "5.3.*",
        "symfony/translation": "5.3.*",
        "symfony/twig-bundle": "5.3.*",
        "symfony/validator": "5.3.*",
        "symfony/web-link": "5.3.*",
        "symfony/webpack-encore-bundle": "^1.12",
        "symfony/yaml": "5.3.*",
        "twig/cssinliner-extra": "^3.3",
        "twig/extra-bundle": "^3.3",
        "twig/twig": "^2.12|^3.0"
    },
    "require-dev": {
        "phpunit/phpunit": "^9.5",
       "symfony/browser-kit": "5.3.*",
        "symfony/css-selector": "5.3.*",
        "symfony/debug-bundle": "5.3.*",
        "symfony/maker-bundle": "^1.34",
        "symfony/phpunit-bridge": "^5.3",
        "symfony/stopwatch": "5.3.*",
        "symfony/web-profiler-bundle": "5.3.*"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": {
            "*": "dist"
        },
        "sort-packages": true
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },
    "replace": {
        "symfony/polyfill-ctype": "*",
        "symfony/polyfill-iconv": "*",
        "symfony/polyfill-php72": "*"
    },
    "scripts": {
        "auto-scripts": {
            "cache:clear": "symfony-cmd",
            "assets:install %PUBLIC_DIR%": "symfony-cmd"
        },
        "post-install-cmd": [
            "@auto-scripts"
        ],
        "post-update-cmd": [
            "@auto-scripts"
        ]
    },
    "conflict": {
        "symfony/symfony": "*"
    },
    "extra": {
        "symfony": {
            "allow-contrib": false,
            "require": "5.3.*"
        }
    }
}

Thanks.



from Recent Questions - Stack Overflow https://ift.tt/3eqd3aM
https://ift.tt/eA8V8J

Why the CLR keeps checking static members for type constructor invocation even after the constructor invoked?

I understand that when a type declares an explicit static constructor, the just-in-time (JIT) compiler adds a check to each static method and instance constructor of the type to make sure that the static constructor was previously called.

This behaviour I can imagine it as the following code (correct me please if I’m wrong with this conclusion):

class  ExplicitConstructor
    {
        private static string myVar;

        // Force “precise” initialization 
        static ExplicitConstructor() { myVar = "hello, world";} 
    
        
        /* CLR: if the type constructor didn't invoked 
                then add a call to the type constructor */
        public static string MyProperty
        {
            get { return myVar; }
        }
        
        /* CLR: if the type constructor didn't invoked 
                then add a call to the type constructor */
        public ExplicitConstructor()
        {
            Console.WriteLine("In instance ctor");
        }

    }

    class ImplicitConstructor 
    { 
        private static string myVar = "hello, world";
        
        public static string MyProperty
        {
            /* CLR: Invoke the type constructor only here */
            get { return myVar; }
        }
        
        public ImplicitConstructor()
        {
            Console.WriteLine("In instance ctor");
        }
    }

According to performance rules, this behaive has an impact on the performance because of the checks that the runtime performs in order to run the type initializer at a precise time.

[MemoryDiagnoser]
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
[RankColumn]
public class BenchmarkExample
{
    public const int iteration = Int32.MaxValue - 1;

    [Benchmark]
    public void BenchExplicitConstructor()
    {
        for (int i = 0; i < iteration; i++)
        {
            var temp = ExplicitConstructor.MyProperty;
        }
    }

    [Benchmark]
    public void BenchImplicitConstructor()
    {
        for (int i = 0; i < iteration; i++)
        {
            var temp = ImplicitConstructor.MyProperty;
        }
    }

}
Method Mean Error StdDev Rank Allocated
BenchImplicitConstructor 982.6 ms 56.64 ms 163.4 ms 1 -
BenchExplicitConstructor 7,361.4 ms 318.19 ms 933.2 ms 2 -

Why did the CLR, instead of adding a check to each static method/instance constructor of the type to make sure that the type constructor was previously called, check if the type constructor had been invoked (only once)? 



from Recent Questions - Stack Overflow https://ift.tt/3FiqzJ5
https://ift.tt/eA8V8J

Can i send variable in php to anoter page?

This is my code but it doesn't work (error 500)

while ($dbarr = mysqli_fetch_array($result))    
{
    echo $dbarr['qno']; 
    echo '<a href=show_detail.php?item=' . $dbarr[qno] . '>' . $dbarr[ans] . '</a>';
    
    echo $dbarr['qname'],"</a>&nbsp;";      
    echo $dbarr['qcount'] . "<br>\n";   

}


from Recent Questions - Stack Overflow https://ift.tt/3yHn78w
https://ift.tt/eA8V8J