问:
how to remove double quote only from numeric data in a spark dataframe while writing it into a csv
While writing data into a csv from spark dataframe . I want to remove " quotes only from numeric data .

Actual Output:

```<code>+-------+---------+-----+
|user_id|course   |marks|
+-------+---------+-----+
|    "1"|    "eng"|  "9"|
|    "1"| "french"|  "7"|
+-------+---------+-- ---+
</code>```

Expected Output

```<code>+-------+---------+-----+
|user_id|course   |marks|
+-------+---------+-----+
|      1|    "eng"|    9|
|      1| "french"|    7|
+-------+---------+-----+
</code>```

答:
In DF, cast the numerical column Data type to Integer Type,</p>

```<code>import org.apache.spark.sql.types.IntegerType

df
.select(df("user_id").cast(IntegerType), df("course"), df("marks").cast(IntegerType))
.show()
</code>```

Body:
While writing data into a csv from spark dataframe . I want to remove " quotes only from numeric data .

Actual Output:

+-------+---------+-----+
|user_id|course   |marks|
+-------+---------+-----+
|    "1"|    "eng"|  "9"|
|    "1"| "french"|  "7"|
+-------+---------+-- ---+

Expected Output

+-------+---------+-----+
|user_id|course   |marks|
+-------+---------+-----+
|      1|    "eng"|    9|
|      1| "french"|    7|
+-------+---------+-----+

Body:
In DF, cast the numerical column Data type to Integer Type,

import org.apache.spark.sql.types.IntegerType

df
.select(df("user_id").cast(IntegerType), df("course"), df("marks").cast(IntegerType))
.show()


来源: stackexchange

问:
Printing a squares triangle. How to mirror numbers?
So I've been working on this lab for a while now for my programming class and so far I think I'm on the right track.

However, I'm not quite sure how to mirror the numbers. So pretty much, my code is only printing the top half of the triangle. Anyway here is the actual assignment that was given to us:

Write a program using a Scanner that asks the user for a number n between 1 and 9 (inclusive). The program prints a triangle with n rows. The first row contains only the square of 1, and it is right-justified. The second row contains the square of 2 followed by the square of 1, and is right justified. Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2 and 1, and so forth until n rows are printed.
Assuming the user enters 4, the program prints the following triangle to the console:

```<code>          1
       4  1
    9  4  1
16  9  4  1
    9  4  1
       4  1
          1
</code>```

For full credit, each column should be 3 characters wide and the values should be right justified.

Now here is what I have written for my code so far:

import java.util.Scanner;
public class lab6 {
    public static void main(String[] args) {
        Scanner kybd = new Scanner(System.in);
        System.out.println(
                "Enter a number that is between 1 and 9 (inclusive): ");

        // this is the value that the user will enter for # of rows
        int rows = kybd.nextInt();

        for (int i = rows; i > 0; i--) {
            for (int j = rows; j > 0; j--)
                System.out.print((rows - j + 1) < i ?
                        "   " : String.format("%3d", j * j));
            System.out.println();
        }
    }
}
```
<p>And this is what that code PRINTS when I enter <code>4</code>:</p>
```Enter a number that is between 1 and 9 (inclusive):
4
          1
       4  1
    9  4  1
16  9  4  1
```

As you can see, I can only get the TOP half of the triangle to print out. I've been playing around trying to figure out how to mirror it but I can't seem to figure it out. I've looked on this website for help, and all over the Internet but I can't seem to do it.

答:
Another alternative : </p>

```<code>public static void main(String args[]) {

    Scanner kybd = new Scanner(System.in);
    System.out.println("Enter a number that is between 1 and 9 (inclusive): ");
    int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows

    int row = rows, increment = -1;
    while (row <= rows){
        for (int j = rows; j > 0; j--) {
            System.out.print(rows - j + 1 < row ? "   " : String.format("%3d", j * j));
        }
        System.out.println();
        if(row == 1) {
            increment = - increment;
        }
        row += increment;
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So I've been working on this lab for a while now for my programming class and so far I think I'm on the right track.

However, I'm not quite sure how to mirror the numbers. So pretty much, my code is only printing the top half of the triangle. Anyway here is the actual assignment that was given to us:

Write a program using a Scanner that asks the user for a number n between 1 and 9 (inclusive). The program prints a triangle with n rows. The first row contains only the square of 1, and it is right-justified. The second row contains the square of 2 followed by the square of 1, and is right justified. Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2 and 1, and so forth until n rows are printed.
Assuming the user enters 4, the program prints the following triangle to the console:

          1
       4  1
    9  4  1
16  9  4  1
    9  4  1
       4  1
          1

For full credit, each column should be 3 characters wide and the values should be right justified.

Now here is what I have written for my code so far:

import java.util.Scanner;
public class lab6 {
    public static void main(String[] args) {
        Scanner kybd = new Scanner(System.in);
        System.out.println(
                "Enter a number that is between 1 and 9 (inclusive): ");

        // this is the value that the user will enter for # of rows
        int rows = kybd.nextInt();

        for (int i = rows; i > 0; i--) {
            for (int j = rows; j > 0; j--)
                System.out.print((rows - j + 1) < i ?
                        "   " : String.format("%3d", j * j));
            System.out.println();
        }
    }
}

And this is what that code PRINTS when I enter 4:

Enter a number that is between 1 and 9 (inclusive):
4
          1
       4  1
    9  4  1
16  9  4  1

As you can see, I can only get the TOP half of the triangle to print out. I've been playing around trying to figure out how to mirror it but I can't seem to figure it out. I've looked on this website for help, and all over the Internet but I can't seem to do it.

Body:
Another alternative :

public static void main(String args[]) {

    Scanner kybd = new Scanner(System.in);
    System.out.println("Enter a number that is between 1 and 9 (inclusive): ");
    int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows

    int row = rows, increment = -1;
    while (row <= rows){
        for (int j = rows; j > 0; j--) {
            System.out.print(rows - j + 1 < row ? "   " : String.format("%3d", j * j));
        }
        System.out.println();
        if(row == 1) {
            increment = - increment;
        }
        row += increment;
    }
}


问:
Why my code in not working for loops and if conditions?
I am trying to run this code in qutip. But its not showing any result. However there is not showing any error. All codes are correct and not showing any error. But don't know why the program is not execute. If anybody can resolve this problem is most welcome.

```<code>  from __future__ import division
  from qutip import *
  import pylab
  import math
  import matplotlib.pyplot as plt
  import numpy as np
  import csv
  #import plotly.plotly as py
  #from plotly.graph_objs import *
  #py.sign_in("cayayald", "zlae2s4d1i")
  #linewidth
  #gamma = 1 => fully independent
  #G = 1 => fully collective
  gamma = .25
  G = 1.0 - gamma
  #delta is detuning
  delta = -1
  deltastep = 0.1
  dlist = []
  #n is number of atoms
  n = 16
  #V is energy shiftdue to dipole-dipole
  V = 10
  #omega is rabi freq
  omega = 1.5
  omegastep = 0
  #lowering, raising, and state collapsing operators
  sigmamlist = []
  sigmaplist = []
  c_op_list =  []
  for j in range (n):
   if j==0:
   sigmajm=sigmam()
   else:
   sigmajm=qeye(2)
   for i in range (1,n):
   if j == i:
   sigmaj1= tensor(sigmam(),sigmajm)
   else:
   sigmajm = tensor(qeye(2),sigmajm)
   sigmamlist.append(sigmajm)

  coplist.append(math.sqrt(gamma)*sigmajm) #n-many indep collapse ops
  sigmajp = sigmajm.dag()
  sigmaplist.append(sigmajp)
  coplist.append(math.sqrt(G)*sum(sigmamlist)) #one collective collapse op
  #we want expectation values of operators in exoplist
  exoplist = []
  #numerator of cross correlation
  exoplist.append(sigmaplist[0]*sigmamlist[0]*sigmaplist[1]*sigmamlist[1])
  #denomenator of cross correlation
  exoplist.append(sigmaplist[0]*sigmamlist[0])
  exoplist.append(sigmaplist[1]*sigmamlist[1])
</code>```

After this These codes below are not running and taking time. don't know why?

```<code>   #initial state vector
  psi0 = basis(2,0)
  for i in range(1,n):
  psi0 = tensor(psi0,basis(2,0))
  #build Hamiltonian
  g2 = []
  list = np.linspace(0,200,2000)
  ntraj = 1
  while delta <= 7:
  glist = []
  hlist = []
  vlist = []
  for i in range(n):
        hlist.append(-delta*(sigmaplist[i]*sigmamlist[i])+ (omega / 2)*(sigmaplist[i] +
        sigmamlist[i]))
  for i in range(n):
  for j in range(i):
        vlist.append((V / (n - 1))*((sigmaplist[j]*sigmamlist[j])
   *(sigmaplist[i]*sigmamlist[i])))
   H = sum(hlist) + sum(vlist)
   #monte carlo trajectory
   montecar = mcsolve(H, psi0, tlist, coplist, exoplist, ntraj)
   for i in range(len(montecar.expect[0])):
   numerator = montecar.expect[0][i]
  denomenator = montecar.expect[1][i]
  denom2 = montecar.expect[2][i]
  glist.append(numerator/(denomenator*denom2))
  g2.append(sum(glist)/len(glist))
  dlist.append(delta)
  delta = delta + deltastep
  x = np.arange(10)
  fig = plt.figure()
  ax = plt.subplot(111)
  ax.plot(dlist, g2)
  # Shink current axis by 20%
  box = ax.get_position()
  ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
  plt.grid(True)
  plt.show()
</code>```

答:
You have to use indentation, smt. like this:

```<code>for j in range (n):
    if j==0:
        sigmajm=sigmam()
    else:
        sigmajm=qeye(2)

for i in range (1,n):
    if j == i:
        sigmaj1= tensor(sigmam(),sigmajm)
    else:
        sigmajm = tensor(qeye(2),sigmajm)
        sigmamlist.append(sigmajm)
</code>```

Update:
https://www.tutorialspoint.com/python/python_basic_syntax.htm

Body:
I am trying to run this code in qutip. But its not showing any result. However there is not showing any error. All codes are correct and not showing any error. But don't know why the program is not execute. If anybody can resolve this problem is most welcome.

  from __future__ import division
  from qutip import *
  import pylab
  import math
  import matplotlib.pyplot as plt
  import numpy as np
  import csv
  #import plotly.plotly as py
  #from plotly.graph_objs import *
  #py.sign_in("cayayald", "zlae2s4d1i")
  #linewidth
  #gamma = 1 => fully independent
  #G = 1 => fully collective
  gamma = .25
  G = 1.0 - gamma
  #delta is detuning
  delta = -1
  deltastep = 0.1
  dlist = []
  #n is number of atoms
  n = 16
  #V is energy shiftdue to dipole-dipole
  V = 10
  #omega is rabi freq
  omega = 1.5
  omegastep = 0
  #lowering, raising, and state collapsing operators
  sigmamlist = []
  sigmaplist = []
  c_op_list =  []
  for j in range (n):
   if j==0:
   sigmajm=sigmam()
   else:
   sigmajm=qeye(2)
   for i in range (1,n):
   if j == i:
   sigmaj1= tensor(sigmam(),sigmajm)
   else:
   sigmajm = tensor(qeye(2),sigmajm)
   sigmamlist.append(sigmajm)

  coplist.append(math.sqrt(gamma)*sigmajm) #n-many indep collapse ops
  sigmajp = sigmajm.dag()
  sigmaplist.append(sigmajp)
  coplist.append(math.sqrt(G)*sum(sigmamlist)) #one collective collapse op
  #we want expectation values of operators in exoplist
  exoplist = []
  #numerator of cross correlation
  exoplist.append(sigmaplist[0]*sigmamlist[0]*sigmaplist[1]*sigmamlist[1])
  #denomenator of cross correlation
  exoplist.append(sigmaplist[0]*sigmamlist[0])
  exoplist.append(sigmaplist[1]*sigmamlist[1])

After this These codes below are not running and taking time. don't know why?

   #initial state vector
  psi0 = basis(2,0)
  for i in range(1,n):
  psi0 = tensor(psi0,basis(2,0))
  #build Hamiltonian
  g2 = []
  list = np.linspace(0,200,2000)
  ntraj = 1
  while delta <= 7:
  glist = []
  hlist = []
  vlist = []
  for i in range(n):
        hlist.append(-delta*(sigmaplist[i]*sigmamlist[i])+ (omega / 2)*(sigmaplist[i] +
        sigmamlist[i]))
  for i in range(n):
  for j in range(i):
        vlist.append((V / (n - 1))*((sigmaplist[j]*sigmamlist[j])
   *(sigmaplist[i]*sigmamlist[i])))
   H = sum(hlist) + sum(vlist)
   #monte carlo trajectory
   montecar = mcsolve(H, psi0, tlist, coplist, exoplist, ntraj)
   for i in range(len(montecar.expect[0])):
   numerator = montecar.expect[0][i]
  denomenator = montecar.expect[1][i]
  denom2 = montecar.expect[2][i]
  glist.append(numerator/(denomenator*denom2))
  g2.append(sum(glist)/len(glist))
  dlist.append(delta)
  delta = delta + deltastep
  x = np.arange(10)
  fig = plt.figure()
  ax = plt.subplot(111)
  ax.plot(dlist, g2)
  # Shink current axis by 20%
  box = ax.get_position()
  ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
  plt.grid(True)
  plt.show()

Body:
You have to use indentation, smt. like this:

for j in range (n):
    if j==0:
        sigmajm=sigmam()
    else:
        sigmajm=qeye(2)

for i in range (1,n):
    if j == i:
        sigmaj1= tensor(sigmam(),sigmajm)
    else:
        sigmajm = tensor(qeye(2),sigmajm)
        sigmamlist.append(sigmajm)

Update:
https://www.tutorialspoint.com/python/python_basic_syntax.htm


问:
What's a free flash IDE that supports netbeans/eclipse style shortcuts?
I tried flashdevelop and the basic flash cs5 IDE, and both fail miserably in the shortcuts department.

I am very comfortable with the netbeans set of shortcuts and want to know if there's any AS3 IDEs that would support them.

Some examples are:

```<code>ctrl+/ for toggle comment
control+shift+up/down to duplicate a line
alt+shift+up/down to move a line up and down
ctrl+D to delete a line
alt+shift+f to autoformat
</code>```

答:
FlashDevelop is the best. Quick, intelligent and powerful. Love it.

You have total control over such customizations. And honestly... if you find you actually can't make certain changes (in this case - hotkey shortcuts), accommodating the application's minor differences  is a small price to pay for such an elegant programming environment, imho.

ContentLicense: CC BY-SA 3.0

Body:
I tried flashdevelop and the basic flash cs5 IDE, and both fail miserably in the shortcuts department.

I am very comfortable with the netbeans set of shortcuts and want to know if there's any AS3 IDEs that would support them.

Some examples are:

ctrl+/ for toggle comment
control+shift+up/down to duplicate a line
alt+shift+up/down to move a line up and down
ctrl+D to delete a line
alt+shift+f to autoformat


问:
How to repeat the input options in console using `input()` until the user chooses to quit?
I am providing multiple options to the user to choose from using input() in Python 3. I want the options to be displayed again and again until the user chooses to quit by selecting the quit option

For example :

```<code>a = 5
b = 2
inp = input('''Please choose from Options mentioned below:
        1. Sum
        2. Multiply
        3. Divide
        0. Quit
        ''')

    if int(inp) == 1:
        sum(a,b)
    elif int(inp) == 2:
        multiply(a,b)
    elif int(inp) == 3:
        divide(a,b)
    elif int(inp) == 0:
        print("Thanks for your input.\nQuitting the process")
    elif int(inp) > 3:
        print("Please type numbers from 0 to 8")
    else:
        print("Only numbers are accepted. Please select right option")
</code>```

So, as per the above example, the same options have to be displayed to the user until the user enters "0" which will quit the input() process from the console. If the user enters a number > 3 or if the user enters any non-numerical characters then the relevant message should be printed and also the options have to be shown again.

Right now, in case of these failures, only the message is getting printed on the screen and it's ending the input() process.

Any idea what am I missing here ?

答:
You can do something like this:

```<code>while True:
    inp = input('''Please choose from Options mentioned below:
        1. Sum
        2. Multiply
        3. Divide
        0. Quit
        ''')

    if int(inp) == 1:
        sum(a,b)
    elif int(inp) == 2:
        multiply(a,b)
    elif int(inp) == 3:
        divide(a,b)
    elif int(inp) == 0:
        print("Thanks for your input.\nQuitting the process")
        break
    elif int(inp) > 3:
        print("Please type numbers from 0 to 8")
    else:
        print("Only numbers are accepted. Please select right option")
</code>```

Although this answers your question, I must say iteration and branching are core concepts in programming, so I recommend you to follow some courses or series of tutorials instead of asking questions from the beginning.

Body:
I am providing multiple options to the user to choose from using input() in Python 3. I want the options to be displayed again and again until the user chooses to quit by selecting the quit option

For example :

a = 5
b = 2
inp = input('''Please choose from Options mentioned below:
        1. Sum
        2. Multiply
        3. Divide
        0. Quit
        ''')

    if int(inp) == 1:
        sum(a,b)
    elif int(inp) == 2:
        multiply(a,b)
    elif int(inp) == 3:
        divide(a,b)
    elif int(inp) == 0:
        print("Thanks for your input.\nQuitting the process")
    elif int(inp) > 3:
        print("Please type numbers from 0 to 8")
    else:
        print("Only numbers are accepted. Please select right option")

So, as per the above example, the same options have to be displayed to the user until the user enters "0" which will quit the input() process from the console. If the user enters a number > 3 or if the user enters any non-numerical characters then the relevant message should be printed and also the options have to be shown again.

Right now, in case of these failures, only the message is getting printed on the screen and it's ending the input() process.

Any idea what am I missing here ?

Body:
You can do something like this:

while True:
    inp = input('''Please choose from Options mentioned below:
        1. Sum
        2. Multiply
        3. Divide
        0. Quit
        ''')

    if int(inp) == 1:
        sum(a,b)
    elif int(inp) == 2:
        multiply(a,b)
    elif int(inp) == 3:
        divide(a,b)
    elif int(inp) == 0:
        print("Thanks for your input.\nQuitting the process")
        break
    elif int(inp) > 3:
        print("Please type numbers from 0 to 8")
    else:
        print("Only numbers are accepted. Please select right option")

Although this answers your question, I must say iteration and branching are core concepts in programming, so I recommend you to follow some courses or series of tutorials instead of asking questions from the beginning.


问:
How to exclude a @Configuration class when using @WebMvcTest with spring-boot?
I am writing junits for a rest controller. I want only minimal context to be loaded which is related to the controller and I think that is how @WebMvcTest loads the context. But the junit is loading complete Spring context and it is failing as some of the beans can not be created.

I have searched and read through many questions on stackoverflow and none of the solutions worked to exclude specific configuration. How can I load a minimal context when writing junits for controllers? Or is there any way to exclude some configuration classes? I am using Spring-boot 2.2.2.RELEASE, Java 8 and Junit 4.

Junit (where I have tried to exclude loading of some beans and configurations but it doesn't work):

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = OrderController.class, excludeFilters = {@Filter(classes = Configuration.class), @Filter(type = FilterType.REGEX, pattern = "com\\.foo\\..*")})
@TestPropertySource(properties = { "spring.cloud.config.server.bootstrap:false" })
public class OrderControllerTest {

    @MockBean
    private OrderService orderService;

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void test() throws Exception {
        mockMvc.perform(get("/internal/order/123"));
        // Further code to verify the response
    }

}
```

<p>Controller</p>

<pre class="lang-java prettyprint-override"><code>@Slf4j
@Validated
@RestController
@RequestMapping("/internal")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping(value = "/order/{orderId}", produces = { MediaType.APPLICATION_JSON_VALUE })
    public ResponseEntity<RegularContributionOrder> retrieveRegularContributionOrder(@NotNull @PathVariable("orderId") String orderId)
            throws OrderNotFoundException {

        RegularContributionOrder order = orderService.retrieve(orderId);

        return new ResponseEntity<RegularContributionOrder>(order, HttpStatus.OK);
    }
}
</code>```

Configuration class which I want to exclude from context loading

@Slf4j
@Configuration
@EnableAspectJAutoProxy
@ImportResource({ "classpath:spring/service-config-one.xml", "classpath:spring/service-config-two.xml" })
public class OrderServiceConfig {

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:resourcebundles/error-messages.properties");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        return mapper;
    }
}
```

<p>Spring boot main class:</p>

<pre class="lang-java prettyprint-override"><code>@EnableJms
@EnableAspectJAutoProxy
@ComponentScan(basePackages = { "com.foo.services", "com.bar" })
@SpringBootApplication(exclude = { SomeConfiguration.class})
public class BootApplication extends SpringBootServletInitializer {

    @Override
    protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
        return application.sources(BootApplication .class);
    }

    public static void main(final String[] args) {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        SpringApplication.run(BootApplication.class, args);
    }
}
</code>```

答:
When your test classes located in test folder and run with "test" profile then your real configuration class will be excluded. Here is an example of how I configure spring boot test. </p>

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = IntegrationApplication.class,
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class MyControllerTest {
</code>```

<p>=================================</p>

```<code>@SpringBootApplication
public class IntegrationApplication {

public static void main(String[] args) {
    SpringApplication.run(IntegrationApplication.class, args);
}
</code>```

Body:
I am writing junits for a rest controller. I want only minimal context to be loaded which is related to the controller and I think that is how @WebMvcTest loads the context. But the junit is loading complete Spring context and it is failing as some of the beans can not be created.

I have searched and read through many questions on stackoverflow and none of the solutions worked to exclude specific configuration. How can I load a minimal context when writing junits for controllers? Or is there any way to exclude some configuration classes? I am using Spring-boot 2.2.2.RELEASE, Java 8 and Junit 4.

Junit (where I have tried to exclude loading of some beans and configurations but it doesn't work):

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = OrderController.class, excludeFilters = {@Filter(classes = Configuration.class), @Filter(type = FilterType.REGEX, pattern = "com\\.foo\\..*")})
@TestPropertySource(properties = { "spring.cloud.config.server.bootstrap:false" })
public class OrderControllerTest {

    @MockBean
    private OrderService orderService;

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void test() throws Exception {
        mockMvc.perform(get("/internal/order/123"));
        // Further code to verify the response
    }

}

Controller

@Slf4j
@Validated
@RestController
@RequestMapping("/internal")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping(value = "/order/{orderId}", produces = { MediaType.APPLICATION_JSON_VALUE })
    public ResponseEntity<RegularContributionOrder> retrieveRegularContributionOrder(@NotNull @PathVariable("orderId") String orderId)
            throws OrderNotFoundException {

        RegularContributionOrder order = orderService.retrieve(orderId);

        return new ResponseEntity<RegularContributionOrder>(order, HttpStatus.OK);
    }
}

Configuration class which I want to exclude from context loading

@Slf4j
@Configuration
@EnableAspectJAutoProxy
@ImportResource({ "classpath:spring/service-config-one.xml", "classpath:spring/service-config-two.xml" })
public class OrderServiceConfig {

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:resourcebundles/error-messages.properties");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        return mapper;
    }
}

Spring boot main class:

@EnableJms
@EnableAspectJAutoProxy
@ComponentScan(basePackages = { "com.foo.services", "com.bar" })
@SpringBootApplication(exclude = { SomeConfiguration.class})
public class BootApplication extends SpringBootServletInitializer {

    @Override
    protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
        return application.sources(BootApplication .class);
    }

    public static void main(final String[] args) {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        SpringApplication.run(BootApplication.class, args);
    }
}

Body:
When your test classes located in test folder and run with "test" profile then your real configuration class will be excluded. Here is an example of how I configure spring boot test.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = IntegrationApplication.class,
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class MyControllerTest {

=================================

@SpringBootApplication
public class IntegrationApplication {

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


问:
javascript can't reassignment data to array in map()
```<code>
let obj2 = {
  level2:{
    data:"data"
  }
}

let obj2Array  = [obj2,obj2,obj2];
obj2Array.map(obj=>{
  obj = obj.levle2.data
});
console.log(obj2Array)

</code>```

what I'm expecting is ["data","data","data"].But I still got the original data.
I know I can use forEach() to achieve this, but why I can't reassignment element in map()?

答:
You forgot to set obj2Array to the value returned by .map(). See below:

var obj2 = {
  level2:{
    data:"data"
  }
}

var obj2Array  = [obj2,obj2,obj2];

// set to returned map
obj2Array = obj2Array.map(obj=>{
  return obj2.level2.data
});

console.log(obj2Array)```

Body:
let obj2 = {
  level2:{
    data:"data"
  }
}

let obj2Array  = [obj2,obj2,obj2];
obj2Array.map(obj=>{
  obj = obj.levle2.data
});
console.log(obj2Array)

what I'm expecting is ["data","data","data"].But I still got the original data.
I know I can use forEach() to achieve this, but why I can't reassignment element in map()?


答:
Map will return new array</p>

```<code>const result = obj2Array.map(obj=>{
  return obj2.levle2.data
});
console.log(result)
</code>```

Title: javascript can't reassignment data to array in map()

Body:
Map will return new array

const result = obj2Array.map(obj=>{
  return obj2.levle2.data
});
console.log(result)


问:
I have Problem with AJAX post using laravel
I am working on simple private chat application ,when i send message to selected user so message is sending perfectly but meassage is showing  on browser  relaod i have used ajax but unfortunatly ajax is not working please help me thanks.

Controller

```<code>             public function chataction(REQUEST $request)
             {
             $chat_message = $request->get('message');
             $from_user_id=Auth::user()->id;
             $to_user_id =$request->get('myid');
             $user = Auth::user();
             $response = $user->Chats()->create([

             'chat_message'=>  $chat_message,
             'from_user_id' => $from_user_id,
             'to_user_id'  => $to_user_id,
              ]);
             $response = array(
              'status' => 'success',
              'msg' => 'Setting created successfully',
              );
              return Response::json($response);

              }
</code>```

html view

```<code>          <!-- /.card-body -->
          <div class="card-footer">
          <form id="myform" action="{{route('chat.action')}}" method="post">
          {{csrf_field()}}
          <input type="hidden" name="myid" value="{{$single_chat->id}}" >
          <div class="input-group">
          <input type="text" id="chatmessage" name="message" placeholder="Type Message
          ..." class="form-control">
          <span class="input-group-append">
          <button type="submit" name="btnsubmit" id="btnsubmit"  class="btn btn-
          primary">Send</button>
          </span>
          </div>
          </form>
          </div>
          <!-- /.card-footer-->
         </div>
</code>```

Ajax

```<code>             <script type="text/javascript">
             $(document).ready(function() {

             $("#btnsubmit").click(function(){
             event.preventDefault();
             var form_data = $("#chatmessage").val();
             $.ajax({
             url:"{{ route('chat.action') }}",
              data:   {
              "_token": "{{ csrf_token() }}",
              "form_data": form_data
              }
             dataType:"json",
             success:function(data)
            {

            }

            });
            });
            });

            </script>
</code>```

Route

```<code>        Route::post('chat/action','HomeController@chataction')->name('chat.action');
</code>```

答:
your javascript code is wrong.

Try this:

```<code><script type="text/javascript">
 $(document).ready(function() {

   $("#btnsubmit").click(function(){
     event.preventDefault();
     var form_data = $("#myform").serialize();
     $.ajax({
       type:"POST",
       url:"{{ route('chat.action') }}",
       data: form_data,
      dataType:"json",
      success:function(data)
      {

      }

    });
   });
 });
</script>
</code>```

Body:
I am working on simple private chat application ,when i send message to selected user so message is sending perfectly but meassage is showing  on browser  relaod i have used ajax but unfortunatly ajax is not working please help me thanks.

Controller

             public function chataction(REQUEST $request)
             {
             $chat_message = $request->get('message');
             $from_user_id=Auth::user()->id;
             $to_user_id =$request->get('myid');
             $user = Auth::user();
             $response = $user->Chats()->create([

             'chat_message'=>  $chat_message,
             'from_user_id' => $from_user_id,
             'to_user_id'  => $to_user_id,
              ]);
             $response = array(
              'status' => 'success',
              'msg' => 'Setting created successfully',
              );
              return Response::json($response);

              }

html view

          <form id="myform" action="{{route('chat.action')}}" method="post">
          {{csrf_field()}}
          <input type="hidden" name="myid" value="{{$single_chat->id}}" >

          <input type="text" id="chatmessage" name="message" placeholder="Type Message
          ..." class="form-control">

          <button type="submit" name="btnsubmit" id="btnsubmit"  class="btn btn-
          primary">Send</button>

          </form>

Ajax

Route

        Route::post('chat/action','HomeController@chataction')->name('chat.action');

Body:
your javascript code is wrong.

Try this:

<script type="text/javascript">
 $(document).ready(function() {

   $("#btnsubmit").click(function(){
     event.preventDefault();
     var form_data = $("#myform").serialize();
     $.ajax({
       type:"POST",
       url:"{{ route('chat.action') }}",
       data: form_data,
      dataType:"json",
      success:function(data)
      {

      }

    });
   });
 });
</script>


问:
Grouping SQL results from a Union
I have a table in my database used for users to follow eachother.

The table goes as follows:

```<code>UniqueID
FollowerID
FollowedUserID
</code>```

FollowID is the UserID of the person who is following someone else.

FollowedUserID is the UserID of the person who is being followed by the FollowID User.

I'd like to retrieve a list of connections from this table based off a single user. My query should return all the other UserIDs that the current user is either following or being followed by with no overlaps.

So say we have a few entries here:

```<code>FollowerID   FollowedUserID
    1              2
    1              3
    4              1
    2              1
</code>```

This would show that the User 1 is following users 2 and 3, and thus users 2 and 3 are being followed by user 1. On the other side of the spectrum it shows that User 1 is followed by users 2 and 3.

What I'd like to do is find out the connections that user 1 has, so the query should return users: 2, 3, and 4 (user 1 is following users 2 and 3 and is being followed by user 4)

How can I achieve this from a single query?

A connection is considered either being followed or following someone else, so it is possible that some duplicate results can occur (if both users are following eachother). I'd like to be able to group these results so that the result is distinct.

I've tried a UNION query similar to:

```<code>SELECT FollowerID, FollowedUserID From Follows WHERE FollowerID = 1
UNION
SELECT FollowerID, FollowedUserID FROM Follows WHERE FollowedUserID = 1
</code>```

Theoretically I'd like to Group FollowerID and FollowedUserID together to keep them distinct.

I'm not interested in retrieving a non-distinct result and then creating a dataset of unique results php side -- the query should return distinct values only.

答:
You were close, but you have to reverse the order of the columns in one of the branches of the UNION:

```<code>SELECT FollowerID AS reference_user, FollowedUserID AS connection
  FROM Follows
 WHERE FollowerID = 1
UNION
SELECT FollowedUserID AS reference_user, FollowerID AS connection
  FROM Follows
 WHERE FollowedUserID = 1
GROUP BY reference_user;
</code>```

Note that if you drop the WHERE clauses, you get all connections for everyone.

Title: Grouping SQL results from a Union

Body:
I have a table in my database used for users to follow eachother.

The table goes as follows:

UniqueID
FollowerID
FollowedUserID

FollowID is the UserID of the person who is following someone else.

FollowedUserID is the UserID of the person who is being followed by the FollowID User.

I'd like to retrieve a list of connections from this table based off a single user. My query should return all the other UserIDs that the current user is either following or being followed by with no overlaps.

So say we have a few entries here:

FollowerID   FollowedUserID
    1              2
    1              3
    4              1
    2              1

This would show that the User 1 is following users 2 and 3, and thus users 2 and 3 are being followed by user 1. On the other side of the spectrum it shows that User 1 is followed by users 2 and 3.

What I'd like to do is find out the connections that user 1 has, so the query should return users: 2, 3, and 4 (user 1 is following users 2 and 3 and is being followed by user 4)

How can I achieve this from a single query?

A connection is considered either being followed or following someone else, so it is possible that some duplicate results can occur (if both users are following eachother). I'd like to be able to group these results so that the result is distinct.

I've tried a UNION query similar to:

SELECT FollowerID, FollowedUserID From Follows WHERE FollowerID = 1
UNION
SELECT FollowerID, FollowedUserID FROM Follows WHERE FollowedUserID = 1

Theoretically I'd like to Group FollowerID and FollowedUserID together to keep them distinct.

I'm not interested in retrieving a non-distinct result and then creating a dataset of unique results php side -- the query should return distinct values only.

Body:
You were close, but you have to reverse the order of the columns in one of the branches of the UNION:

SELECT FollowerID AS reference_user, FollowedUserID AS connection
  FROM Follows
 WHERE FollowerID = 1
UNION
SELECT FollowedUserID AS reference_user, FollowerID AS connection
  FROM Follows
 WHERE FollowedUserID = 1
GROUP BY reference_user;

Note that if you drop the WHERE clauses, you get all connections for everyone.


答:
Because .map() does not mutate the original array, it returns a new one, so you should do sth like this:

```<code>let obj2Array = [obj2,obj2,obj2];
obj2Array = obj2Array.map(obj=>{
  obj = obj.levle2.data
});
console.log(obj2Array)
</code>```

Body:
Because .map() does not mutate the original array, it returns a new one, so you should do sth like this:

let obj2Array = [obj2,obj2,obj2];
obj2Array = obj2Array.map(obj=>{
  obj = obj.levle2.data
});
console.log(obj2Array)


问:
Android printer, the paper come out but dont print
How i said in the title, i need to implement a system print on my app, i add this class and implemente this code but i dont understand why when i hit "Stampa" that stand for "Print" the paper comes out but there isn't nothing printed.
How can i solve this? (I use Printooth library)
I try also with different code on internet i find everytie the same issues
The code: </p>

```<code>package com.example.testaapplication0209;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

import com.mazenrashed.printooth.Printooth;
import com.mazenrashed.printooth.data.printable.Printable;
import com.mazenrashed.printooth.data.printable.RawPrintable;
import com.mazenrashed.printooth.data.printable.TextPrintable;
import com.mazenrashed.printooth.data.printer.DefaultPrinter;
import com.mazenrashed.printooth.ui.ScanningActivity;
import com.mazenrashed.printooth.utilities.Printing;
import com.mazenrashed.printooth.utilities.PrintingCallback;

import java.util.ArrayList;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class PrintActivity extends AppCompatActivity implements PrintingCallback {

    Printing printing;
    Button btn_unpair_pair, btn_print;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_print);
        Printooth.INSTANCE.init(this);
        printing = Printooth.INSTANCE.printer();

        initViews();
    }

    private void initViews() {
        btn_print = findViewById(R.id.btn_print);
        btn_unpair_pair = findViewById(R.id.btn_pair_unpair);

        if (printing != null)
            printing.setPrintingCallback(this);

        btn_print.setOnClickListener(view -> {
            if (!Printooth.INSTANCE.hasPairedPrinter())
                startActivityForResult(new Intent(PrintActivity.this, ScanningActivity.class), ScanningActivity.SCANNING_FOR_PRINTER);
            else
                printText();
        });

        changePairAndUnpair();

    }

    private void printText() {
        ArrayList<Printable> printables = new ArrayList<>();
        printables.add(new RawPrintable.Builder(new byte[]{27, 100, 4}).build());

        //Add Text
        printables.add(new TextPrintable.Builder().setText("Hello World: Jagadeesh")
                .setCharacterCode(DefaultPrinter.Companion.getCHARCODE_PC1252())
                .setNewLinesAfter(1)
                .build());

        //Custom Text
        printables.add(new TextPrintable.Builder()
                .setText("Hello World")
                .setLineSpacing(DefaultPrinter.Companion.getLINE_SPACING_60())
                .setAlignment(DefaultPrinter.Companion.getALIGNMENT_CENTER())
                .setEmphasizedMode(DefaultPrinter.Companion.getEMPHASIZED_MODE_BOLD())
                .setUnderlined(DefaultPrinter.Companion.getUNDERLINED_MODE_ON())
                .setNewLinesAfter(1)
                .build());

        printing.print(printables);
    }

    private void changePairAndUnpair() {
        if (Printooth.INSTANCE.hasPairedPrinter())
            btn_unpair_pair.setText(new StringBuilder("Unpair ").append(Printooth.INSTANCE
                    .getPairedPrinter().getName()).toString());
        else
            btn_unpair_pair.setText("Pair with Printer");
    }

    @Override
    public void connectingWithPrinter() {
        Toast.makeText(this, "Connecting to Printer", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void connectionFailed(String s) {
        Toast.makeText(this, "Failed: " + s, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(String s) {
        Toast.makeText(this, "Error: " + s, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onMessage(String s) {
        Toast.makeText(this, "Message: " + s, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void printingOrderSentSuccessfully() {
        Toast.makeText(this, "Order sent to printer", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == ScanningActivity.SCANNING_FOR_PRINTER && resultCode == Activity.RESULT_OK)
            initPrinting();
        changePairAndUnpair();
    }

    private void initPrinting() {
        if (!Printooth.INSTANCE.hasPairedPrinter())
            printing = Printooth.INSTANCE.printer();
        if (printing != null)
            printing.setPrintingCallback(this);
    }
}
</code>```

答:
Change this line of your code:

```<code>printing.print(printables);
</code>```

To this:

```<code>Printooth.INSTANCE.printer().print(printables);
</code>```

Body:
How i said in the title, i need to implement a system print on my app, i add this class and implemente this code but i dont understand why when i hit "Stampa" that stand for "Print" the paper comes out but there isn't nothing printed.
How can i solve this? (I use Printooth library)
I try also with different code on internet i find everytie the same issues
The code:

package com.example.testaapplication0209;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

import com.mazenrashed.printooth.Printooth;
import com.mazenrashed.printooth.data.printable.Printable;
import com.mazenrashed.printooth.data.printable.RawPrintable;
import com.mazenrashed.printooth.data.printable.TextPrintable;
import com.mazenrashed.printooth.data.printer.DefaultPrinter;
import com.mazenrashed.printooth.ui.ScanningActivity;
import com.mazenrashed.printooth.utilities.Printing;
import com.mazenrashed.printooth.utilities.PrintingCallback;

import java.util.ArrayList;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class PrintActivity extends AppCompatActivity implements PrintingCallback {

    Printing printing;
    Button btn_unpair_pair, btn_print;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_print);
        Printooth.INSTANCE.init(this);
        printing = Printooth.INSTANCE.printer();

        initViews();
    }

    private void initViews() {
        btn_print = findViewById(R.id.btn_print);
        btn_unpair_pair = findViewById(R.id.btn_pair_unpair);

        if (printing != null)
            printing.setPrintingCallback(this);

        btn_print.setOnClickListener(view -> {
            if (!Printooth.INSTANCE.hasPairedPrinter())
                startActivityForResult(new Intent(PrintActivity.this, ScanningActivity.class), ScanningActivity.SCANNING_FOR_PRINTER);
            else
                printText();
        });

        changePairAndUnpair();

    }

    private void printText() {
        ArrayList<Printable> printables = new ArrayList<>();
        printables.add(new RawPrintable.Builder(new byte[]{27, 100, 4}).build());

        //Add Text
        printables.add(new TextPrintable.Builder().setText("Hello World: Jagadeesh")
                .setCharacterCode(DefaultPrinter.Companion.getCHARCODE_PC1252())
                .setNewLinesAfter(1)
                .build());

        //Custom Text
        printables.add(new TextPrintable.Builder()
                .setText("Hello World")
                .setLineSpacing(DefaultPrinter.Companion.getLINE_SPACING_60())
                .setAlignment(DefaultPrinter.Companion.getALIGNMENT_CENTER())
                .setEmphasizedMode(DefaultPrinter.Companion.getEMPHASIZED_MODE_BOLD())
                .setUnderlined(DefaultPrinter.Companion.getUNDERLINED_MODE_ON())
                .setNewLinesAfter(1)
                .build());

        printing.print(printables);
    }

    private void changePairAndUnpair() {
        if (Printooth.INSTANCE.hasPairedPrinter())
            btn_unpair_pair.setText(new StringBuilder("Unpair ").append(Printooth.INSTANCE
                    .getPairedPrinter().getName()).toString());
        else
            btn_unpair_pair.setText("Pair with Printer");
    }

    @Override
    public void connectingWithPrinter() {
        Toast.makeText(this, "Connecting to Printer", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void connectionFailed(String s) {
        Toast.makeText(this, "Failed: " + s, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(String s) {
        Toast.makeText(this, "Error: " + s, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onMessage(String s) {
        Toast.makeText(this, "Message: " + s, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void printingOrderSentSuccessfully() {
        Toast.makeText(this, "Order sent to printer", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == ScanningActivity.SCANNING_FOR_PRINTER && resultCode == Activity.RESULT_OK)
            initPrinting();
        changePairAndUnpair();
    }

    private void initPrinting() {
        if (!Printooth.INSTANCE.hasPairedPrinter())
            printing = Printooth.INSTANCE.printer();
        if (printing != null)
            printing.setPrintingCallback(this);
    }
}

Body:
Change this line of your code:

printing.print(printables);

To this:

Printooth.INSTANCE.printer().print(printables);


问:
JSON.parse() string that contains new line in a value
For reasons that can not be changed I have a string with a shitty piece of JSON with new lines like this:

```<code>{
    "description" : "- some text;
              - some more text;"
}
</code>```

I want to JSON.parse() it so it becomes usable. Of course, it fails when hitting the new line:

Unexpected token in JSON at position 156

How can I make this work?

答:
You need to get rid of that new line

replace the first and last characters with backticks

Body:
For reasons that can not be changed I have a string with a shitty piece of JSON with new lines like this:

{
    "description" : "- some text;
              - some more text;"
}

I want to JSON.parse() it so it becomes usable. Of course, it fails when hitting the new line:

Unexpected token in JSON at position 156

How can I make this work?


问:
Using R for web scraping
I need to get the list from a lot of webpages like this: https://fossilplants.info/genus.htm?page=3
I tried to do that using several R packages, such as rvest and XML, but didn't figure out how to make it work. Could anyone help me on that? Thanks so much.</p>

答:
We can use rvest like :

```<code>library(rvest)
library(purrr)

url <- 'https://fossilplants.info/genus.htm?page=3'

url %>%
  read_html() %>%
  html_nodes('h1') %>%
  html_text() %>%
  gsub('[\r\n\t]', '', .)

# [1] "Genus Abies-pollenites Thierg. in Raatz Abh. Preuss. Geol. Landesanst., Neue Folge, (183): 16.  26 Jan 1938"
# [2] "Genus Abieticedripites Maljavk. Trudy Vsesoyuzn. Neft. Nauchno-Issl. Geol.-Razved.  Inst., N. S., (119): 103.  11 Jul 1958"
# [3] "Genus Abietineae-pollenites R. Potonié Palaeontographica, Abt. B, Paläophytol., 91(5-6): 144, 145.  Apr 1951"
# [4] "Genus Abietineaepollenites R. Potonié in Delcourt, Sprumont Mém. Soc. Belge Géol.,  N. Sér. 4°, (5): 51.  1955"
# [5] "Genus Abietipites Wodehouse Bull. Torrey Bot. Club, 60(7): 491.  Oct 1933"
# [6] "Genus Abietites Maljavk. Trudy Vsesoyuzn. Neft. Nauchno-Issl. Geol.-Razved.  Inst., N. S., (231): 142.  10 Aug 1964"
# [7] "Genus Abietites Hising. Lethaea Svecica 110.  7 Dec 1836"
# [8] "Genus Abietopitys Kräusel Beitr. Geol. Erforsch. Deutsch. Schutzgeb., (20): 32.  11 Aug 1928"
# [9] "Unranked Abietosaccites Erdtman Svensk Bot. Tidskr., 41(1): 110.  26 Mar 1947"
#[10] "Genus Abietoxylon  73.  "
</code>```

If you want to do this for multiple pages, you can change the url like and perform the same function.

```<code>map(1:3, ~{
   url <- sprintf('https://fossilplants.info/genus.htm?page=%d', .x)
   url %>%
     read_html() %>%
     html_nodes('h1') %>%
     html_text() %>%
     gsub('[\r\n\t]', '', .)
}) %>% flatten_chr()
</code>```

Title: Using R for web scraping

Body:
We can use rvest like :

library(rvest)
library(purrr)

url <- 'https://fossilplants.info/genus.htm?page=3'

url %>%
  read_html() %>%
  html_nodes('h1') %>%
  html_text() %>%
  gsub('[\r\n\t]', '', .)

# [1] "Genus Abies-pollenites Thierg. in Raatz Abh. Preuss. Geol. Landesanst., Neue Folge, (183): 16.  26 Jan 1938"
# [2] "Genus Abieticedripites Maljavk. Trudy Vsesoyuzn. Neft. Nauchno-Issl. Geol.-Razved.  Inst., N. S., (119): 103.  11 Jul 1958"
# [3] "Genus Abietineae-pollenites R. Potonié Palaeontographica, Abt. B, Paläophytol., 91(5-6): 144, 145.  Apr 1951"
# [4] "Genus Abietineaepollenites R. Potonié in Delcourt, Sprumont Mém. Soc. Belge Géol.,  N. Sér. 4°, (5): 51.  1955"
# [5] "Genus Abietipites Wodehouse Bull. Torrey Bot. Club, 60(7): 491.  Oct 1933"
# [6] "Genus Abietites Maljavk. Trudy Vsesoyuzn. Neft. Nauchno-Issl. Geol.-Razved.  Inst., N. S., (231): 142.  10 Aug 1964"
# [7] "Genus Abietites Hising. Lethaea Svecica 110.  7 Dec 1836"
# [8] "Genus Abietopitys Kräusel Beitr. Geol. Erforsch. Deutsch. Schutzgeb., (20): 32.  11 Aug 1928"
# [9] "Unranked Abietosaccites Erdtman Svensk Bot. Tidskr., 41(1): 110.  26 Mar 1947"
#[10] "Genus Abietoxylon  73.  "

If you want to do this for multiple pages, you can change the url like and perform the same function.

map(1:3, ~{
   url <- sprintf('https://fossilplants.info/genus.htm?page=%d', .x)
   url %>%
     read_html() %>%
     html_nodes('h1') %>%
     html_text() %>%
     gsub('[\r\n\t]', '', .)
}) %>% flatten_chr()


问:
Single Sign On for for websites hosted on different domain
this is Emon. I have 2 websites and both are built in PHP. Now I'm trying to join these two websites which are mywebsite.com and mywebsite.live so that my users can log in to mywebsite.com and click on the live icon which is linked to mywebsite.live and will be instantly signed in, as it would be more convenient for customers to just log in once and they can navigate between the sites.

How do I create a single sign on page for login to both the side? For ie: If my users log in to mywebsite.com and press the live icon(I already have a live icon which redirects to mywebsite.live) it will take my users to mywebsite.live and automatically login as the same user. Please help me out here. Thanks

答:
The SSO solution that I've implemented here works as follows:

There is a master domain, login.mydomain.com with the script

master_login.php that manages the logins.

Each client domain has the script client_login.php

All the domains have a shared user session database.

When the client domain requires the user to be logged in, it redirects to the

master domain (login.mydomain.com/master_login.php). If the user has not signed in

to the master it requests authentication from the user (ie. display login page).

After the user is authenticated it creates a session in a database. If the user is

already authenticated it looks up their session id in the database.

The master domain returns to the client domain
(client.mydomain.com/client_login.php) passing the session id.

The client domain creates a cookie storing the session id from the master. The client can find out the logged in user by querying the shared database using the session id.
Notes:

The session id is a unique global identifier generated with algorithm from RFC 4122
The master_login.enter code herephp will only redirect to domains in its whitelist
The master and clients can be in different top level domains. Eg. client1.abc.com, client2.xyz.com, login.mydomain.com


问:
Array of JavaScript arrow functions
I'm implementing the card game Hearts in JavaScript, and one of the core elements of the game is that you can pass your cards to other players. My game has strictly 4 players, no more, no less.

The passing order goes left, right, straight ahead, then no passing. Therefore, P1 would pass to P2, P4, P3, and then pass to nobody. The cycle loops until the game is over.

I am trying to implement this logic via arrow functions, however, it is not working. What I am trying to do is print out the player, and the player that they should pass to, based on a given index.

Here is my code, I hope it is clear what I am trying to do.

const players = [1, 2, 3, 4];
const passingOrder = 2;
const passCards = [
  i => (i + 1) % 4, //pass left
  i => (i - 1 + 4) % 4, //pass right
  i => (i + 2) % 4, //pass straight
  i => i //pass to ones self
];

players.forEach((player, index) => {
  console.log(player + "passes to " + passCards[passingOrder](index))
})```

答:
In your case, you have passCards which takes an index and return an index. You can also consider passTo (just named differently) which takes a player and returns a player.

Below an example in which passTo defines the possible actions

const players = [1, 2, 3, 4];
const passingOrder = 2;
const passTo = (players => {
  const inIndexSpace = cb => {
    return player => {
      const i = players.indexOf(player)
      return players[cb(i)]
    }
  }
  return {
    left: inIndexSpace(i => (i + 1) % 4),
    right: inIndexSpace(i => (i - 1 + 4) % 4),
    straight: inIndexSpace(i => (i + 2) % 4),
    self: inIndexSpace(i => i)
  }
})(players)

players.forEach((player, index) => {
  console.log(player + "passes to " + passTo.straight(player))
})```
</div>
</div>
</p>

<p>which in "minimal" form (which you should avoid since dupplicate code) would be</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const players = [1, 2, 3, 4];
const passingOrder = 2;
const passTo = [
  player => { const i = players.indexOf(player); return players[(i + 1) % 4]},
  player => { const i = players.indexOf(player); return players[(i - 1 + 4) % 4]},
  player => { const i = players.indexOf(player); return players[(i + 2) % 4]},
  player => { const i = players.indexOf(player); return players[i]}
];

players.forEach((player, index) => {
  console.log(player + "passes to " + passTo[passingOrder](player))
})</code>```

Title: Array of JavaScript arrow functions

Body:
In your case, you have passCards which takes an index and return an index. You can also consider passTo (just named differently) which takes a player and returns a player.

Below an example in which passTo defines the possible actions

const players = [1, 2, 3, 4];
const passingOrder = 2;
const passTo = (players => {
  const inIndexSpace = cb => {
    return player => {
      const i = players.indexOf(player)
      return players[cb(i)]
    }
  }
  return {
    left: inIndexSpace(i => (i + 1) % 4),
    right: inIndexSpace(i => (i - 1 + 4) % 4),
    straight: inIndexSpace(i => (i + 2) % 4),
    self: inIndexSpace(i => i)
  }
})(players)

players.forEach((player, index) => {
  console.log(player + "passes to " + passTo.straight(player))
})

which in "minimal" form (which you should avoid since dupplicate code) would be

const players = [1, 2, 3, 4];
const passingOrder = 2;
const passTo = [
  player => { const i = players.indexOf(player); return players[(i + 1) % 4]},
  player => { const i = players.indexOf(player); return players[(i - 1 + 4) % 4]},
  player => { const i = players.indexOf(player); return players[(i + 2) % 4]},
  player => { const i = players.indexOf(player); return players[i]}
];

players.forEach((player, index) => {
  console.log(player + "passes to " + passTo[passingOrder](player))
})


答:
```<code>for row in df['Domains']:
    phrase = re.findall('.*;', row)
    if len(phrase) > 0:
        print(phrase[0])
    else:
        print(row)
</code>```

Title: Extract word uptill certain symbol

Body:
Hi I have this uniprot gff data that looks like

+--------+--------+-------+------+------------------------------------------------------------------------------------------------------+
| Entry  | check  | start | end  |                                               Domains                                               |
+--------+--------+-------+------+------------------------------------------------------------------------------------------------------+
| O75581 | Repeat |    63 |  106 |  Note=LDL-receptor class B 1                                                                         |
| O75581 | Repeat |   150 |  193 |  Note=LDL-receptor class B 3                                                                         |
| O75581 | Domain |   282 |  324 |  Note=EGF-like 1                                                                                |
| O75581 | Domain |  1248 | 1286 |  Note=LDL-receptor class A 1;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00124 |
| O75581 | Domain |  1287 | 1323 |  Note=LDL-receptor class A 2;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00124 |
| O75581 | Domain |  1325 | 1361 |  Note=LDL-receptor class A 3;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00124 |
| P13688 | Domain |    35 |  142 |  Note=Ig-like V-type;Ontology_term=ECO:0000250;evidence=ECO:0000250|UniProtKB:P31997                 |
| P13688 | Domain |   145 |  232 |  Note=Ig-like C2-type 1;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00114      |
| P13688 | Domain |   237 |  317 |  Note=Ig-like C2-type 2;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00114      |
| P13688 | Domain |   323 |  413 |  Note=Ig-like C2-type 3;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00114      |
| P19022 | Domain |   160 |  267 |  Note=Cadherin 1;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00043             |
| P19022 | Domain |   268 |  382 |  Note=Cadherin 2;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00043             |
| P19022 | Domain |   383 |  497 |  Note=Cadherin 3;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00043             |
| Q13586 | Domain |   132 |  200 |  Note=SAM;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00184                    |
| P04629 | Repeat |    90 |  113 |  Note=LRR 1                                                                                |
| P04629 | Repeat |   116 |  137 |  Note=LRR 2                                                                                |
+--------+--------+-------+------+------------------------------------------------------------------------------------------------------+

I am trying to extract the domain names column df['Domains]. With the following code, I am close to getting the first 2 3 words of the domain name but doesn't work universally.

for row in df['Domains']:
    print(re.findall(r'Note=(\w*)(.?)(\w*)', row))

which gives something like this

[('LDL', '-', 'receptor')]
[('LDL', '-', 'receptor')]
[('EGF', '-', 'like')]
[('Ig', '-', 'like')]
[('Ig', '-', 'like')]`

So, I wish to change my approach and get everything starting after Note= and ends before ; or end of line. How may I get this?


问:
Android: Prevent data notifications from popping up on the screen when app is in the background
I'm sending data payloads through FCM and handling them in the onMessageReceived() method of FirebaseMessagingService. The problem is, when the app is in the background, the push notifications seem to be popping up each time the device handles them. I'd like them to be silent similar to how Android delivers notification payloads.

How do I make sure the notifications do not create this popup effect? I'm on Android 9.

Here's how the notification is generated on the client:

```<code>var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(this, myChannelId)
                              .SetContentTitle(title)
                              .SetContentText(body)
                              .SetSmallIcon(Resource.Mipmap.ic_launcher)
                              .SetAutoCancel(true)
                              .SetContentIntent(pendingIntent);
</code>```

and this is how it's notified:

```<code>if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
   notificationBuilder.SetChannelId(myChannelId);

var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(myId, notificationBuilder.Build());
</code>```

答:
When app is killed / in background...

When only 'data' payload is passed in request, notification will be generated with popup, and handled by user in 'onMessageReceived'

When only 'notification' payload is passed in request, notification will be generated without popup, and handled by android OS

When both 'data' and 'notification' payload are passed in request, notification will be generated without popup, and handled by android OS and data will be available for handling in extras of the intent.

So, in our case (don't want to show notification as popup) pass both 'data' and 'notification' payloads in request params. (Here title and body will be shown, what is passed in notification payload)

Refer official link: https://firebase.google.com/docs/cloud-messaging/android/receive#handling_messages

Body:
I'm sending data payloads through FCM and handling them in the onMessageReceived() method of FirebaseMessagingService. The problem is, when the app is in the background, the push notifications seem to be popping up each time the device handles them. I'd like them to be silent similar to how Android delivers notification payloads.

How do I make sure the notifications do not create this popup effect? I'm on Android 9.

Here's how the notification is generated on the client:

var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(this, myChannelId)
                              .SetContentTitle(title)
                              .SetContentText(body)
                              .SetSmallIcon(Resource.Mipmap.ic_launcher)
                              .SetAutoCancel(true)
                              .SetContentIntent(pendingIntent);

and this is how it's notified:

if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
   notificationBuilder.SetChannelId(myChannelId);

var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(myId, notificationBuilder.Build());


问:
spring security with spring boot cant redirect after login
I encountered a problem when integrating spring security with spring boot.After  Overwriting the WebSecurityConfigurerAdapter, I can't redirect to the successful page(wlecome.ftl) when I've accessed the login page.It's aways redirect to the login page(index.ftl) without error logs.

Is there anyting I missed?Help is aways appreciated,thanks!

SecurityConfig.java

```<code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    MyUserDetailsService detailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/user/**").hasRole("USER")
                .anyRequest().fullyAuthenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error=true")
                .usernameParameter("username")
                .passwordParameter("password")
                .defaultSuccessUrl("/user/welcome")//add this but not work
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .permitAll();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**", "/css/**", "/images/**", "/**/favicon.ico");
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER");
    }
</code>```

Login.Controller

```<code>@Controller
public class LoginController {

    @RequestMapping("/login")
    public String login(){
        return "index";
    }

    @RequestMapping("/user/welcome")
    public String welcome(){
        return "user/welcome";
    }
</code>```

index.ftl(the login page)

```<code><!DOCTYPE html>
<#import "/spring.ftl" as spring />
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="<@spring.url '/login' />" method="post">
    username:<input type="text" name="username"><br>
    password：<input type="password" name="password"><br>
    <input type="submit" value="login">
</form>

</body>
</html>
</code>```

welcome.ftl

```<code><html>
  <head>

  </head>
<body>
  welcome
</body>
</html>
</code>```

答:
try this</p>

```<code>.defaultSuccessUrl("/user/welcome",true)
</code>```

Body:
I encountered a problem when integrating spring security with spring boot.After  Overwriting the WebSecurityConfigurerAdapter, I can't redirect to the successful page(wlecome.ftl) when I've accessed the login page.It's aways redirect to the login page(index.ftl) without error logs.

Is there anyting I missed?Help is aways appreciated,thanks!

SecurityConfig.java

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    MyUserDetailsService detailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/user/**").hasRole("USER")
                .anyRequest().fullyAuthenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error=true")
                .usernameParameter("username")
                .passwordParameter("password")
                .defaultSuccessUrl("/user/welcome")//add this but not work
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .permitAll();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**", "/css/**", "/images/**", "/**/favicon.ico");
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER");
    }

Login.Controller

@Controller
public class LoginController {

    @RequestMapping("/login")
    public String login(){
        return "index";
    }

    @RequestMapping("/user/welcome")
    public String welcome(){
        return "user/welcome";
    }

index.ftl(the login page)

<!DOCTYPE html>
<#import "/spring.ftl" as spring />

    <meta charset="UTF-8">
    <title>Title</title>

<form action="<@spring.url '/login' />" method="post">
    username:<input type="text" name="username">

    password：<input type="password" name="password">

    <input type="submit" value="login">
</form>

welcome.ftl

  welcome

Body:
try this

.defaultSuccessUrl("/user/welcome",true)


问:
Bad Request Error after creation of payment
After trying payment-creation API Of Razorpay below Error response is getting </p>

```<code>Error: { code: 'BAD_REQUEST_ERROR',
     description: 'Payment failed. Please contact site admin',
     field: 'amount' } }
Request :
     { amount: 1000, // in currency subunits. Here 1000 = 1000 paise, which equals to ₹10
      currency: 'INR',// Default is INR. We support more than 90 currencies.
      email: 'test12@test.com',
      contact: 'XXXXXXXXXX',
      order_id: 'order_EFRPoaGqJF0jMR',
      method: 'netbanking',
      bank: 'HDFC'
}
</code>```

答: I got answer of my question. The amount passing through request is more than 10 ₹. </p>

Body:
After trying payment-creation API Of Razorpay below Error response is getting

Error: { code: 'BAD_REQUEST_ERROR',
     description: 'Payment failed. Please contact site admin',
     field: 'amount' } }
Request :
     { amount: 1000, // in currency subunits. Here 1000 = 1000 paise, which equals to ₹10
      currency: 'INR',// Default is INR. We support more than 90 currencies.
      email: 'test12@test.com',
      contact: 'XXXXXXXXXX',
      order_id: 'order_EFRPoaGqJF0jMR',
      method: 'netbanking',
      bank: 'HDFC'
}


问:
TypeError when assigning a random value from a list to a variable?
I have a list and I want to assign a random element from that list to a new variable five times in order to generate a hand of cards. I've searched, and I can't seem to understand why my random.choice is causing errors.

```<code>import random

cards = { '2' '3' '4' '5' '6' '7' '8' '9' 'J' 'Q' 'K' 'A' }

for newCard in range(5):
        newDraw = random.choice(cards)
        playerdeck.append(newDraw)
        if newDraw in playerdeck:
                playermatches = playermatches + 1
        newDraw = oldDraw
</code>```

When I try to run it I get this error:

```<code>Traceback (most recent call last):
  File "C:\Users\Nathaniel\Desktop\Fcard.py", line 6, in <module>
    newDraw = random.choice(cards)
  File "C:\Python32\lib\random.py", line 253, in choice
    return seq[i]
TypeError: 'set' object does not support indexing
</code>```

答:
There's a problem with your set definition.
When you have multiple strings side by side, python concatenates them as if you did 'A' + 'B'. So you generated a set with only one element which is '23456789JQKA'

You don't really need a set or a list to do that:

```<code>>>> cards = '23456789JQKA'
>>> random.choice(cards)
</code>```

PS:
Although sets cannot be indexed, they can be iterated:

```<code>>>> [int(i) for i in {'1','2','3'}]
[1, 3, 2]
</code>```

Note the order may not be preserved.

Body:
I have a list and I want to assign a random element from that list to a new variable five times in order to generate a hand of cards. I've searched, and I can't seem to understand why my random.choice is causing errors.

import random

cards = { '2' '3' '4' '5' '6' '7' '8' '9' 'J' 'Q' 'K' 'A' }

for newCard in range(5):
        newDraw = random.choice(cards)
        playerdeck.append(newDraw)
        if newDraw in playerdeck:
                playermatches = playermatches + 1
        newDraw = oldDraw

When I try to run it I get this error:

Traceback (most recent call last):
  File "C:\Users\Nathaniel\Desktop\Fcard.py", line 6, in <module>
    newDraw = random.choice(cards)
  File "C:\Python32\lib\random.py", line 253, in choice
    return seq[i]
TypeError: 'set' object does not support indexing

Body:
There's a problem with your set definition.
When you have multiple strings side by side, python concatenates them as if you did 'A' + 'B'. So you generated a set with only one element which is '23456789JQKA'

You don't really need a set or a list to do that:

>>> cards = '23456789JQKA'
>>> random.choice(cards)

PS:
Although sets cannot be indexed, they can be iterated:

>>> [int(i) for i in {'1','2','3'}]
[1, 3, 2]

Note the order may not be preserved.


问:
How to select hierarchical static fields in Excel using C#
I need to get pivot data table based on FY'19 .
Here i am using power pivotTable but when it is inside the if loop the commented part is giving me error.</p>

```<code>while (index <= System.Convert.ToInt32(oPivotTable.CubeFields.Count))
            {
                if (oPivotTable.CubeFields[index].Name.ToString().Equals("[Range].[Task Closed Fiscal Yr]"))
                {
                    CubeField1 = oPivotTable.CubeFields[index];
                    CubeField1.Orientation = Microsoft.Office.Interop.Excel.XlPivotFieldOrientation.xlPageField;
                     //Facing issue in below code
                    CubeField1.CurrentPageName = String.Format("[{0}].[{1}].&[{2}]", "Task Age Summary", "Task Closed Fiscal Yr", "FY'19");
                }

                index += 1;

            }
        }
</code>```

答:
I wanted to comment but don't have enough rep ....

I ditched Microsoft.Office.Interop.Excel a while ago in favour of the fantastic NuGet package EPPlus

https://github.com/JanKallman/EPPlus/wiki/Getting-Started

Unfortunately the docs are pending on Pivot Tables at the moment but there are some examples.

https://github.com/JanKallman/EPPlus/blob/master/SampleApp/Sample12.cs

I have used this package for many Excel read/write operations and find it very easy to use.

Body:
I need to get pivot data table based on FY'19 .
Here i am using power pivotTable but when it is inside the if loop the commented part is giving me error.

while (index <= System.Convert.ToInt32(oPivotTable.CubeFields.Count))
            {
                if (oPivotTable.CubeFields[index].Name.ToString().Equals("[Range].[Task Closed Fiscal Yr]"))
                {
                    CubeField1 = oPivotTable.CubeFields[index];
                    CubeField1.Orientation = Microsoft.Office.Interop.Excel.XlPivotFieldOrientation.xlPageField;
                     //Facing issue in below code
                    CubeField1.CurrentPageName = String.Format("[{0}].[{1}].&[{2}]", "Task Age Summary", "Task Closed Fiscal Yr", "FY'19");
                }

                index += 1;

            }
        }


问:
Background image responsive without getting cropped
I've already made the background image to full size in my page, but when I inspect and try to display it in phone mode, my background image get cropped, how can I resist this thing so it can't get cropped but always cover particular part of the page </p>

```<code><div class="inner-banner has-base-color-overlay text-center" style="background: url(header.jpg); background-size: cover; position: center;">
    <div class="container">
        <div class="box">
            <h3>About Us</h3>
        </div>
    </div>
</div>
</code>```

答:
you can set these css for BackGround Image :

```<code>background-position: 100% 100%;
background-size: cover;
</code>```

and your manual height

Body:
I've already made the background image to full size in my page, but when I inspect and try to display it in phone mode, my background image get cropped, how can I resist this thing so it can't get cropped but always cover particular part of the page

About Us

Body:
you can set these css for BackGround Image :

background-position: 100% 100%;
background-size: cover;

and your manual height


问:
object of data specific to current logged in user

The goal is the user can save up to 7 field vals in obj userA, logout, log back in and the saved vals are there, retrievable. Specific to each user.

I am trying to create an object i.e. userA and update it, as the
user saves each field value (i.e. BaseMap: basemapSaved), save
the updated state in local storage, then retrieve saved state using
local storage. So, when the user logs out, then logs back in, their
saved data is still there specific to their username.

Below is my most recent attempt (full js): Any pointers? Am I going about this all wrong?

UPDATED ATTEMPT BELOW WITH BOUNTY.

I am simply trying to save an object of data and a field within it (i.e. userA.BaseMap.basemapSaved;) with local storage, on click.

I later want to parse that saved object in local storage, get that field, and update my API object i.e. object.data.field (userA.BaseMap.basemapSaved;) with the value saved and gathered. I can do this pro grammatically pretty easy, but the idea is to save the state per user, so they can log out, then log back in and have their selection saved.

```<code>  // Here I am trying to initialize the variables
    var currentUser;
    var basemapSaved;
    var userA[key] = {};

    // This function I am getting the logged in username, I want to set this as the object key in userA i.e. userA[key]

    function checkUser()  {
      var node = document.querySelectorAll("span.username")[0];
      currentUser = node.textContent;
      var key = currentUser;
      console.log("current user is:" + key);
    }

    // This is just a handler to wait to my basemap gallery loads before trying to save

    var basemapMod = document.getElementsByClassName("basemap")[0];
    basemapMod.addEventListener('click', ()=>{
      setTimeout(
        function() {
          BaseMapSaver();
        }, 2000);
    });

    function BaseMapSaver() {
      savebtnBM.addEventListener('click', ()=>{
        checkUser();
        // This is where I get the data from my API to save, gathers fine
        basemapSaved = app.widget.Manager.Gallery.activeBasemap.Item.id;
        // Below I am trying to set it, at first without the object key but would like to use the key
        var saveMap = localStorage.setItem('userA', JSON.stringify(userA));

        console.log(userA);
      });
    }
    // Home button
    var defaultViewHbtn = document.getElementById("home");

    defaultViewHbtn.addEventListener('click', ()=>{

        checkUser();

        // Here I try to parse the value from local storage object
        const userAParseValue = JSON.parse(localStorage.getItem('userA'));

        // Errors with Uncaught TypeError: Cannot read property 'BaseMap' of undefined
        userBaseMap = userAParseValue.userA.BaseMap.basemapSaved;
        console.log(userBaseMap);

        app.widget.Manager.Gallery.activeBasemap.Item.id = {
          portalItem: {
              id: userA.BaseMap.basemapSaved // this is where I want to load saved value from local storage object
            }
          };
    });
</code>```

答:
There are many ways to handle this depending upon your use case. You have specifically mentioned LocalStorage hence everyone is suggesting the same but cookies will fit your bill as well as long as you handle the expiry time properly for them.

Local Storage

Make an Object of fields you will like to store for that user

```<code>let obj = {'keyname' : value, 'keyname' : value};

//store it - mapping it with user
localStorage.setItem('userID', JSON.stringify(obj));

//retrieve and use on login success
let ret_obj= localStorage.getItem('userID');
</code>```

Cookies

You can set an arbitrary expiration time and then you again have choice of choosing just one variable or store it as a JSON itself.

```<code>document.cookie = "userName=Robert; expires=Fri, 31 Dec 9999 23:59:59 GMT";
</code>```

*Cookies will hold limited amount of data, as in not huge data (Which I don't think is the use case here because I checked your jsfiddle example, you are basically trying to store some data)

If you want to store JSON data in cookies check this out Click Here

*Why am I suggesting cookies? Many enterprises already do something similar for example even post logging out when you visit a website
  they will display your name and ask you to sign-in, it is just a
  personalisation addition.

Body:
The goal is the user can save up to 7 field vals in obj userA, logout, log back in and the saved vals are there, retrievable. Specific to each user.

I am trying to create an object i.e. userA and update it, as the
user saves each field value (i.e. BaseMap: basemapSaved), save
the updated state in local storage, then retrieve saved state using
local storage. So, when the user logs out, then logs back in, their
saved data is still there specific to their username.

Below is my most recent attempt (full js): Any pointers? Am I going about this all wrong?

UPDATED ATTEMPT BELOW WITH BOUNTY.

I am simply trying to save an object of data and a field within it (i.e. userA.BaseMap.basemapSaved;) with local storage, on click.

I later want to parse that saved object in local storage, get that field, and update my API object i.e. object.data.field (userA.BaseMap.basemapSaved;) with the value saved and gathered. I can do this pro grammatically pretty easy, but the idea is to save the state per user, so they can log out, then log back in and have their selection saved.

  // Here I am trying to initialize the variables
    var currentUser;
    var basemapSaved;
    var userA[key] = {};

    // This function I am getting the logged in username, I want to set this as the object key in userA i.e. userA[key]

    function checkUser()  {
      var node = document.querySelectorAll("span.username")[0];
      currentUser = node.textContent;
      var key = currentUser;
      console.log("current user is:" + key);
    }

    // This is just a handler to wait to my basemap gallery loads before trying to save

    var basemapMod = document.getElementsByClassName("basemap")[0];
    basemapMod.addEventListener('click', ()=>{
      setTimeout(
        function() {
          BaseMapSaver();
        }, 2000);
    });

    function BaseMapSaver() {
      savebtnBM.addEventListener('click', ()=>{
        checkUser();
        // This is where I get the data from my API to save, gathers fine
        basemapSaved = app.widget.Manager.Gallery.activeBasemap.Item.id;
        // Below I am trying to set it, at first without the object key but would like to use the key
        var saveMap = localStorage.setItem('userA', JSON.stringify(userA));

        console.log(userA);
      });
    }
    // Home button
    var defaultViewHbtn = document.getElementById("home");

    defaultViewHbtn.addEventListener('click', ()=>{

        checkUser();

        // Here I try to parse the value from local storage object
        const userAParseValue = JSON.parse(localStorage.getItem('userA'));

        // Errors with Uncaught TypeError: Cannot read property 'BaseMap' of undefined
        userBaseMap = userAParseValue.userA.BaseMap.basemapSaved;
        console.log(userBaseMap);

        app.widget.Manager.Gallery.activeBasemap.Item.id = {
          portalItem: {
              id: userA.BaseMap.basemapSaved // this is where I want to load saved value from local storage object
            }
          };
    });

Body:
There are many ways to handle this depending upon your use case. You have specifically mentioned LocalStorage hence everyone is suggesting the same but cookies will fit your bill as well as long as you handle the expiry time properly for them.

Local Storage

Make an Object of fields you will like to store for that user

let obj = {'keyname' : value, 'keyname' : value};

//store it - mapping it with user
localStorage.setItem('userID', JSON.stringify(obj));

//retrieve and use on login success
let ret_obj= localStorage.getItem('userID');

Cookies

You can set an arbitrary expiration time and then you again have choice of choosing just one variable or store it as a JSON itself.

document.cookie = "userName=Robert; expires=Fri, 31 Dec 9999 23:59:59 GMT";

*Cookies will hold limited amount of data, as in not huge data (Which I don't think is the use case here because I checked your jsfiddle example, you are basically trying to store some data)

If you want to store JSON data in cookies check this out Click Here

*Why am I suggesting cookies? Many enterprises already do something similar for example even post logging out when you visit a website
  they will display your name and ask you to sign-in, it is just a
  personalisation addition.


问:
How to solve ReadTimeoutError: HTTPSConnectionPool(host='pypi.python.org', port=443) with pip?
I recently need to install some packages

```<code>pip install future
pip install scikit-learn
pip install numpy
pip install scipy
</code>```

I also tried by writin sudo before them but all it came up with the following errors in red lines:

```<code>Exception:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 290, in run
    requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1198, in prepare_files
    do_download,
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1376, in unpack_url
    self.session,
  File "/usr/lib/python2.7/dist-packages/pip/download.py", line 572, in unpack_http_url
    download_hash = _download_url(resp, link, temp_location)
  File "/usr/lib/python2.7/dist-packages/pip/download.py", line 433, in _download_url
    for chunk in resp_read(4096):
  File "/usr/lib/python2.7/dist-packages/pip/download.py", line 421, in resp_read
    chunk_size, decode_content=False):
  File "/usr/lib/python2.7/dist-packages/urllib3/response.py", line 256, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/usr/lib/python2.7/dist-packages/urllib3/response.py", line 201, in read
    raise ReadTimeoutError(self._pool, None, 'Read timed out.')
ReadTimeoutError: HTTPSConnectionPool(host='pypi.python.org', port=443): Read timed out.

Storing debug log for failure in /root/.pip/pip.log'
</code>```

答:
They are two ways to handle this issue:

```<code>sudo pip install --default-timeout=100 future
</code>```

or

```<code>pip install --default-timeout=100 future
</code>```

Note: If you are not superuser of your machine, the sudo pip command will not work.

Body:
I recently need to install some packages

pip install future
pip install scikit-learn
pip install numpy
pip install scipy

I also tried by writin sudo before them but all it came up with the following errors in red lines:

Exception:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 290, in run
    requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1198, in prepare_files
    do_download,
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1376, in unpack_url
    self.session,
  File "/usr/lib/python2.7/dist-packages/pip/download.py", line 572, in unpack_http_url
    download_hash = _download_url(resp, link, temp_location)
  File "/usr/lib/python2.7/dist-packages/pip/download.py", line 433, in _download_url
    for chunk in resp_read(4096):
  File "/usr/lib/python2.7/dist-packages/pip/download.py", line 421, in resp_read
    chunk_size, decode_content=False):
  File "/usr/lib/python2.7/dist-packages/urllib3/response.py", line 256, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/usr/lib/python2.7/dist-packages/urllib3/response.py", line 201, in read
    raise ReadTimeoutError(self._pool, None, 'Read timed out.')
ReadTimeoutError: HTTPSConnectionPool(host='pypi.python.org', port=443): Read timed out.

Storing debug log for failure in /root/.pip/pip.log'

Body:
They are two ways to handle this issue:

sudo pip install --default-timeout=100 future

or

pip install --default-timeout=100 future

Note: If you are not superuser of your machine, the sudo pip command will not work.


问:
How to convert date and time from kdb server query response using qPython and pandas?
I have issue converting date and times in the kdb server reply.

I have searched in Internet and here, in StackOverflow, but I could not find a suitable solution. Therefore I need help.

```<code>from qpython import qconnection
import pandas as pd
from datetime import datetime

query = 'select from trade where date = 2007.02.28, sym = `XXXX'

q = qconnection.QConnection(host=server, port=server_port, username=user, password=server_password, timeout=server_timeout)

q.open()

df = pd.DataFrame(q.sendSync(query))
print(df.to_string())

q.close()
</code>```

The reply is (only header row and the first line of it):

```<code>      date            time    ex      sym     cond     size          price  stop  corr      seq   src  trpt     participantTime1  rrn     participantTime2   id  exempt
0       2615  15517877000000  b'P'  b'XXXX'  b'T   '      500      27.670000  b' '     0     1095  b'N'  b' ' -9223372036854775808  b'' -9223372036854775808  b''  -32768
</code>```

How to convert date and time? Right now I have 2615 for date, which has to be 2007.02.28. The same goes with the time. It is 15517877000000, while it should be 0D04:18:37.877000000. (Most probably 0D in time comes from the encoding - a problem which I shall solve later, if needed.). The same goes for participantTime1 and participantTime2

Thank you in advance for anyone's time.

答:
Pandas integration and automatic temporal-type casting is supported by the qPython package, which would simplify your issue. You can find the relevant documentation here.

The only change you would need to make from your code snippet is to set the pandas flag to True when instantiating the QConnection object:

q = qconnection.QConnection(host=server, port=server_port, username=user,
  password=server_password, timeout=server_timeout, pandas=True)
```

<p>In this case, you also wouldn't need to convert the return value from <code>sendSync</code> as q tables will now be represented as pandas dataframes by default:</p>

<pre class="lang-py prettyprint-override"><code>df = q.sendSync(query)
</code>```

Body:
I have issue converting date and times in the kdb server reply.

I have searched in Internet and here, in StackOverflow, but I could not find a suitable solution. Therefore I need help.

from qpython import qconnection
import pandas as pd
from datetime import datetime

query = 'select from trade where date = 2007.02.28, sym = `XXXX'

q = qconnection.QConnection(host=server, port=server_port, username=user, password=server_password, timeout=server_timeout)

q.open()

df = pd.DataFrame(q.sendSync(query))
print(df.to_string())

q.close()

The reply is (only header row and the first line of it):

      date            time    ex      sym     cond     size          price  stop  corr      seq   src  trpt     participantTime1  rrn     participantTime2   id  exempt
0       2615  15517877000000  b'P'  b'XXXX'  b'T   '      500      27.670000  b' '     0     1095  b'N'  b' ' -9223372036854775808  b'' -9223372036854775808  b''  -32768

How to convert date and time? Right now I have 2615 for date, which has to be 2007.02.28. The same goes with the time. It is 15517877000000, while it should be 0D04:18:37.877000000. (Most probably 0D in time comes from the encoding - a problem which I shall solve later, if needed.). The same goes for participantTime1 and participantTime2

Thank you in advance for anyone's time.

Body:
Pandas integration and automatic temporal-type casting is supported by the qPython package, which would simplify your issue. You can find the relevant documentation here.

The only change you would need to make from your code snippet is to set the pandas flag to True when instantiating the QConnection object:

q = qconnection.QConnection(host=server, port=server_port, username=user,
  password=server_password, timeout=server_timeout, pandas=True)

In this case, you also wouldn't need to convert the return value from sendSync as q tables will now be represented as pandas dataframes by default:

df = q.sendSync(query)


问:
how to position radio button outside of a block with css
I would like to create a question row like this http://imageshack.us/photo/my-images/200/questionh.png/

At this time, my html source is :

```<code><p class="questionrow">
  <span class="question">question label</span>
  <span class="reponses">
    <input type='radio' class="radiocontrol"/><label class="radioanswer">Oui</label>
    <input type='radio' class="radiocontrol"/><label class="radioanswer">Non</label>
  </span>
</p>
</code>```

(but i can change it)

ths css is :

```<code>.questionrow
{
  width:1000px;
  background-color: #EDF2BE;
}

.question
{
  width: 300px;
  padding-left: 30px;
  padding-right: 30px;
  display: inline-block;
}

.reponses
{
  width: 600px;
  display: inline-block;
}

.radiocontrol {
  border: 1px solid #006;
  background: #ffc;
}
</code>```

I'd like to have 2 effects :

I would like to put the label outside, on top of the colored line. I would like to have the label on the same column of the radio button.

I would like to draw a vertical line (but I imagine it will be easy if there is a solution for the previous)

Does someone has some idea about that ?

Regards

答:
Here is a solution that closely resembles your sample image...

Demo: http://jsfiddle.net/Zjnw9/1/

HTML...

```<code><div class="row">
    <p class="q">This is a question?</p>
    <ul class="options">
        <li><label>One</label><input type="radio" /></li>
        <li><label>Two</label><input type="radio" /></li>
        <li><label>Three</label><input type="radio" /></li>
        <li><label>Four</label><input type="radio" /></li>
    </ul>
</div>
</code>```

CSS...

```<code>.row {
    padding-bottom: 2em;
}
.q {
    background-color: #EDF2BE;
    margin-top: 1.2em;
    padding: 0.5em;
}
.options {
    float: right;
    margin-top: -3.4em;
}
.options li {
    float: left;
    width: 100px;
    text-align: center;
    border-left: 1px solid #999;
    padding: 0em 0.5em 0.7em;
}
.options label {
    display: block;
    font-size: 9pt;
    padding-bottom: 0.8em;
}
</code>```

Body:
I would like to create a question row like this http://imageshack.us/photo/my-images/200/questionh.png/

At this time, my html source is :

  question label

    <input type='radio' class="radiocontrol"/>Oui
    <input type='radio' class="radiocontrol"/>Non

(but i can change it)

ths css is :

.questionrow
{
  width:1000px;
  background-color: #EDF2BE;
}

.question
{
  width: 300px;
  padding-left: 30px;
  padding-right: 30px;
  display: inline-block;
}

.reponses
{
  width: 600px;
  display: inline-block;
}

.radiocontrol {
  border: 1px solid #006;
  background: #ffc;
}

I'd like to have 2 effects :

I would like to put the label outside, on top of the colored line. I would like to have the label on the same column of the radio button.

I would like to draw a vertical line (but I imagine it will be easy if there is a solution for the previous)

Does someone has some idea about that ?

Regards

Body:
Here is a solution that closely resembles your sample image...

Demo: http://jsfiddle.net/Zjnw9/1/

HTML...

<div class="row">
    <p class="q">This is a question?</p>
    <ul class="options">
        <li><label>One</label><input type="radio" /></li>
        <li><label>Two</label><input type="radio" /></li>
        <li><label>Three</label><input type="radio" /></li>
        <li><label>Four</label><input type="radio" /></li>
    </ul>
</div>

CSS...

.row {
    padding-bottom: 2em;
}
.q {
    background-color: #EDF2BE;
    margin-top: 1.2em;
    padding: 0.5em;
}
.options {
    float: right;
    margin-top: -3.4em;
}
.options li {
    float: left;
    width: 100px;
    text-align: center;
    border-left: 1px solid #999;
    padding: 0em 0.5em 0.7em;
}
.options label {
    display: block;
    font-size: 9pt;
    padding-bottom: 0.8em;
}


问:
FPC/Lazarus component like TImageList, but for generic files?
Just like TImageList contains a collection of images, is there a similar component for generic files?

I know I can embed files as resources, but I'd like the convenience of storing different groups of files in different "TFileList" components, and to be able to retrieve files by name or by their position in the list.

Extra points if such a component allowed some sort of design time preview of the file content (just like TImageList lets you see what each image looks like, at design time).

(I come from Delphi where I wrote my own component to do the above, but before I rewrite and port the property editor and all that to Lazarus, maybe there is already something that is tried and tested...)

Thanks!

答:
You can use pre-defined lazarus TFPGList to specialize list of the type, that you want, for example - UTF8String
But, there's no T<>List as a component, only as object.
So, yes, this feature will be useful and i can implement, if have time,
also, there's a very limited RTTI, which has been updated only a few months ago, so you can access Methods and Properties now, so FP is more systemized, than delphi pascal, but also not so enterprise-developed, which limits it to implementations for common opensource and shareware project problems.
Nevertheless, it is more stable and supported, even my friends can contribute.</p>