问:
How come the Image is not displayed on screen after I pick the Image for the phones photo gallery
I am able to gain access to the phones photo library using the but when I click on a image_picker import but when I choose a image it reverts to home screen and does not display the image picked

I think it may have to do with how I define the variable that will store my image file at the beginning but i am not sure.

```<code>File? imageFile;

</code>```

here is my code.

```<code>import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

void main() {
  runApp(
    MaterialApp(
      theme: ThemeData.dark(),
      home: MyApp(),
    ),
  );
  //runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyApp> {
  /// Variables
  File? imageFile;

  /// Widget
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Image Picker"),
        ),
        body: Container(
          child: imageFile == null
              ? Container(
                  alignment: Alignment.center,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      ElevatedButton(
                        onPressed: () {
                          print('heyheyheyheyhey');
                          _getFromGallery();
                        },
                        child: Text("PICK FROM GALLERY"),
                      ),
                      Container(
                        height: 40.0,
                      ),
                      ElevatedButton(
                        onPressed: () {
                          _getFromCamera();
                        },
                        child: Text("PICK FROM CAMERA"),
                      )
                    ],
                  ),
                )
              : Container(
                  child: Image.file(
                    imageFile!,
                    fit: BoxFit.cover,
                  ),
                ),
        ));
  }

  /// Get from gallery
  _getFromGallery() async {
    print('heyheyheyheyhey');
    PickedFile pickedFile = (await ImagePicker().pickImage(
      source: ImageSource.gallery,
      maxWidth: 1800,
      maxHeight: 1800,
    )) as PickedFile;
    if (pickedFile != null) {
      setState(() {
        imageFile = File(pickedFile.path);
        print('heyheyheyheyhey');
      });
    }
  }

  //Get from Camera
  _getFromCamera() async {
    PickedFile pickedFile = (await ImagePicker().pickImage(
      source: ImageSource.camera,
      maxWidth: 1800,
      maxHeight: 1800,
    )) as PickedFile;
    if (pickedFile != null) {
      setState(() {
        imageFile = File(pickedFile.path);
      });
    }
  }

</code>```

答:
Image picker returns the future object of XFile, that was causing a problem for you.

Here is the updated code of your functions:

```<code>/// Get from gallery
_getFromGallery() async {
  print('heyheyheyheyhey');
  XFile? pickedFile = await ImagePicker().pickImage(
    source: ImageSource.gallery,
    maxWidth: 1800,
    maxHeight: 1800,
  );
  if (pickedFile != null) {
    setState(() {
      imageFile = File(pickedFile.path);
      print('heyheyheyheyhey');
    });
  }
}

//Get from Camera
_getFromCamera() async {
  XFile? pickedFile = await ImagePicker().pickImage(
    source: ImageSource.camera,
    maxWidth: 1800,
    maxHeight: 1800,
  );
  if (pickedFile != null) {
    setState(() {
      imageFile = File(pickedFile.path);
    });
  }
}
</code>```

Body:
I am able to gain access to the phones photo library using the but when I click on a image_picker import but when I choose a image it reverts to home screen and does not display the image picked

I think it may have to do with how I define the variable that will store my image file at the beginning but i am not sure.

File? imageFile;

here is my code.

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

void main() {
  runApp(
    MaterialApp(
      theme: ThemeData.dark(),
      home: MyApp(),
    ),
  );
  //runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyApp> {
  /// Variables
  File? imageFile;

  /// Widget
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Image Picker"),
        ),
        body: Container(
          child: imageFile == null
              ? Container(
                  alignment: Alignment.center,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      ElevatedButton(
                        onPressed: () {
                          print('heyheyheyheyhey');
                          _getFromGallery();
                        },
                        child: Text("PICK FROM GALLERY"),
                      ),
                      Container(
                        height: 40.0,
                      ),
                      ElevatedButton(
                        onPressed: () {
                          _getFromCamera();
                        },
                        child: Text("PICK FROM CAMERA"),
                      )
                    ],
                  ),
                )
              : Container(
                  child: Image.file(
                    imageFile!,
                    fit: BoxFit.cover,
                  ),
                ),
        ));
  }

  /// Get from gallery
  _getFromGallery() async {
    print('heyheyheyheyhey');
    PickedFile pickedFile = (await ImagePicker().pickImage(
      source: ImageSource.gallery,
      maxWidth: 1800,
      maxHeight: 1800,
    )) as PickedFile;
    if (pickedFile != null) {
      setState(() {
        imageFile = File(pickedFile.path);
        print('heyheyheyheyhey');
      });
    }
  }

  //Get from Camera
  _getFromCamera() async {
    PickedFile pickedFile = (await ImagePicker().pickImage(
      source: ImageSource.camera,
      maxWidth: 1800,
      maxHeight: 1800,
    )) as PickedFile;
    if (pickedFile != null) {
      setState(() {
        imageFile = File(pickedFile.path);
      });
    }
  }

Body:
Image picker returns the future object of XFile, that was causing a problem for you.

Here is the updated code of your functions:

/// Get from gallery
_getFromGallery() async {
  print('heyheyheyheyhey');
  XFile? pickedFile = await ImagePicker().pickImage(
    source: ImageSource.gallery,
    maxWidth: 1800,
    maxHeight: 1800,
  );
  if (pickedFile != null) {
    setState(() {
      imageFile = File(pickedFile.path);
      print('heyheyheyheyhey');
    });
  }
}

//Get from Camera
_getFromCamera() async {
  XFile? pickedFile = await ImagePicker().pickImage(
    source: ImageSource.camera,
    maxWidth: 1800,
    maxHeight: 1800,
  );
  if (pickedFile != null) {
    setState(() {
      imageFile = File(pickedFile.path);
    });
  }
}


来源: stackexchange

问:
Indices of the permutation for sorted list
Given an array, I would like to get an array holding the indices of the permutation that would result in the array being sorted. An example should make it clear:
Input array:

```<code>[10, 50, 40, 20, 30]
</code>```

should produce the following output:

```<code>[0, 3, 4, 2, 1]
</code>```

because if I first take the 0th, then the 3rd, then the 4th, then the 2nd and then the 1st element of the list, I would get [10, 20, 30, 40, 50], which would be the sorted array.

Of course I could just code it in Python from scratch, but I wonder if there is a function for this in Python already.

答:
Use NumPy argsort: that provides exactly what you need.

```<code>a = np.array([10, 50, 40, 20, 30])
np.argsort(a)
</code>```

will result in

```<code>np.array([0, 3, 4, 2, 1])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Given an array, I would like to get an array holding the indices of the permutation that would result in the array being sorted. An example should make it clear:
Input array:

[10, 50, 40, 20, 30]

should produce the following output:

[0, 3, 4, 2, 1]

because if I first take the 0th, then the 3rd, then the 4th, then the 2nd and then the 1st element of the list, I would get [10, 20, 30, 40, 50], which would be the sorted array.

Of course I could just code it in Python from scratch, but I wonder if there is a function for this in Python already.

Body:
Use NumPy argsort: that provides exactly what you need.

a = np.array([10, 50, 40, 20, 30])
np.argsort(a)

will result in

np.array([0, 3, 4, 2, 1])


问:
Impulse, gaussian and salt and pepper noise with OpenCV
I'm studying Image Processing on the famous Gonzales "Digital Image Processing" and talking about image restoration a lot of examples are done with computer-generated noise (gaussian, salt and pepper, etc). In MATLAB there are some built-in functions to do it. What about OpenCV?</p>

答:
```<code>def add_salt_noise(src, ratio: float = 0.05, noise: list = [0, 0, 0]):
    dst = src.copy()
    import random
    shuffle_dict = {}
    i = 0
    while i < (int(dst.shape[0]*dst.shape[1] * ratio)):
        x, y = random.randint(0, dst.shape[0] - 1), random.randint(0, dst.shape[1] - 1)
        if (x, y) in shuffle_dict:
            continue
        else:
            dst[x, y] = noise
            shuffle_dict[(x, y)] = 0
            i += 1
    return dst
</code>```

ContentLicense: CC BY-SA 3.0


问:
How to get summarized and ranked list of data in BigQuery - summarize many rows into 1 based on rank
I have a BigQuery view (flow_test_metrics_level_1_moving_average) that keeps track of the average failure rate for different tests.

```<code>SELECT test, commit_date2, result2, AVG(result2)
  OVER (
    PARTITION BY test
    ORDER BY commit_date2
    ROWS BETWEEN 4 PRECEDING AND CURRENT ROW
  ) AS avg_result
FROM `data.dev_src_flow_test_metrics.flow_test_metrics_level_1`
ORDER BY test
</code>```

Here are some rows returned from this view:

This is working and I can visualize the data for each test in Grafana like this:

I would like to create a new visualization where I get a summarized and ranked list of tests with the highest failure rate, based on the latest commit date (commit_date2 field) for each test. Not all tests will have the same commit date values.

Test1 might have a latest commit date of Jan 1 where the average pass rate was 0.90.

Test2 might have a latest commit date of Jan 2 where the average pass rate was 0.80.

Test3 might have a latest commit date of Jan 3 where the average pass rate was 0.85.

I would like to create a new view showing the ranking as follows (from lowest pass rate to highest):

Test2 (0.80)

Test3 (0.85)

Test1 (0.90)

I'd like to create a BigQuery view / table that creates this ranked list and only uses the latest commit date of each test.

I tried the following BigQuery view but I'm getting ALL test rows returned instead of just the latest ones for each test based on the commit date

```<code>SELECT test, avg_result, commit_date2,
  RANK() OVER (PARTITION BY test ORDER BY avg_result desc) AS RANK
FROM `data.dev_src_flow_test_metrics.flow_test_metrics_level_1_moving_average`

ORDER BY commit_date2 desc
</code>```

But this returns ALL the rows with their rank. I only want the last rows of each test, based on the latest commit date for each test.

答:
I found a way to do this by splitting up the problem into 2 parts

find the latest commit date of each test

narrow down the result by using a where clause based on the latest commit date of each test

Got help from this SO answer: BigQuery: Get latest row in a table only if a field has a specific value that was doing something very similar

create query to get the latest commit date of each test - this will still output all rows but the latest commit date will be constant now for each test.

```<code>SELECT test, avg_result, commit_date2,
  FIRST_VALUE(commit_date2) OVER (PARTITION BY test ORDER BY commit_date2 DESC) as latest_commit_date
FROM `data.dev_src_flow_test_metrics.flow_test_metrics_level_1_moving_average`
</code>```

use the query from 1) as sub-query where you can narrow the result to match each test name, so there's only 1 record per test returned

```<code>SELECT test, avg_result, commit_date2
from (
SELECT test, avg_result, commit_date2,
  FIRST_VALUE(commit_date2) OVER (PARTITION BY test ORDER BY commit_date2 DESC) as latest_commit_date
FROM `data.dev_src_flow_test_metrics.flow_test_metrics_level_1_moving_average`
)
WHERE commit_date2 = latest_commit_date
</code>```

Now we get a summary of 1 record per test with the latest commit date and showing the average result

Body:
I have a BigQuery view (flow_test_metrics_level_1_moving_average) that keeps track of the average failure rate for different tests.

SELECT test, commit_date2, result2, AVG(result2)
  OVER (
    PARTITION BY test
    ORDER BY commit_date2
    ROWS BETWEEN 4 PRECEDING AND CURRENT ROW
  ) AS avg_result
FROM `data.dev_src_flow_test_metrics.flow_test_metrics_level_1`
ORDER BY test

Here are some rows returned from this view:

This is working and I can visualize the data for each test in Grafana like this:

I would like to create a new visualization where I get a summarized and ranked list of tests with the highest failure rate, based on the latest commit date (commit_date2 field) for each test. Not all tests will have the same commit date values.

Test1 might have a latest commit date of Jan 1 where the average pass rate was 0.90.

Test2 might have a latest commit date of Jan 2 where the average pass rate was 0.80.

Test3 might have a latest commit date of Jan 3 where the average pass rate was 0.85.

I would like to create a new view showing the ranking as follows (from lowest pass rate to highest):

Test2 (0.80)

Test3 (0.85)

Test1 (0.90)

I'd like to create a BigQuery view / table that creates this ranked list and only uses the latest commit date of each test.

I tried the following BigQuery view but I'm getting ALL test rows returned instead of just the latest ones for each test based on the commit date

SELECT test, avg_result, commit_date2,
  RANK() OVER (PARTITION BY test ORDER BY avg_result desc) AS RANK
FROM `data.dev_src_flow_test_metrics.flow_test_metrics_level_1_moving_average`

ORDER BY commit_date2 desc

But this returns ALL the rows with their rank. I only want the last rows of each test, based on the latest commit date for each test.

Body:
I found a way to do this by splitting up the problem into 2 parts

find the latest commit date of each test

narrow down the result by using a where clause based on the latest commit date of each test

Got help from this SO answer: BigQuery: Get latest row in a table only if a field has a specific value that was doing something very similar

create query to get the latest commit date of each test - this will still output all rows but the latest commit date will be constant now for each test.

SELECT test, avg_result, commit_date2,
  FIRST_VALUE(commit_date2) OVER (PARTITION BY test ORDER BY commit_date2 DESC) as latest_commit_date
FROM `data.dev_src_flow_test_metrics.flow_test_metrics_level_1_moving_average`

use the query from 1) as sub-query where you can narrow the result to match each test name, so there's only 1 record per test returned

SELECT test, avg_result, commit_date2
from (
SELECT test, avg_result, commit_date2,
  FIRST_VALUE(commit_date2) OVER (PARTITION BY test ORDER BY commit_date2 DESC) as latest_commit_date
FROM `data.dev_src_flow_test_metrics.flow_test_metrics_level_1_moving_average`
)
WHERE commit_date2 = latest_commit_date

Now we get a summary of 1 record per test with the latest commit date and showing the average result


问:
python dictionary sorting oddly (want non-alphabetical)
so I am trying to send a packet with some keys that i have put into a dictionary. these need to be printed in a specific order, so I've tried to make a function to reorder them. I assume python is doing something to rearrange in the order I don't want, but i'm not sure why.

I'm currently using this function to try and achieve this.

```<code>def array_sort(array, sort): #yeah, it's array cuz i php like that.
    ordered = {}
    for i in range(0,len(sort)):
        if sort[i] in array:
            ordered[sort[i]] = array[sort[i]]
    keys = array.keys()
    return ordered

order = "l5,l4,l3,l2,q,y,k,k3,d1,z,p,c,b,d3,dt,N,n,a,h,v".split(',')
keys = array_sort(infos, order)
</code>```

for some reason this isn't working, infos is the list of keys in alphabetical order, i'm just not sure why the function is outputting the keys in an odd order. (a first, when 15 should be first :S)

If you know a better way to do this feel free to tell me, I just recently started on python, so I'm not that familiar.

EDIT:
I was able to print the keys in the correct order using this immediately after making the order dictionary. even if it was just output as a string the order would be preserved (for the time being) and you could .split() it again to get the dictionary in the correct order (i think).

```<code>for i in range(0, len(order)):
    if order[i] in infos:
        packet += order[i] + '="' + infos[order[i]] + '" '
</code>```

答: Python dictionaries are not ordered containers.  Take a look at the collections.OrderedDict instead</p>

Body:
so I am trying to send a packet with some keys that i have put into a dictionary. these need to be printed in a specific order, so I've tried to make a function to reorder them. I assume python is doing something to rearrange in the order I don't want, but i'm not sure why.

I'm currently using this function to try and achieve this.

def array_sort(array, sort): #yeah, it's array cuz i php like that.
    ordered = {}
    for i in range(0,len(sort)):
        if sort[i] in array:
            ordered[sort[i]] = array[sort[i]]
    keys = array.keys()
    return ordered

order = "l5,l4,l3,l2,q,y,k,k3,d1,z,p,c,b,d3,dt,N,n,a,h,v".split(',')
keys = array_sort(infos, order)

for some reason this isn't working, infos is the list of keys in alphabetical order, i'm just not sure why the function is outputting the keys in an odd order. (a first, when 15 should be first :S)

If you know a better way to do this feel free to tell me, I just recently started on python, so I'm not that familiar.

EDIT:
I was able to print the keys in the correct order using this immediately after making the order dictionary. even if it was just output as a string the order would be preserved (for the time being) and you could .split() it again to get the dictionary in the correct order (i think).

for i in range(0, len(order)):
    if order[i] in infos:
        packet += order[i] + '="' + infos[order[i]] + '" '


问:
Client does not interact with the server java (Socket)-
Is a client application that should create an interface and connect to the server which then connects to db to run queries.
I can't understand why the client doesn't connect to the server.
The server works, while the client gives me the NullPointerException error.

Code server:

```<code>public class ServerLab  extends Thread{

   private Socket socket;
   private BufferedReader in;
   private PrintWriter out;
   public ServerLab(Socket socket) throws IOException {
       this.socket = socket;
       this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
       this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
       start();

   }

   public void run() {

       try {
           while (true) {
               String c =in.readLine();
               System.out.println(c);
           }
       }catch(IOException e) {
           e.printStackTrace();
       }

   }
}

</code>```

code client:

```<code>
public class RegCentV extends Thread{

   JFrame frame;
   private JTextField cap;
   private JTextField sigla;
   private JTextField comune;
   private JTextField nome;
   private JTextField indirizzo;
   private JComboBox comboBox_1,comboBox;
   private String ind,t;
   int PORT = 6060;
   private Socket socket;
   private BufferedReader in;
   private PrintWriter out;

   /**
    * Launch the application.
    */
   public RegCentV(InetAddress add) throws IOException {
       this.socket = new Socket("192.168.1.17", 6060);
       this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
       this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
       start();
   }
   public void run() {
       try {
           out.println("Hello server");
           RegCentV window = new RegCentV();
           window.frame.setVisible(true);

       } catch (Exception e) {
           e.printStackTrace();
       }
   }

   /**
    * Create the application.
    */
   public RegCentV() {
       initialize();
   }

   /**
    * Initialize the contents of the frame.
    */
   private void initialize() {
       frame = new JFrame();
       frame.setBounds(100, 100, 579, 325);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       JLabel lblNewLabel_5 = new JLabel("Nome Centro Vaccinale");
       lblNewLabel_5.setBounds(10, 64, 163, 14);

       nome = new JTextField();
       nome.setBounds(183, 61, 96, 20);
       nome.setColumns(10);

       JLabel lblNewLabel_4 = new JLabel("Indirizzo");
       lblNewLabel_4.setBounds(289, 64, 71, 14);

       String[] addres = { "Via", "V.le", "Piazza" };
       JComboBox comboBox_1 = new JComboBox(addres);
       comboBox_1.setBounds(382, 61, 57, 20);

       JLabel lblNewLabel_3 = new JLabel("Comune");
       lblNewLabel_3.setBounds(10, 105, 136, 14);

       comune = new JTextField();
       comune.setBounds(183, 102, 96, 20);
       comune.setColumns(10);

       JLabel lblNewLabel_2 = new JLabel("Sigla Provincia");
       lblNewLabel_2.setBounds(289, 105, 91, 14);

       sigla = new JTextField();
       sigla.setBounds(380, 102, 96, 20);
       sigla.setColumns(10);

       JLabel lblNewLabel_1 = new JLabel("CAP");
       lblNewLabel_1.setBounds(10, 152, 132, 14);

       cap = new JTextField();
       cap.setBounds(183, 149, 96, 20);
       cap.setColumns(10);

       JLabel lblNewLabel = new JLabel("Tipologia");
       lblNewLabel.setBounds(286, 152, 74, 14);

       String[] tipe = { "Ospedaliero", "Hub", "Aziendale" };
       JComboBox comboBox = new JComboBox(tipe);
       comboBox.setBounds(382, 149, 85, 20);

       frame.getContentPane().setLayout(null);
       frame.getContentPane().add(lblNewLabel_5);
       frame.getContentPane().add(nome);
       frame.getContentPane().add(lblNewLabel_4);
       frame.getContentPane().add(comboBox_1);

       indirizzo = new JTextField();
       indirizzo.setBounds(447, 61, 96, 20);
       frame.getContentPane().add(indirizzo);
       indirizzo.setColumns(10);
       frame.getContentPane().add(lblNewLabel_3);
       frame.getContentPane().add(comune);
       frame.getContentPane().add(lblNewLabel_2);
       frame.getContentPane().add(sigla);
       frame.getContentPane().add(lblNewLabel_1);
       frame.getContentPane().add(cap);
       frame.getContentPane().add(lblNewLabel);
       frame.getContentPane().add(comboBox);

       JButton btnNewButton = new JButton("SALVA");
       btnNewButton.addMouseListener(new MouseAdapter() {
           @Override
           public void mouseClicked(MouseEvent e) {
               ind = comboBox_1.getSelectedItem().toString();
               t =  comboBox.getSelectedItem().toString();
               registraCentroVaccinale();
               JOptionPane.showMessageDialog(frame,"Elemento salvato");
               IntSeconda nuovaPage=new IntSeconda();
               nuovaPage.frame.setVisible(true);
               RegCentV.this.frame.dispose();
           }
       });
       btnNewButton.setBackground(Color.GREEN);
       btnNewButton.setBounds(343, 225, 96, 23);
       frame.getContentPane().add(btnNewButton);

       JButton btnNewButton_1 = new JButton("INDIETRO");
       btnNewButton_1.addMouseListener(new MouseAdapter() {
           @Override
           public void mouseClicked(MouseEvent e) {
               IntSeconda nuovaPage=new IntSeconda();
               nuovaPage.frame.setVisible(true);
               RegCentV.this.frame.dispose();
           }
       });
       btnNewButton_1.setBackground(Color.RED);
       btnNewButton_1.setBounds(170, 225, 96, 23);
       frame.getContentPane().add(btnNewButton_1);

       JLabel lblNewLabel_6 = new JLabel("REGISTRAZIONE CENTRO VACCINALE");
       lblNewLabel_6.setForeground(Color.BLUE);
       lblNewLabel_6.setBounds(156, 11, 326, 39);
       frame.getContentPane().add(lblNewLabel_6);

   }
}
</code>```

Main Client:

```<code>
public class Main_Op {
   public static void main(String[] args) {
       // TODO Auto-generated method stub

       RegCentV client = new RegCentV();
       client.start();
   }

}
</code>```

can someone help me? Thanks!

答:
when you start Main_Op , you start the thread you created using the default constructor.

```<code>public class Main_Op {
    public static void main(String[] args) {
    // TODO Auto-generated method stub

    RegCentV client = new RegCentV();
    client.start();
}

// the default constructor you call does not set this.in, this.out or this.socket
// calls initialize for gui fields but doesn't set in, out or socket
public RegCentV() {
   initialize();
}
</code>```

Yet when you run the client, the run method looks like this:

```<code>public void run() {
   try {
       out.println("Hello server");
       RegCentV window = new RegCentV();
       window.frame.setVisible(true);

   } catch (Exception e) {
       e.printStackTrace();
   }
</code>```

}

You are using out but out is null at this point.
if you use the other constructor you would have an out to use. But there is a problem there:

```<code>//
public RegCentV(InetAddress add) throws IOException {
   this.socket = new Socket("192.168.1.17", 6060);
   this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
   this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
   start();
}
</code>```

the other constructor starts the thread it just finished creating. (worse, if you subclass this constructor it may start it before it is done creating.)

I think that start() really doesn't belong there, but I admit this isn't the question you are asking. Just some additional advice.

Basically: you have multiple constructors but only 1 constructor does it's job. (a constructor's job is to bring the object into a stable/usable state.) You should probably merge both constructors as 1 is doing network and the other is doing gui. Or split them into 2 different classes and have each perform only their own job. (gui can own a network-client object to use/perform calls on. possibly register itself as a listener as well)

Body:
Is a client application that should create an interface and connect to the server which then connects to db to run queries.
I can't understand why the client doesn't connect to the server.
The server works, while the client gives me the NullPointerException error.

Code server:

public class ServerLab  extends Thread{

   private Socket socket;
   private BufferedReader in;
   private PrintWriter out;
   public ServerLab(Socket socket) throws IOException {
       this.socket = socket;
       this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
       this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
       start();

   }

   public void run() {

       try {
           while (true) {
               String c =in.readLine();
               System.out.println(c);
           }
       }catch(IOException e) {
           e.printStackTrace();
       }

   }
}

code client:

public class RegCentV extends Thread{

   JFrame frame;
   private JTextField cap;
   private JTextField sigla;
   private JTextField comune;
   private JTextField nome;
   private JTextField indirizzo;
   private JComboBox comboBox_1,comboBox;
   private String ind,t;
   int PORT = 6060;
   private Socket socket;
   private BufferedReader in;
   private PrintWriter out;

   /**
    * Launch the application.
    */
   public RegCentV(InetAddress add) throws IOException {
       this.socket = new Socket("192.168.1.17", 6060);
       this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
       this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
       start();
   }
   public void run() {
       try {
           out.println("Hello server");
           RegCentV window = new RegCentV();
           window.frame.setVisible(true);

       } catch (Exception e) {
           e.printStackTrace();
       }
   }

   /**
    * Create the application.
    */
   public RegCentV() {
       initialize();
   }

   /**
    * Initialize the contents of the frame.
    */
   private void initialize() {
       frame = new JFrame();
       frame.setBounds(100, 100, 579, 325);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       JLabel lblNewLabel_5 = new JLabel("Nome Centro Vaccinale");
       lblNewLabel_5.setBounds(10, 64, 163, 14);

       nome = new JTextField();
       nome.setBounds(183, 61, 96, 20);
       nome.setColumns(10);

       JLabel lblNewLabel_4 = new JLabel("Indirizzo");
       lblNewLabel_4.setBounds(289, 64, 71, 14);

       String[] addres = { "Via", "V.le", "Piazza" };
       JComboBox comboBox_1 = new JComboBox(addres);
       comboBox_1.setBounds(382, 61, 57, 20);

       JLabel lblNewLabel_3 = new JLabel("Comune");
       lblNewLabel_3.setBounds(10, 105, 136, 14);

       comune = new JTextField();
       comune.setBounds(183, 102, 96, 20);
       comune.setColumns(10);

       JLabel lblNewLabel_2 = new JLabel("Sigla Provincia");
       lblNewLabel_2.setBounds(289, 105, 91, 14);

       sigla = new JTextField();
       sigla.setBounds(380, 102, 96, 20);
       sigla.setColumns(10);

       JLabel lblNewLabel_1 = new JLabel("CAP");
       lblNewLabel_1.setBounds(10, 152, 132, 14);

       cap = new JTextField();
       cap.setBounds(183, 149, 96, 20);
       cap.setColumns(10);

       JLabel lblNewLabel = new JLabel("Tipologia");
       lblNewLabel.setBounds(286, 152, 74, 14);

       String[] tipe = { "Ospedaliero", "Hub", "Aziendale" };
       JComboBox comboBox = new JComboBox(tipe);
       comboBox.setBounds(382, 149, 85, 20);

       frame.getContentPane().setLayout(null);
       frame.getContentPane().add(lblNewLabel_5);
       frame.getContentPane().add(nome);
       frame.getContentPane().add(lblNewLabel_4);
       frame.getContentPane().add(comboBox_1);

       indirizzo = new JTextField();
       indirizzo.setBounds(447, 61, 96, 20);
       frame.getContentPane().add(indirizzo);
       indirizzo.setColumns(10);
       frame.getContentPane().add(lblNewLabel_3);
       frame.getContentPane().add(comune);
       frame.getContentPane().add(lblNewLabel_2);
       frame.getContentPane().add(sigla);
       frame.getContentPane().add(lblNewLabel_1);
       frame.getContentPane().add(cap);
       frame.getContentPane().add(lblNewLabel);
       frame.getContentPane().add(comboBox);

       JButton btnNewButton = new JButton("SALVA");
       btnNewButton.addMouseListener(new MouseAdapter() {
           @Override
           public void mouseClicked(MouseEvent e) {
               ind = comboBox_1.getSelectedItem().toString();
               t =  comboBox.getSelectedItem().toString();
               registraCentroVaccinale();
               JOptionPane.showMessageDialog(frame,"Elemento salvato");
               IntSeconda nuovaPage=new IntSeconda();
               nuovaPage.frame.setVisible(true);
               RegCentV.this.frame.dispose();
           }
       });
       btnNewButton.setBackground(Color.GREEN);
       btnNewButton.setBounds(343, 225, 96, 23);
       frame.getContentPane().add(btnNewButton);

       JButton btnNewButton_1 = new JButton("INDIETRO");
       btnNewButton_1.addMouseListener(new MouseAdapter() {
           @Override
           public void mouseClicked(MouseEvent e) {
               IntSeconda nuovaPage=new IntSeconda();
               nuovaPage.frame.setVisible(true);
               RegCentV.this.frame.dispose();
           }
       });
       btnNewButton_1.setBackground(Color.RED);
       btnNewButton_1.setBounds(170, 225, 96, 23);
       frame.getContentPane().add(btnNewButton_1);

       JLabel lblNewLabel_6 = new JLabel("REGISTRAZIONE CENTRO VACCINALE");
       lblNewLabel_6.setForeground(Color.BLUE);
       lblNewLabel_6.setBounds(156, 11, 326, 39);
       frame.getContentPane().add(lblNewLabel_6);

   }
}

Main Client:

public class Main_Op {
   public static void main(String[] args) {
       // TODO Auto-generated method stub

       RegCentV client = new RegCentV();
       client.start();
   }

}

can someone help me? Thanks!

Body:
when you start Main_Op , you start the thread you created using the default constructor.

public class Main_Op {
    public static void main(String[] args) {
    // TODO Auto-generated method stub

    RegCentV client = new RegCentV();
    client.start();
}

// the default constructor you call does not set this.in, this.out or this.socket
// calls initialize for gui fields but doesn't set in, out or socket
public RegCentV() {
   initialize();
}

Yet when you run the client, the run method looks like this:

public void run() {
   try {
       out.println("Hello server");
       RegCentV window = new RegCentV();
       window.frame.setVisible(true);

   } catch (Exception e) {
       e.printStackTrace();
   }

}

You are using out but out is null at this point.
if you use the other constructor you would have an out to use. But there is a problem there:

//
public RegCentV(InetAddress add) throws IOException {
   this.socket = new Socket("192.168.1.17", 6060);
   this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
   this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
   start();
}

the other constructor starts the thread it just finished creating. (worse, if you subclass this constructor it may start it before it is done creating.)

I think that start() really doesn't belong there, but I admit this isn't the question you are asking. Just some additional advice.

Basically: you have multiple constructors but only 1 constructor does it's job. (a constructor's job is to bring the object into a stable/usable state.) You should probably merge both constructors as 1 is doing network and the other is doing gui. Or split them into 2 different classes and have each perform only their own job. (gui can own a network-client object to use/perform calls on. possibly register itself as a listener as well)


问:
Parse multiple json objects that are in one line
I'm parsing files that containt json objects. The problem is that some files have multiple objects in one line. e.g.:

```<code>{"data1": {"data1_inside": "bla{bl\"a"}}{"data1": {"data1_inside": "blabla["}}{"data1": {"data1_inside": "bla{bla"}}{"data1": {"data1_inside": "bla["}}
</code>```

I've made a function that tries parsing a substring when there are no open brackets left, but there may be curly brackets in values. I've tried skipping values with checking the start and end of quotes, but there are also values with escaped quotes. Any ideas on how to deal with this?

My attempt:

```<code>def get_lines(data):
    lines = []
    open_brackets = 0
    start = 0
    is_comment = False
    for index, c in enumerate(data):
        if c == '"':
            is_comment = not is_comment
        elif not is_comment:
            if c == '{':
                if not open_brackets:
                    start = index
                open_brackets += 1

            if c == '}':
                open_brackets -= 1
                if not open_brackets:
                    lines.append(data[start: index+1])

    return lines
</code>```

答:
Building on Carcophan's answer and Hi-angel's comment I added a check to see if the leftover part of the string is whitespace.  Python strings have a isspace() method so I used that to check.

NOTE: This is python3 -- I think the json library returned a different exception in eariler verisons.

```<code>dec = json.JSONDecoder()
pos = 0
results = []
while pos != len(str(json_str)):
    try:
        j, json_len = dec.raw_decode(str(json_str)[pos:])
    except json.decoder.JSONDecodeError as exc:
        if len(results) > 0 and str(json_str)[pos:].isspace():
            break
        raise exc
    else:
        pos += json_len
        results.append(j)
</code>```

Body:
I'm parsing files that containt json objects. The problem is that some files have multiple objects in one line. e.g.:

{"data1": {"data1_inside": "bla{bl\"a"}}{"data1": {"data1_inside": "blabla["}}{"data1": {"data1_inside": "bla{bla"}}{"data1": {"data1_inside": "bla["}}

I've made a function that tries parsing a substring when there are no open brackets left, but there may be curly brackets in values. I've tried skipping values with checking the start and end of quotes, but there are also values with escaped quotes. Any ideas on how to deal with this?

My attempt:

def get_lines(data):
    lines = []
    open_brackets = 0
    start = 0
    is_comment = False
    for index, c in enumerate(data):
        if c == '"':
            is_comment = not is_comment
        elif not is_comment:
            if c == '{':
                if not open_brackets:
                    start = index
                open_brackets += 1

            if c == '}':
                open_brackets -= 1
                if not open_brackets:
                    lines.append(data[start: index+1])

    return lines

Body:
Building on Carcophan's answer and Hi-angel's comment I added a check to see if the leftover part of the string is whitespace.  Python strings have a isspace() method so I used that to check.

NOTE: This is python3 -- I think the json library returned a different exception in eariler verisons.

dec = json.JSONDecoder()
pos = 0
results = []
while pos != len(str(json_str)):
    try:
        j, json_len = dec.raw_decode(str(json_str)[pos:])
    except json.decoder.JSONDecodeError as exc:
        if len(results) > 0 and str(json_str)[pos:].isspace():
            break
        raise exc
    else:
        pos += json_len
        results.append(j)


问:
Post photo on Facebook group using graph api error(#120) Invalid album id
someone please help me. i'm trying to post a picture to the group but it's not working. Posts still appear on the group but no photos.
My code</p>
```<code>$post_data = array(
    'caption' => $mess,
    'url' => $urlphoto
    );
try {
 $response = $fb->post('/944379269276566/photos', $post_data, $pageAccessToken);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
 echo 'Graph returned an error: '.$e->getMessage();
 exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
 echo 'Facebook SDK returned an error: '.$e->getMessage();
 exit;
}
</code>```

答:
this error occurs when you include a question mark (?) in the caption.
and this is a Facebook bug
https://developers.facebook.com/support/bugs/739380653703276/</p>

Body:
someone please help me. i'm trying to post a picture to the group but it's not working. Posts still appear on the group but no photos.
My code

$post_data = array(
    'caption' => $mess,
    'url' => $urlphoto
    );
try {
 $response = $fb->post('/944379269276566/photos', $post_data, $pageAccessToken);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
 echo 'Graph returned an error: '.$e->getMessage();
 exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
 echo 'Facebook SDK returned an error: '.$e->getMessage();
 exit;
}


问:
Xcode 4 hangs at "Attaching to (app name)"
I just upgraded to Xcode 4 and for some reason my app won't run in the simulator or iOS device. It was working perfectly in Xcode 3, but all of a sudden now when I press run the program stops at "Attaching to...". There doesn't seem to be any other info to help with this problem either.

For summary you can try following things to tackle the issue:

Restart the simulator.

Make sure that you haven't included the Info.plist file in your Building Phases -> Copy Bundle Resources.

Resources folder added to the project as a folder reference (the blue folder icon). That caused the trouble, after adding the folder as a group the problem went away.

答:
I solved this problem how:

1) iOS Simulator->Reset Contents and Settings...

2) Sure project name, scheme name and target name is identical. "AppName" and "Appname" is not true. Must be "AppName" and "AppName", or "Appname" and "Appname".

3) Restart XCode and Quit Simulator.

Project name at Build Settings->Product Name.

Scheme name at Product->Manage Schemes. Click on current scheme once for rename.

Target name at Column of Project with Targets. Click once on current target for rename.

Good luck =)


问:
Python: How to refresh the turtle window
is there some kind of method to refresh the turtle screen while keeping the turtle drawings and the pen having the same attributes, it's kind of like reloading a page but it still has the same content</p>

答:
There is a way to do that
and you can do it by:</p>
```<code>t = turtle.Turtle()
t.clear()
</code>```

Body:
There is a way to do that
and you can do it by:

t = turtle.Turtle()
t.clear()


问:
Cant output answer buttons and sort them in my project
im trying to make a quizz project fetching api of quiz with answers and questions im so in the api
there is array of wrong answers(3) and one correct answer i try to output them as buttons and i outtput the 3 wrong answers so i thought i would push the correct answer into the wrong answers array and then randomly sort them and output as answers but i get the errot that array of answers isnt iterable can anyone help me to solve this problem and tell me if im going in the right direction or not ?</p>
```<code>
import './App.css';
import axios from 'axios'
import {useState,useEffect} from 'react'

function App() {
  const [quiz,setQuiz] = useState([])
  const [answer,setAnswer] = useState([])
  useEffect(()=>{
    axios.get('https://opentdb.com/api.php?amount=10')
    .then(res=>{

      setQuiz(res.data.results[0])

       setAnswer([...quiz.incorrect_answers, quiz.correct_answer])
    })
    .catch(err=>{
      console.log(err);
    })

  },[])

  return (
    <div className="App">
   <h1>{quiz.question}</h1>
   {answer && answer?.map(answers =>
   <button key={answers}>{answers}</button>)

   }
    </div>

  );
}

export default App;
</code>```

答:
```<code>useEffect(()=>{
    axios.get('https://opentdb.com/api.php?amount=10')
    .then(res=>{
       setQuiz(res.data.results[0])
       let tempVar = res.data.results[0] ;
       setAnswer([...tempVar.incorrect_answers, tempVar.correct_answer])
    })
    .catch(err=>{
      console.log(err);
    })

  },[])

</code>```

Your useEffect should look like this.
As changing a state is an asynchronous task .
That is why you are getting error that quiz.incorrect_answers is not iterable.
I hope this solves your issue .

Body:
im trying to make a quizz project fetching api of quiz with answers and questions im so in the api
there is array of wrong answers(3) and one correct answer i try to output them as buttons and i outtput the 3 wrong answers so i thought i would push the correct answer into the wrong answers array and then randomly sort them and output as answers but i get the errot that array of answers isnt iterable can anyone help me to solve this problem and tell me if im going in the right direction or not ?

import './App.css';
import axios from 'axios'
import {useState,useEffect} from 'react'

function App() {
  const [quiz,setQuiz] = useState([])
  const [answer,setAnswer] = useState([])
  useEffect(()=>{
    axios.get('https://opentdb.com/api.php?amount=10')
    .then(res=>{

      setQuiz(res.data.results[0])

       setAnswer([...quiz.incorrect_answers, quiz.correct_answer])
    })
    .catch(err=>{
      console.log(err);
    })

  },[])

  return (

{quiz.question}

   {answer && answer?.map(answers =>
   <button key={answers}>{answers}</button>)

   }

  );
}

export default App;

Body:
useEffect(()=>{
    axios.get('https://opentdb.com/api.php?amount=10')
    .then(res=>{
       setQuiz(res.data.results[0])
       let tempVar = res.data.results[0] ;
       setAnswer([...tempVar.incorrect_answers, tempVar.correct_answer])
    })
    .catch(err=>{
      console.log(err);
    })

  },[])

Your useEffect should look like this.
As changing a state is an asynchronous task .
That is why you are getting error that quiz.incorrect_answers is not iterable.
I hope this solves your issue .


问:
Get a specific text value from an HTML table using python and selenium
This website (https://egov.uscis.gov/processing-times/) shows the processing time for different immigration applications for different service centers.
There are two drop-down menus; first is the Form (immigration application), and second is the service center. Once you select a value from these two menus and hit the "Get processing time" button, a table will be displayed which shows the details for different immigration categories/types (you have to scroll down a bit to be able to see the table)(the table has three column titles: "Estimated time range", "Form type", "Receipt date for a case inquiry").
I want to use selenium with python to automate printing out the current range for processing time for form I-765 in Texas Service Center for the category of "Based on a pending I-485 adjustment application [(c)(9)]", which is the sixth row in the table.

As of 2/5/2022, I want my code to print out a text as: "11.5 Months to 13.5 Months".

Here is my attempt so far, but it only prints an empty string.

It opens the website, selects the right Form and then the right service center, and hits the button. But it fails to fetch the text I want from the table.

What if I want to print out all the text values in the 6th row?

```<code> from selenium import webdriver
 from selenium.webdriver.support.ui import Select
 import time

 browser = webdriver.Chrome('C:\ChromeDriver\chromedriver')
 browser.get('https://egov.uscis.gov/processing-times/')

 form_menu = browser.find_element_by_id('selectForm')
 select_form_menu = Select(form_menu)
 select_form = select_form_menu.select_by_visible_text('I-765 | Application for Employment Authorization')

 time.sleep(2)

 office_menu = browser.find_element_by_id('officeOrCenter')
 select_office_menu = Select(office_menu)
 select_office = select_office_menu.select_by_visible_text('Texas Service Center')

 time.sleep(2)

 search_btn = browser.find_element_by_id('getProcTimes')
 search_btn.click()

 time.sleep(2)

 table = browser.find_element_by_id('resultList')
 items = table.find_elements_by_id('est') #here I am trying to return a list of all the values in the first column.

 print(items[5].text) #my value of interest is the 6th element in the list (6th row in the table).
</code>```

答:
The Element is hidden as the table is collapsed. The text is not visible in UI. so webdriver doesnt show the text as .text will show only visible text.

While innerText will consider the the visibility style but of child elements only not on the element it self:

Eg:

console.log("outer.textContent:", outer.textContent);
console.log("outer.innerText:", outer.innerText);
console.log("inner.textContent:", inner.textContent);
console.log("inner.innerText:", inner.innerText);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="outer" style="display: none;" >This is visible <span id="inner" >This is invisible</span></div></code>```

https://stackoverflow.com/a/68809991/6793637

Here outer display is none but we still see the innerText . Because:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText#value

Value

A DOMString representing the rendered text content of an
element. If the element itself is not being rendered (e.g detached
from the document or is hidden from view), the returned value is the
same as the Node.textContent property.

Body:
This website (https://egov.uscis.gov/processing-times/) shows the processing time for different immigration applications for different service centers.
There are two drop-down menus; first is the Form (immigration application), and second is the service center. Once you select a value from these two menus and hit the "Get processing time" button, a table will be displayed which shows the details for different immigration categories/types (you have to scroll down a bit to be able to see the table)(the table has three column titles: "Estimated time range", "Form type", "Receipt date for a case inquiry").
I want to use selenium with python to automate printing out the current range for processing time for form I-765 in Texas Service Center for the category of "Based on a pending I-485 adjustment application [(c)(9)]", which is the sixth row in the table.

As of 2/5/2022, I want my code to print out a text as: "11.5 Months to 13.5 Months".

Here is my attempt so far, but it only prints an empty string.

It opens the website, selects the right Form and then the right service center, and hits the button. But it fails to fetch the text I want from the table.

What if I want to print out all the text values in the 6th row?

 from selenium import webdriver
 from selenium.webdriver.support.ui import Select
 import time

 browser = webdriver.Chrome('C:\ChromeDriver\chromedriver')
 browser.get('https://egov.uscis.gov/processing-times/')

 form_menu = browser.find_element_by_id('selectForm')
 select_form_menu = Select(form_menu)
 select_form = select_form_menu.select_by_visible_text('I-765 | Application for Employment Authorization')

 time.sleep(2)

 office_menu = browser.find_element_by_id('officeOrCenter')
 select_office_menu = Select(office_menu)
 select_office = select_office_menu.select_by_visible_text('Texas Service Center')

 time.sleep(2)

 search_btn = browser.find_element_by_id('getProcTimes')
 search_btn.click()

 time.sleep(2)

 table = browser.find_element_by_id('resultList')
 items = table.find_elements_by_id('est') #here I am trying to return a list of all the values in the first column.

 print(items[5].text) #my value of interest is the 6th element in the list (6th row in the table).

Body:
The Element is hidden as the table is collapsed. The text is not visible in UI. so webdriver doesnt show the text as .text will show only visible text.

While innerText will consider the the visibility style but of child elements only not on the element it self:

Eg:

console.log("outer.textContent:", outer.textContent);
console.log("outer.innerText:", outer.innerText);
console.log("inner.textContent:", inner.textContent);
console.log("inner.innerText:", inner.innerText);

<div id="outer" style="display: none;" >This is visible <span id="inner" >This is invisible</span></div>

https://stackoverflow.com/a/68809991/6793637

Here outer display is none but we still see the innerText . Because:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText#value

Value

A DOMString representing the rendered text content of an
element. If the element itself is not being rendered (e.g detached
from the document or is hidden from view), the returned value is the
same as the Node.textContent property.


问:
Query where column match one or all, according to an argument
Sorry if this is basic. I have a function that get as an argument one of these 2 :

```<code>subjects ['ALL']. //search for any subject
subjects ['A','B','C'] //only one of these
</code>```

So in my function I need to query according to subjects argument

```<code>def function (subjects):

    query = ('''
                SELECT date_num, subject, in_col
                FROM base
                WHERE subject in {subjects} // = subject in ('A','B','C') works, but what about ALL ?

        ''').format(subjects=subjects)
</code>```

so when the subjects to be found are a,b,c there is no problem, but how can I tell it to search for ALL subjects in the case argument is ALL ?

Could I send * instead ? like subjects[*] ?

(I do turn the ['a','b'] into ('a','b') in my code )

答:
```<code>subjects = ['ALL']
# subjects = ['A', 'B']
where_clause = f"WHERE subject in {tuple(subjects)}" if subjects[0] != "ALL" else ""

query = f'''SELECT date_num, subject, in_col FROM base {where_clause}'''
</code>```

Try uncommenting the second line to check how the query modifies

Body:
Sorry if this is basic. I have a function that get as an argument one of these 2 :

subjects ['ALL']. //search for any subject
subjects ['A','B','C'] //only one of these

So in my function I need to query according to subjects argument

def function (subjects):

    query = ('''
                SELECT date_num, subject, in_col
                FROM base
                WHERE subject in {subjects} // = subject in ('A','B','C') works, but what about ALL ?

        ''').format(subjects=subjects)

so when the subjects to be found are a,b,c there is no problem, but how can I tell it to search for ALL subjects in the case argument is ALL ?

Could I send * instead ? like subjects[*] ?

(I do turn the ['a','b'] into ('a','b') in my code )

Body:
subjects = ['ALL']
# subjects = ['A', 'B']
where_clause = f"WHERE subject in {tuple(subjects)}" if subjects[0] != "ALL" else ""

query = f'''SELECT date_num, subject, in_col FROM base {where_clause}'''

Try uncommenting the second line to check how the query modifies


问:
Change column width in datatable (with URLs in one column or without)
This is my first question here, so please let me know if I'm doing anything wrong.

For some days, I've been trying to format a table in a Shiny App, I tried everything, but I'm just completely stuck.

I have a table that should ideally include 14 columns, most of which can be very narrow. There are 2 columns with long strings however, one with normal text, and one with URLs (sources for the information in the text column). I want the first one to be wide so that the text is easily readable, and I don't care too much about the URL column. I read somewhere that datatable automatically tries to fit columns to the longest word and I see that that could be the problem here, because no matter how I try to set the column width, the URL column ends up very wide and the other ones (including the text column) narrow. But I think I might have 2 separate problems:

Problem 1:

I tried to produce a minimal reproducible example and I figured out that indeed it seems to be the URL column that messes up everything.

```<code>library(data.table)
library(DT)
var1 <- rep(seq(as.Date("2020-01-01"), as.Date("2020-01-10"), by="days"), each=5 )
var2 <- rep(c("a", "b", "c", "d", "e"), each=10)
var3 <- c(rep(NA, 10), "This is a non-empty entry.", rep(NA, 5), "yet another text. oh wow, this one is long. in the real world, there are even longer texts,", rep(NA, 2), "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "Every 60 seconds in Africa a minute passes", rep(NA, 20), "some more dummy text", rep(NA, 8))
var4 <- c(rep(NA, 10), "https://stackoverflow.com/questions/55208855/how-to-set-column-width-in-r-shiny-data-table", rep(NA, 5), "https://stackoverflow.com/questions/25205410/r-shiny-set-datatable-column-width?noredirect=1&lq=1", rep(NA, 2), "https://www.youtube.com/watch?v=sAn7baRbhx4", "https://www.timeanddate.com/weather/antarctica", rep(NA, 20), "https://www.theguardian.com/football/live/2022/feb/06/senegal-v-egypt-africa-cup-of-nations-final-live-score-updates", rep(NA,8))
var5 <- c(1:50)
var6 <- c(21:70)
df <- data.table(var1, var2, var3, var4, var5, var6)
selection <- datatable(
  df[var3!="NA", c("var1", "var2", "var3", "var4", "var6")],
  options=list(
    scrollX=TRUE,
    autoWidth=TRUE,
    columnDefs=list((list(targets=c(1,2), visible=TRUE, width='5%')), (list(targets=c(3), visible=TRUE, width='80%')), (list(targets=c(4,5), visible=TRUE, width='5%')))))
</code>```

Screenshot: https://i.ibb.co/qkxw6Hm/Screenshot-from-2022-02-07-12-20-57.png

...whereas if I don't include the URL column:

```<code>library(data.table)
library(DT)
var1 <- rep(seq(as.Date("2020-01-01"), as.Date("2020-01-10"), by="days"), each=5 )
var2 <- rep(c("a", "b", "c", "d", "e"), each=10)
var3 <- c(rep(NA, 10), "This is a non-empty entry.", rep(NA, 5), "yet another text. oh wow, this one is long. in the real world, there are even longer texts,", rep(NA, 2), "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "Every 60 seconds in Africa a minute passes", rep(NA, 20), "some more dummy text", rep(NA, 8))
var4 <- c(rep(NA, 10), "https://stackoverflow.com/questions/55208855/how-to-set-column-width-in-r-shiny-data-table", rep(NA, 5), "https://stackoverflow.com/questions/25205410/r-shiny-set-datatable-column-width?noredirect=1&lq=1", rep(NA, 2), "https://www.youtube.com/watch?v=sAn7baRbhx4", "https://www.timeanddate.com/weather/antarctica", rep(NA, 20), "https://www.theguardian.com/football/live/2022/feb/06/senegal-v-egypt-africa-cup-of-nations-final-live-score-updates", rep(NA,8))
var5 <- c(1:50)
var6 <- c(21:70)
df <- data.table(var1, var2, var3, var4, var5, var6)
selection <- datatable(
  df[var3!="NA", c("var1", "var2", "var3", "var6")],
  options=list(
    scrollX=TRUE,
    autoWidth=TRUE,
    columnDefs=list((list(targets=c(1,2), visible=TRUE, width='5%')), (list(targets=c(3), visible=TRUE, width='85%')), (list(targets=c(4), visible=TRUE, width='5%')))))

</code>```

Screenshot: https://i.ibb.co/rsgvD2b/Screenshot-from-2022-02-07-12-24-35.png

Do you have any advice how to handle this problem? Is there a way to format URLs in a datatable so that you would only show a short text as a clickable link? Or is there a way to force DT to squeeze the column despite the long "words"?

Problem 2:

Actually, I already gave up and decided to drop the column with URLs and tell the reader that they should download the .csv file if they want to see the sources. But in my real Shiny App setting the column width doesn't work anyway. Here's the code for my actual table, without the URL column:

```<code>    output$selection <- renderDT(DT::datatable(
        df[country==input$selection&change!="NA", c("date", "country", "change", "strictest_night", "strictest_day", "least_strict_night", "least_strict_day", "stayhome_day", "stayhome_night", "walk_day", "walk_night", "leave_municip", "outside_masks", "difference_with_oxcgrt")],
                                 options=list(
                                     scrollX=TRUE,
                                     autoWidth=TRUE,
                                     columnDefs=list((list(targets=c(1, 2), visible=TRUE, width='5%')), (list(targets=c(3), visible=TRUE, width='35%')), (list(targets=c(4:14), visible=TRUE, width='5%'))))))
</code>```

And here's how I call the table in the UI:

```<code>           selectInput("selection","select country/territory", choices=unique(df$country)),
           tags$style(HTML("
                    .dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_processing, .dataTables_wrapper .dataTables_paginate {
                    color: #ffffff;
                    }

                    thead {
                    color: #ffffff;
                    }
                    "
                    )),
           DTOutput("selection")
</code>```

It's in the main panel, there is a tabset panel above, but I don't think that should matter. I thought the mistake could be in the HTML style code, because frankly, I just copied that from somewhere. But I commented it out and I still have the same problem. What could be the problem then? Do I have too many columns?

Here's how the table looks like: https://i.ibb.co/XZ6hNH5/Screenshot-from-2022-02-07-13-07-43.png

Thank you so much!

SOLUTION FOUND:
danlooo has answered problem 1. Thanks again! For problem 2 I found the solution here: Setting column width in R Shiny DataTable does not work in case of lots of column I saw this thread already and thought I had tried everything, but I missed something: I need to specify the width of the DToutput itself. I thought it's enough to specify the main panel width, but it isn't. I left everything the same, just added a width argument when I called the table in the UI: DTOutput("selection", width="2000px") ... and it works!

答:
You can create a HTML link instead of just showing the URL as a raw text, if you use datatable(escape = FALSE):

```<code>library(data.table)
library(DT)
var1 <- rep(seq(as.Date("2020-01-01"), as.Date("2020-01-10"), by = "days"), each = 5)
var2 <- rep(c("a", "b", "c", "d", "e"), each = 10)
var3 <- c(rep(NA, 10), "This is a non-empty entry.", rep(NA, 5), "yet another text. oh wow, this one is long. in the real world, there are even longer texts,", rep(NA, 2), "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "Every 60 seconds in Africa a minute passes", rep(NA, 20), "some more dummy text", rep(NA, 8))
var4 <- c(rep(NA, 10), "https://stackoverflow.com/questions/55208855/how-to-set-column-width-in-r-shiny-data-table", rep(NA, 5), "https://stackoverflow.com/questions/25205410/r-shiny-set-datatable-column-width?noredirect=1&lq=1", rep(NA, 2), "https://www.youtube.com/watch?v=sAn7baRbhx4", "https://www.timeanddate.com/weather/antarctica", rep(NA, 20), "https://www.theguardian.com/football/live/2022/feb/06/senegal-v-egypt-africa-cup-of-nations-final-live-score-updates", rep(NA, 8))
var5 <- c(1:50)
var6 <- c(21:70)
df <- data.table(var1, var2, var3, var4, var5, var6)

# Transform text to HTML
df$var4 <- sapply(df$var4, function(x) paste0("<a href=\"", x, '\">link</a>'))

datatable(
  escape = FALSE,
  df[var3 != "NA", c("var1", "var2", "var3", "var4", "var6")],
  options = list(
    scrollX = TRUE,
    autoWidth = TRUE,
    columnDefs = list((list(targets = c(1, 2), visible = TRUE, width = "5%")), (list(targets = c(3), visible = TRUE, width = "80%")), (list(targets = c(4, 5), visible = TRUE, width = "5%")))
  )
)
</code>```

Body:
This is my first question here, so please let me know if I'm doing anything wrong.

For some days, I've been trying to format a table in a Shiny App, I tried everything, but I'm just completely stuck.

I have a table that should ideally include 14 columns, most of which can be very narrow. There are 2 columns with long strings however, one with normal text, and one with URLs (sources for the information in the text column). I want the first one to be wide so that the text is easily readable, and I don't care too much about the URL column. I read somewhere that datatable automatically tries to fit columns to the longest word and I see that that could be the problem here, because no matter how I try to set the column width, the URL column ends up very wide and the other ones (including the text column) narrow. But I think I might have 2 separate problems:

Problem 1:

I tried to produce a minimal reproducible example and I figured out that indeed it seems to be the URL column that messes up everything.

library(data.table)
library(DT)
var1 <- rep(seq(as.Date("2020-01-01"), as.Date("2020-01-10"), by="days"), each=5 )
var2 <- rep(c("a", "b", "c", "d", "e"), each=10)
var3 <- c(rep(NA, 10), "This is a non-empty entry.", rep(NA, 5), "yet another text. oh wow, this one is long. in the real world, there are even longer texts,", rep(NA, 2), "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "Every 60 seconds in Africa a minute passes", rep(NA, 20), "some more dummy text", rep(NA, 8))
var4 <- c(rep(NA, 10), "https://stackoverflow.com/questions/55208855/how-to-set-column-width-in-r-shiny-data-table", rep(NA, 5), "https://stackoverflow.com/questions/25205410/r-shiny-set-datatable-column-width?noredirect=1&lq=1", rep(NA, 2), "https://www.youtube.com/watch?v=sAn7baRbhx4", "https://www.timeanddate.com/weather/antarctica", rep(NA, 20), "https://www.theguardian.com/football/live/2022/feb/06/senegal-v-egypt-africa-cup-of-nations-final-live-score-updates", rep(NA,8))
var5 <- c(1:50)
var6 <- c(21:70)
df <- data.table(var1, var2, var3, var4, var5, var6)
selection <- datatable(
  df[var3!="NA", c("var1", "var2", "var3", "var4", "var6")],
  options=list(
    scrollX=TRUE,
    autoWidth=TRUE,
    columnDefs=list((list(targets=c(1,2), visible=TRUE, width='5%')), (list(targets=c(3), visible=TRUE, width='80%')), (list(targets=c(4,5), visible=TRUE, width='5%')))))

Screenshot: https://i.ibb.co/qkxw6Hm/Screenshot-from-2022-02-07-12-20-57.png

...whereas if I don't include the URL column:

library(data.table)
library(DT)
var1 <- rep(seq(as.Date("2020-01-01"), as.Date("2020-01-10"), by="days"), each=5 )
var2 <- rep(c("a", "b", "c", "d", "e"), each=10)
var3 <- c(rep(NA, 10), "This is a non-empty entry.", rep(NA, 5), "yet another text. oh wow, this one is long. in the real world, there are even longer texts,", rep(NA, 2), "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "Every 60 seconds in Africa a minute passes", rep(NA, 20), "some more dummy text", rep(NA, 8))
var4 <- c(rep(NA, 10), "https://stackoverflow.com/questions/55208855/how-to-set-column-width-in-r-shiny-data-table", rep(NA, 5), "https://stackoverflow.com/questions/25205410/r-shiny-set-datatable-column-width?noredirect=1&lq=1", rep(NA, 2), "https://www.youtube.com/watch?v=sAn7baRbhx4", "https://www.timeanddate.com/weather/antarctica", rep(NA, 20), "https://www.theguardian.com/football/live/2022/feb/06/senegal-v-egypt-africa-cup-of-nations-final-live-score-updates", rep(NA,8))
var5 <- c(1:50)
var6 <- c(21:70)
df <- data.table(var1, var2, var3, var4, var5, var6)
selection <- datatable(
  df[var3!="NA", c("var1", "var2", "var3", "var6")],
  options=list(
    scrollX=TRUE,
    autoWidth=TRUE,
    columnDefs=list((list(targets=c(1,2), visible=TRUE, width='5%')), (list(targets=c(3), visible=TRUE, width='85%')), (list(targets=c(4), visible=TRUE, width='5%')))))

Screenshot: https://i.ibb.co/rsgvD2b/Screenshot-from-2022-02-07-12-24-35.png

Do you have any advice how to handle this problem? Is there a way to format URLs in a datatable so that you would only show a short text as a clickable link? Or is there a way to force DT to squeeze the column despite the long "words"?

Problem 2:

Actually, I already gave up and decided to drop the column with URLs and tell the reader that they should download the .csv file if they want to see the sources. But in my real Shiny App setting the column width doesn't work anyway. Here's the code for my actual table, without the URL column:

    output$selection <- renderDT(DT::datatable(
        df[country==input$selection&change!="NA", c("date", "country", "change", "strictest_night", "strictest_day", "least_strict_night", "least_strict_day", "stayhome_day", "stayhome_night", "walk_day", "walk_night", "leave_municip", "outside_masks", "difference_with_oxcgrt")],
                                 options=list(
                                     scrollX=TRUE,
                                     autoWidth=TRUE,
                                     columnDefs=list((list(targets=c(1, 2), visible=TRUE, width='5%')), (list(targets=c(3), visible=TRUE, width='35%')), (list(targets=c(4:14), visible=TRUE, width='5%'))))))

And here's how I call the table in the UI:

           selectInput("selection","select country/territory", choices=unique(df$country)),
           tags$style(HTML("
                    .dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_processing, .dataTables_wrapper .dataTables_paginate {
                    color: #ffffff;
                    }

                    thead {
                    color: #ffffff;
                    }
                    "
                    )),
           DTOutput("selection")

It's in the main panel, there is a tabset panel above, but I don't think that should matter. I thought the mistake could be in the HTML style code, because frankly, I just copied that from somewhere. But I commented it out and I still have the same problem. What could be the problem then? Do I have too many columns?

Here's how the table looks like: https://i.ibb.co/XZ6hNH5/Screenshot-from-2022-02-07-13-07-43.png

Thank you so much!

SOLUTION FOUND:
danlooo has answered problem 1. Thanks again! For problem 2 I found the solution here: Setting column width in R Shiny DataTable does not work in case of lots of column I saw this thread already and thought I had tried everything, but I missed something: I need to specify the width of the DToutput itself. I thought it's enough to specify the main panel width, but it isn't. I left everything the same, just added a width argument when I called the table in the UI: DTOutput("selection", width="2000px") ... and it works!

Body:
You can create a HTML link instead of just showing the URL as a raw text, if you use datatable(escape = FALSE):

library(data.table)
library(DT)
var1 <- rep(seq(as.Date("2020-01-01"), as.Date("2020-01-10"), by = "days"), each = 5)
var2 <- rep(c("a", "b", "c", "d", "e"), each = 10)
var3 <- c(rep(NA, 10), "This is a non-empty entry.", rep(NA, 5), "yet another text. oh wow, this one is long. in the real world, there are even longer texts,", rep(NA, 2), "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "Every 60 seconds in Africa a minute passes", rep(NA, 20), "some more dummy text", rep(NA, 8))
var4 <- c(rep(NA, 10), "https://stackoverflow.com/questions/55208855/how-to-set-column-width-in-r-shiny-data-table", rep(NA, 5), "https://stackoverflow.com/questions/25205410/r-shiny-set-datatable-column-width?noredirect=1&lq=1", rep(NA, 2), "https://www.youtube.com/watch?v=sAn7baRbhx4", "https://www.timeanddate.com/weather/antarctica", rep(NA, 20), "https://www.theguardian.com/football/live/2022/feb/06/senegal-v-egypt-africa-cup-of-nations-final-live-score-updates", rep(NA, 8))
var5 <- c(1:50)
var6 <- c(21:70)
df <- data.table(var1, var2, var3, var4, var5, var6)

# Transform text to HTML
df$var4 <- sapply(df$var4, function(x) paste0("<a href=\"", x, '\">link</a>'))

datatable(
  escape = FALSE,
  df[var3 != "NA", c("var1", "var2", "var3", "var4", "var6")],
  options = list(
    scrollX = TRUE,
    autoWidth = TRUE,
    columnDefs = list((list(targets = c(1, 2), visible = TRUE, width = "5%")), (list(targets = c(3), visible = TRUE, width = "80%")), (list(targets = c(4, 5), visible = TRUE, width = "5%")))
  )
)


问:
How could I make this LINQ query more efficient?
Any suggestions on how to make this LINQ query more efficient? I recently created the formattedDate variable as previously I was calling the GetDateInFormat multiple times.

```<code>    if (customerOrder.OrderLines
          .SelectMany(ol => ol.OrderDates)
          .Where(ol => ol.DateTypeId == "OrderPickUpFrom" && ol.ActualDate != null)
          .Any())
    {
        var date = customerOrder.OrderLines
          .SelectMany(ol => ol.OrderDates)
          .OrderBy(d => d.ActualDate)
          .FirstOrDefault(d => d.DateTypeId == "OrderPickUpFrom" && d.ActualDate != null)
          .ActualDate;

        if (date != null)
        {
            var formattedDate = _dateHelper.GetDateInFormat("DD/MM/YYYY", date);
            order.ArriveDate = formattedDate;
            order.EarliestShipDate = formattedDate;
            order.EarliestDeliveryDate = formattedDate;
            order.EarliestApptTime = _dateHelper.GetDateInFormat("HHMM", date);
        }
    }
</code>```

The customerOrder is a customer Order class.

```<code>public class Order
{
    public Order();

    public List<OrderLine> OrderLines { get; set; }
}

public class OrderLine
{
    public OrderLine();

    public List<OrderDate> OrderDates { get; set; }
}

public class OrderDate
{
    public OrderDate();

    public DateTimeOffset? ActualDate { get; set; }
    public string DateTypeId { get; set; }
}
</code>```

答:
I would suggest using .SelectMany(), .Where() and .Min() as follows:

```<code>var date = customerOrder.OrderLines
    .SelectMany(ol => ol.OrderDates)
    .Where(ol => ol.DateTypeId == "OrderPickUpFrom")
    .Min(ol => ol.ActualDate);
</code>```

.Min() will return null when the result from .Where() is empty.

Body:
Any suggestions on how to make this LINQ query more efficient? I recently created the formattedDate variable as previously I was calling the GetDateInFormat multiple times.

    if (customerOrder.OrderLines
          .SelectMany(ol => ol.OrderDates)
          .Where(ol => ol.DateTypeId == "OrderPickUpFrom" && ol.ActualDate != null)
          .Any())
    {
        var date = customerOrder.OrderLines
          .SelectMany(ol => ol.OrderDates)
          .OrderBy(d => d.ActualDate)
          .FirstOrDefault(d => d.DateTypeId == "OrderPickUpFrom" && d.ActualDate != null)
          .ActualDate;

        if (date != null)
        {
            var formattedDate = _dateHelper.GetDateInFormat("DD/MM/YYYY", date);
            order.ArriveDate = formattedDate;
            order.EarliestShipDate = formattedDate;
            order.EarliestDeliveryDate = formattedDate;
            order.EarliestApptTime = _dateHelper.GetDateInFormat("HHMM", date);
        }
    }

The customerOrder is a customer Order class.

public class Order
{
    public Order();

    public List<OrderLine> OrderLines { get; set; }
}

public class OrderLine
{
    public OrderLine();

    public List<OrderDate> OrderDates { get; set; }
}

public class OrderDate
{
    public OrderDate();

    public DateTimeOffset? ActualDate { get; set; }
    public string DateTypeId { get; set; }
}

Body:
I would suggest using .SelectMany(), .Where() and .Min() as follows:

var date = customerOrder.OrderLines
    .SelectMany(ol => ol.OrderDates)
    .Where(ol => ol.DateTypeId == "OrderPickUpFrom")
    .Min(ol => ol.ActualDate);

.Min() will return null when the result from .Where() is empty.


问:
Using anaconda environment in Atom
I've install Anaconda (Python 3.6) and  tensorflow (python 3.5).  I've managed to get it run both on Spyder and on sublime text 3( by making new build system). Now all the is using Atom( which I'm not used to). So I've trying to "tell" Atom to use python in the following folder: </p>

```<code>C:\users\engine\anaconda3\envs\tensorflow\python.exe
</code>```

<p>without any success, any idea how to do that or what kind of package should I use( I'm using windows so virtualenv)
thanks in advance ! </p>

答:
script package configuration (in atom) rather frustrated!:</p>
```<code>$ pwd
/home/<UserID>/.atom/packages/script
$ vim lib/grammars/python.js
  "File Based": {
    // me using miniconda here
    // command: "python", // orig
    command: "/opt/miniconda/bin/python",
</code>```

Title: Using anaconda environment in Atom

Body:
I've install Anaconda (Python 3.6) and  tensorflow (python 3.5).  I've managed to get it run both on Spyder and on sublime text 3( by making new build system). Now all the is using Atom( which I'm not used to). So I've trying to "tell" Atom to use python in the following folder:

C:\users\engine\anaconda3\envs\tensorflow\python.exe

without any success, any idea how to do that or what kind of package should I use( I'm using windows so virtualenv)
thanks in advance !

Body:
script package configuration (in atom) rather frustrated!:

$ pwd
/home/<UserID>/.atom/packages/script
$ vim lib/grammars/python.js
  "File Based": {
    // me using miniconda here
    // command: "python", // orig
    command: "/opt/miniconda/bin/python",


问:
Classpath resource not found when running as jar
Having this problem both in Spring Boot 1.1.5 and 1.1.6 - I'm loading a classpath resource using an @Value annotation, which works just fine when I run the application from within STS (3.6.0, Windows). However, when I run a mvn package and then try to run the jar, I get FileNotFound exceptions.

The resource, message.txt, is in src/main/resources. I've inspected the jar and verified that it contains the file "message.txt" at the top level (same level as application.properties).

Here's the application:

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application implements CommandLineRunner {

    private static final Logger logger = Logger.getLogger(Application.class);

    @Value("${message.file}")
    private Resource messageResource;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... arg0) throws Exception {
        // both of these work when running as Spring boot app from STS, but
        // fail after mvn package, and then running as java -jar
        testResource(new ClassPathResource("message.txt"));
        testResource(this.messageResource);
    }

    private void testResource(Resource resource) {
        try {
            resource.getFile();
            logger.debug("Found the resource " + resource.getFilename());
        } catch (IOException ex) {
            logger.error(ex.toString());
        }
    }
}
```

<p>The exception:</p>

```c:\Users\glyoder\Documents\workspace-sts-3.5.1.RELEASE\classpath-resource-proble
m\target>java -jar demo-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.1.5.RELEASE)

2014-09-16 08:46:34.635  INFO 5976 --- [           main] demo.Application
                  : Starting Application on 8W59XV1 with PID 5976 (C:\Users\glyo
der\Documents\workspace-sts-3.5.1.RELEASE\classpath-resource-problem\target\demo
-0.0.1-SNAPSHOT.jar started by glyoder in c:\Users\glyoder\Documents\workspace-s
ts-3.5.1.RELEASE\classpath-resource-problem\target)
2014-09-16 08:46:34.640 DEBUG 5976 --- [           main] demo.Application
                  : Running with Spring Boot v1.1.5.RELEASE, Spring v4.0.6.RELEA
SE
2014-09-16 08:46:34.681  INFO 5976 --- [           main] s.c.a.AnnotationConfigA
pplicationContext : Refreshing org.springframework.context.annotation.Annotation
ConfigApplicationContext@1c77b086: startup date [Tue Sep 16 08:46:34 EDT 2014];
root of context hierarchy
2014-09-16 08:46:35.196  INFO 5976 --- [           main] o.s.j.e.a.AnnotationMBe
anExporter        : Registering beans for JMX exposure on startup
2014-09-16 08:46:35.210 ERROR 5976 --- [           main] demo.Application
                  : java.io.FileNotFoundException: class path resource [message.
txt] cannot be resolved to absolute file path because it does not reside in the
file system: jar:file:/C:/Users/glyoder/Documents/workspace-sts-3.5.1.RELEASE/cl
asspath-resource-problem/target/demo-0.0.1-SNAPSHOT.jar!/message.txt
2014-09-16 08:46:35.211 ERROR 5976 --- [           main] demo.Application
                  : java.io.FileNotFoundException: class path resource [message.
txt] cannot be resolved to absolute file path because it does not reside in the
file system: jar:file:/C:/Users/glyoder/Documents/workspace-sts-3.5.1.RELEASE/cl
asspath-resource-problem/target/demo-0.0.1-SNAPSHOT.jar!/message.txt
2014-09-16 08:46:35.215  INFO 5976 --- [           main] demo.Application
                  : Started Application in 0.965 seconds (JVM running for 1.435)

2014-09-16 08:46:35.217  INFO 5976 --- [       Thread-2] s.c.a.AnnotationConfigA
pplicationContext : Closing org.springframework.context.annotation.AnnotationCon
figApplicationContext@1c77b086: startup date [Tue Sep 16 08:46:34 EDT 2014]; roo
t of context hierarchy
2014-09-16 08:46:35.218  INFO 5976 --- [       Thread-2] o.s.j.e.a.AnnotationMBe
anExporter        : Unregistering JMX-exposed beans on shutdown
```

答:
Solution is correct as per the accepted answer. I am giving my solution to read the Stream to String more efficiently (using StreamUtils) instead of trying to create a temp file and read text.

```<code>  @Bean
  public String readFromResource(final @Value("classpath:data/message.txt") Resource messageFile)
      throws IOException {
    return StreamUtils.copyToString(messageFile.getInputStream(), StandardCharsets.UTF_8);
  }
</code>```

Body:
Having this problem both in Spring Boot 1.1.5 and 1.1.6 - I'm loading a classpath resource using an @Value annotation, which works just fine when I run the application from within STS (3.6.0, Windows). However, when I run a mvn package and then try to run the jar, I get FileNotFound exceptions.

The resource, message.txt, is in src/main/resources. I've inspected the jar and verified that it contains the file "message.txt" at the top level (same level as application.properties).

Here's the application:

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application implements CommandLineRunner {

    private static final Logger logger = Logger.getLogger(Application.class);

    @Value("${message.file}")
    private Resource messageResource;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... arg0) throws Exception {
        // both of these work when running as Spring boot app from STS, but
        // fail after mvn package, and then running as java -jar
        testResource(new ClassPathResource("message.txt"));
        testResource(this.messageResource);
    }

    private void testResource(Resource resource) {
        try {
            resource.getFile();
            logger.debug("Found the resource " + resource.getFilename());
        } catch (IOException ex) {
            logger.error(ex.toString());
        }
    }
}

The exception:

c:\Users\glyoder\Documents\workspace-sts-3.5.1.RELEASE\classpath-resource-proble
m\target>java -jar demo-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.1.5.RELEASE)

2014-09-16 08:46:34.635  INFO 5976 --- [           main] demo.Application
                  : Starting Application on 8W59XV1 with PID 5976 (C:\Users\glyo
der\Documents\workspace-sts-3.5.1.RELEASE\classpath-resource-problem\target\demo
-0.0.1-SNAPSHOT.jar started by glyoder in c:\Users\glyoder\Documents\workspace-s
ts-3.5.1.RELEASE\classpath-resource-problem\target)
2014-09-16 08:46:34.640 DEBUG 5976 --- [           main] demo.Application
                  : Running with Spring Boot v1.1.5.RELEASE, Spring v4.0.6.RELEA
SE
2014-09-16 08:46:34.681  INFO 5976 --- [           main] s.c.a.AnnotationConfigA
pplicationContext : Refreshing org.springframework.context.annotation.Annotation
ConfigApplicationContext@1c77b086: startup date [Tue Sep 16 08:46:34 EDT 2014];
root of context hierarchy
2014-09-16 08:46:35.196  INFO 5976 --- [           main] o.s.j.e.a.AnnotationMBe
anExporter        : Registering beans for JMX exposure on startup
2014-09-16 08:46:35.210 ERROR 5976 --- [           main] demo.Application
                  : java.io.FileNotFoundException: class path resource [message.
txt] cannot be resolved to absolute file path because it does not reside in the
file system: jar:file:/C:/Users/glyoder/Documents/workspace-sts-3.5.1.RELEASE/cl
asspath-resource-problem/target/demo-0.0.1-SNAPSHOT.jar!/message.txt
2014-09-16 08:46:35.211 ERROR 5976 --- [           main] demo.Application
                  : java.io.FileNotFoundException: class path resource [message.
txt] cannot be resolved to absolute file path because it does not reside in the
file system: jar:file:/C:/Users/glyoder/Documents/workspace-sts-3.5.1.RELEASE/cl
asspath-resource-problem/target/demo-0.0.1-SNAPSHOT.jar!/message.txt
2014-09-16 08:46:35.215  INFO 5976 --- [           main] demo.Application
                  : Started Application in 0.965 seconds (JVM running for 1.435)

2014-09-16 08:46:35.217  INFO 5976 --- [       Thread-2] s.c.a.AnnotationConfigA
pplicationContext : Closing org.springframework.context.annotation.AnnotationCon
figApplicationContext@1c77b086: startup date [Tue Sep 16 08:46:34 EDT 2014]; roo
t of context hierarchy
2014-09-16 08:46:35.218  INFO 5976 --- [       Thread-2] o.s.j.e.a.AnnotationMBe
anExporter        : Unregistering JMX-exposed beans on shutdown

Body:
Solution is correct as per the accepted answer. I am giving my solution to read the Stream to String more efficiently (using StreamUtils) instead of trying to create a temp file and read text.

  @Bean
  public String readFromResource(final @Value("classpath:data/message.txt") Resource messageFile)
      throws IOException {
    return StreamUtils.copyToString(messageFile.getInputStream(), StandardCharsets.UTF_8);
  }


问:
how do i remove the empty lines in the output?
so im trying to make a kind of keylogger which tracks your keyboard and whenever the user exits the program it will save in a text file. However if the user presses space it will leave a full line empty and i am trying to fix it. UPDATE, i have fixed it thank you guys! <3</p>
```<code>import pynput

from pynput.keyboard import Key, Listener

count = 0
keys = []

def on_press (key) :
    global keys, count

    keys.append(key)
    count += 1
    print('{0} pressed'.format(key))

    if count >= 10:
        count += 1
        write_file(keys)
        keys = []

def write_file(keys):
    with open('log.txt', 'a') as f:
        for key in keys :
            k = str(key).replace("'","")
            if k.find('space') > 0:
                f.write('\n')
            elif k.find('Key') == -1:
                f.write(k)

def on_release(key) :
    if key == Key.esc:
        return False

with Listener (on_press=on_press, on_release=on_release) as listener:
    listener.join()
</code>```

答:
```<code>f.write(' ')
</code>```

instead of

```<code>f.write('\n')
</code>```

will do what you need.

Body:
so im trying to make a kind of keylogger which tracks your keyboard and whenever the user exits the program it will save in a text file. However if the user presses space it will leave a full line empty and i am trying to fix it. UPDATE, i have fixed it thank you guys! <3

import pynput

from pynput.keyboard import Key, Listener

count = 0
keys = []

def on_press (key) :
    global keys, count

    keys.append(key)
    count += 1
    print('{0} pressed'.format(key))

    if count >= 10:
        count += 1
        write_file(keys)
        keys = []

def write_file(keys):
    with open('log.txt', 'a') as f:
        for key in keys :
            k = str(key).replace("'","")
            if k.find('space') > 0:
                f.write('\n')
            elif k.find('Key') == -1:
                f.write(k)

def on_release(key) :
    if key == Key.esc:
        return False

with Listener (on_press=on_press, on_release=on_release) as listener:
    listener.join()

Body:
f.write(' ')

instead of

f.write('\n')

will do what you need.


问:
Cannot copy html response using findElement Selenium - Java
I am trying to copy the html response content of the webpage https://api.bseindia.com/BseIndiaAPI/api/AnnGetData/w?pageno=1&strCat=-1&strPrevDate=20220204&strScrip=&strSearch=P&strToDate=20220204&strType=C
in selenium using a webelement. I used 'Table' in findElement but it throws error as below.

Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element

How can I copy the html response into a java variable using selenium or any other tool?

Below is the code:

```<code>public void launchBrowser()
{
System.setProperty("webdriver.chrome.driver", "/Users/vamsi/selenium-java-4.1.0/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://api.bseindia.com/BseIndiaAPI/api/AnnGetData/w?pageno=1&strCat=-1&strPrevDate=20220204&strScrip=&strSearch=P&strToDate=20220204&strType=C");
WebElement p = driver.findElement(By.name("Table"));
}
</code>```

答:
The page source response is not HTML, it's json string.

So it's not possible to locate any element.

However, it's possible to get the response content.

String source = driver.getPageSource();
```
<p>Besides, it's possible to parse data with:</p>
<pre class="lang-java prettyprint-override"><code>import com.fasterxml.jackson.databind.ObjectMapper

Map<String,Object> result = new ObjectMapper().readValue(source, HashMap.class);

Object tableData = result.get("Table"); //Looks like it's List Object
</code>```

this dependency required:

https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.13.1

Body:
I am trying to copy the html response content of the webpage https://api.bseindia.com/BseIndiaAPI/api/AnnGetData/w?pageno=1&strCat=-1&strPrevDate=20220204&strScrip=&strSearch=P&strToDate=20220204&strType=C
in selenium using a webelement. I used 'Table' in findElement but it throws error as below.

Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element

How can I copy the html response into a java variable using selenium or any other tool?

Below is the code:

public void launchBrowser()
{
System.setProperty("webdriver.chrome.driver", "/Users/vamsi/selenium-java-4.1.0/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://api.bseindia.com/BseIndiaAPI/api/AnnGetData/w?pageno=1&strCat=-1&strPrevDate=20220204&strScrip=&strSearch=P&strToDate=20220204&strType=C");
WebElement p = driver.findElement(By.name("Table"));
}

Body:
The page source response is not HTML, it's json string.

So it's not possible to locate any element.

However, it's possible to get the response content.

String source = driver.getPageSource();

Besides, it's possible to parse data with:

import com.fasterxml.jackson.databind.ObjectMapper

Map<String,Object> result = new ObjectMapper().readValue(source, HashMap.class);

Object tableData = result.get("Table"); //Looks like it's List Object

this dependency required:

https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.13.1


问:
if...else within JSP or JSTL
I want to output some HTML code based on some condition in a JSP file.

if (condition 1) {
    Some HTML code specific for condition 1
}
else if (condition 2) {
    Some HTML code specific for condition 2
}
```

How can I do that? Should I use JSTL?

答:
```<code><c:if test="${condition1 && condition2 && condition3}" var="condition">
    //if
</c:if>
<c:if test="${!condition}">
    //else
</c:if>
</code>```

This is an another way to take the if condition in a variable.

Title: if...else within JSP or JSTL

Body:
I want to output some HTML code based on some condition in a JSP file.

if (condition 1) {
    Some HTML code specific for condition 1
}
else if (condition 2) {
    Some HTML code specific for condition 2
}

How can I do that? Should I use JSTL?

Body:
<c:if test="${condition1 && condition2 && condition3}" var="condition">
    //if
</c:if>
<c:if test="${!condition}">
    //else
</c:if>

This is an another way to take the if condition in a variable.


问:
Compass + Blueprint non semantic classes
I've been using compass with blueprint for a while now and one thing I can't figure out is why it generates all the basic blueprint css classes. Like these:

```<code>#container .span-3 { width: 110px; }
#container .span-4 { width: 150px; }
</code>```

I specify --using blueprint/semantic when creating the compass project, and no I don't have @include blueprint anywhere in my source. Why are these classes being generated and how do I get compass not to include them?

答:
I tried to reproduce your problem but I can't.  Here's what I did and what I got:

```<code>compass create my_project --using blueprint/semantic
</code>```

The generated screen.scss file seems to want you to @import "blueprint", as it contains the following lines initially:

```<code>// Import all the default blueprint modules so that we can access their mixins.
@import "blueprint";
</code>```

The generated screen.css file does not contain .span-x anywhere, and the only place #container appears is in body.two-col #container {.

I modified the screen.scss file and recompiled.  No change -- no non-semantic classes showed up in screen.css.

Hope this helps...

(Tested with Compass version 0.11.5, Ruby 1.8.7, FreeBSD 8.2)

Body:
I've been using compass with blueprint for a while now and one thing I can't figure out is why it generates all the basic blueprint css classes. Like these:

#container .span-3 { width: 110px; }
#container .span-4 { width: 150px; }

I specify --using blueprint/semantic when creating the compass project, and no I don't have @include blueprint anywhere in my source. Why are these classes being generated and how do I get compass not to include them?

Body:
I tried to reproduce your problem but I can't.  Here's what I did and what I got:

compass create my_project --using blueprint/semantic

The generated screen.scss file seems to want you to @import "blueprint", as it contains the following lines initially:

// Import all the default blueprint modules so that we can access their mixins.
@import "blueprint";

The generated screen.css file does not contain .span-x anywhere, and the only place #container appears is in body.two-col #container {.

I modified the screen.scss file and recompiled.  No change -- no non-semantic classes showed up in screen.css.

Hope this helps...

(Tested with Compass version 0.11.5, Ruby 1.8.7, FreeBSD 8.2)


问:
How to add a scope to an app engine instance?
I'm trying to use start a csv file import to cloud sql from an app engine as described here.

Although this works locally, it fails when running on app engine:

```<code>googleapiclient.errors.HttpError: <HttpError 403 when requesting https://sqladmin.googleapis.com/v1/projects/xxxxxx/instances/yyyyyy/import?alt=json
returned "Request had insufficient authentication scopes."
Details: "[{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}]">"
</code>```

How to add the scopes to my app engine standard instance?

答:
The solution turned out to be the following:</p>
```<code>import google.auth
# next line had wrong scope
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
credentials, _ = google.auth.default(scopes=SCOPES)
</code>```

Body:
I'm trying to use start a csv file import to cloud sql from an app engine as described here.

Although this works locally, it fails when running on app engine:

googleapiclient.errors.HttpError: <HttpError 403 when requesting https://sqladmin.googleapis.com/v1/projects/xxxxxx/instances/yyyyyy/import?alt=json
returned "Request had insufficient authentication scopes."
Details: "[{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}]">"

How to add the scopes to my app engine standard instance?

Body:
The solution turned out to be the following:

import google.auth
# next line had wrong scope
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
credentials, _ = google.auth.default(scopes=SCOPES)


问:
Move postgresql database from one server to another without dump file
is it possible copy pg_data from docker and paste new database server in location /var/lib/postgresql/11/main/ ? I have tried and getting error

```<code>psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
</code>```

how can I solve this problem? Via dump file can't restoring, I need exactly through copy paste pg_data

答:
You can use pg_basebackup for this:

pg_basebackup makes an exact copy of the database cluster's files,
while making sure the server is put into and out of backup mode
automatically.

Body:
is it possible copy pg_data from docker and paste new database server in location /var/lib/postgresql/11/main/ ? I have tried and getting error

psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

how can I solve this problem? Via dump file can't restoring, I need exactly through copy paste pg_data