问:
AWS lambda unable to send smtp email
I have a simple AWS lambda request handler running that sends an email using smtp. When I put this code into a local main() function, it runs well and sends the email. When running on aws, I keep getting the following javax.mail.MessagingException: 501 Syntax: HELO <hostname> error. Is there something that needs to be changed in AWS for the mail to go through? Here is my code:

```<code>Properties mailProps = new Properties();
mailProps.setProperty("mail.smtp.host", sesHost);
mailProps.setProperty("mail.smtp.port", port);
mailProps.setProperty("mail.smtp.user", user);
mailProps.setProperty("mail.smtp.auth", "true");
PasswordAuthentication auth = new PasswordAuthentication(user, password);
mailSession = Session.getInstance(mailProps, new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return auth;
    }
});

String toAddress = "example@example.com";

try{
    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress("noreply@example.com", "Example"));
    message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toAddress));
    message.setSubject("test subject");
    message.setContent("content content","text/html; charset=utf-8");

    System.out.println("Sending email to" + toAddress);

    Transport.send(message);
}
catch(Exception e){
    e.printStackTrace();
    System.out.println("Failed to send email");
}
</code>```

答:
There is a need to attach a Security Group with your Lambda which has port 25 open in its outbound rules.

In the Lambda configurations -

Select VPC (create one if there is no existing VPC in account)

Select subnets (create more than one in multiple AZs)

Select the Security group (which has port 25 open in Outbound rules or All traffic permission)

This should work.

Title: AWS lambda unable to send smtp email

Body:
I have a simple AWS lambda request handler running that sends an email using smtp. When I put this code into a local main() function, it runs well and sends the email. When running on aws, I keep getting the following javax.mail.MessagingException: 501 Syntax: HELO <hostname> error. Is there something that needs to be changed in AWS for the mail to go through? Here is my code:

Properties mailProps = new Properties();
mailProps.setProperty("mail.smtp.host", sesHost);
mailProps.setProperty("mail.smtp.port", port);
mailProps.setProperty("mail.smtp.user", user);
mailProps.setProperty("mail.smtp.auth", "true");
PasswordAuthentication auth = new PasswordAuthentication(user, password);
mailSession = Session.getInstance(mailProps, new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return auth;
    }
});

String toAddress = "example@example.com";

try{
    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress("noreply@example.com", "Example"));
    message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toAddress));
    message.setSubject("test subject");
    message.setContent("content content","text/html; charset=utf-8");

    System.out.println("Sending email to" + toAddress);

    Transport.send(message);
}
catch(Exception e){
    e.printStackTrace();
    System.out.println("Failed to send email");
}


来源: stackexchange

问:
Read CSV file using Java for checking doublicates
I have created a program that writes on a CSV file specific info: ID, name, average.

I want to add data again, but before adding it, I want to check that if the file already has the data I would not allow it to upload.

Note: I have already created a method that checks the data entered by the user and it won't allow the user to add it if the ID is already used, but it works only on the command line, so I want to be able to connect it to the file reader as well.

Note: Still I'm still new to reading and writing files.

I'm going to add two things:

The writing File

The check method.

Writing the file:

```<code>public void printStudents() throws IOException {
    FileWriter fileWriter = new FileWriter("studentList.csv", true);
    PrintWriter printWriter = new PrintWriter(fileWriter);

    for (int i = 0; i < this.myStudents.size(); i++) {
        printWriter.print(
                this.myStudents.get(i).getIDNumber() + "," +
                        this.myStudents.get(i).getName() + ","
                        + this.myStudents.get(i).getGPA() + "\n");
    }
    printWriter.close();```
```

<p>Here is the check method:</p>

```private int findStudent(String studentName) {
    for (int i = 0; i < this.myStudents.size(); i++) {
        Student student = this.myStudents.get(i);
        if (student.getIDNumber().equals(studentName)) {
            return i;
        }
    }
    return -1;

}
```

Note: this methods shows that if the "find student method has returned -1, the student can be added successfully".

答:
I suggest you use a LinkedHashMap to save the data from the file, using the student name, the id number and the GPA as a unique key:

//Here you can read the old CSV file
//...
//Then read each student line by line:
LinkedHashMap<String, Student> hashMap = new LinkedHashMap<String, Student>();
for (int i = 0; i < this.myStudents.size(); i++) {
   String tempKey= this.myStudents.get(i).getIDNumber() + this.myStudents.get(i).getName() + this.myStudents.get(i).getGPA();
   if(!hashMap.containsKey(tempKey)){
       hashMap.put(tempKey, this.myStudents.get(i))
   }

//Here is the check method
private boolean findStudent(Student student, LinkedHashMap<String, Student> hashMap) {
    boolean isFound = false;
    String theKey = student.getIDNumber() + student.getName() + student.getGPA();
    if(hashMap.containsKey(theKey)){
        isFound = true;
    }
    return isFound;
}

```

ContentLicense: CC BY-SA 4.0

Body:
I have created a program that writes on a CSV file specific info: ID, name, average.

I want to add data again, but before adding it, I want to check that if the file already has the data I would not allow it to upload.

Note: I have already created a method that checks the data entered by the user and it won't allow the user to add it if the ID is already used, but it works only on the command line, so I want to be able to connect it to the file reader as well.

Note: Still I'm still new to reading and writing files.

I'm going to add two things:

The writing File

The check method.

Writing the file:

public void printStudents() throws IOException {
    FileWriter fileWriter = new FileWriter("studentList.csv", true);
    PrintWriter printWriter = new PrintWriter(fileWriter);

    for (int i = 0; i < this.myStudents.size(); i++) {
        printWriter.print(
                this.myStudents.get(i).getIDNumber() + "," +
                        this.myStudents.get(i).getName() + ","
                        + this.myStudents.get(i).getGPA() + "\n");
    }
    printWriter.close();```

Here is the check method:

private int findStudent(String studentName) {
    for (int i = 0; i < this.myStudents.size(); i++) {
        Student student = this.myStudents.get(i);
        if (student.getIDNumber().equals(studentName)) {
            return i;
        }
    }
    return -1;

}

Note: this methods shows that if the "find student method has returned -1, the student can be added successfully".


问:
Execute powershell command using python
I want to execute power-shell command using my python script to find windows RDP event detail but it's not working.it shown error:

'C:\Windows\System32\powershell.exe' is an internal or external
  command, It is not recognized as an operable program or batch file.

PowerShell command:

```<code>Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" | Where-Object {$_.ID -eq "1149"}
</code>```

Here is my python code:

```<code>import subprocess

subprocess.call('C:\Windows\System32\powershell.exe Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" | Where-Object {$_.ID -eq "1149"}', shell=True)
</code>```

答:
Instead of using PowerShell, You can use pywin32 module to get the Windows events.

If there is no specific reason to use PowerShell then you can achieve it by using following code snippet

```<code>import win32evtlog # install pywin32 module

server = 'localhost' # target computer to get event logs
logtype = 'Microsoft-Windows-TerminalServices-RemoteConnectionManager' # 'Application' # 'Security'
hand = win32evtlog.OpenEventLog(server,logtype)
flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
total = win32evtlog.GetNumberOfEventLogRecords(hand)

while True:
    events = win32evtlog.ReadEventLog(hand, flags,0)
    if events:
        for event in events:
            if "Microsoft-Windows-Terminal-Services-RemoteConnectionManager" in event.SourceName:
                print ('Event Category:', event.EventCategory)
                print ('Time Generated:', event.TimeGenerated)
                print ('Source Name:', event.SourceName)
                print ('Event ID:', event.EventID)
                print ('Event Type:', event.EventType)
                data = event.StringInserts
                if data:
                    print ('Event Data:')
                    for msg in data:
                        print (msg)
                print
</code>```

Title: Execute powershell command using python

Body:
I want to execute power-shell command using my python script to find windows RDP event detail but it's not working.it shown error:

'C:\Windows\System32\powershell.exe' is an internal or external
  command, It is not recognized as an operable program or batch file.

PowerShell command:

Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" | Where-Object {$_.ID -eq "1149"}

Here is my python code:

import subprocess

subprocess.call('C:\Windows\System32\powershell.exe Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" | Where-Object {$_.ID -eq "1149"}', shell=True)

Body:
Instead of using PowerShell, You can use pywin32 module to get the Windows events.

If there is no specific reason to use PowerShell then you can achieve it by using following code snippet

import win32evtlog # install pywin32 module

server = 'localhost' # target computer to get event logs
logtype = 'Microsoft-Windows-TerminalServices-RemoteConnectionManager' # 'Application' # 'Security'
hand = win32evtlog.OpenEventLog(server,logtype)
flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
total = win32evtlog.GetNumberOfEventLogRecords(hand)

while True:
    events = win32evtlog.ReadEventLog(hand, flags,0)
    if events:
        for event in events:
            if "Microsoft-Windows-Terminal-Services-RemoteConnectionManager" in event.SourceName:
                print ('Event Category:', event.EventCategory)
                print ('Time Generated:', event.TimeGenerated)
                print ('Source Name:', event.SourceName)
                print ('Event ID:', event.EventID)
                print ('Event Type:', event.EventType)
                data = event.StringInserts
                if data:
                    print ('Event Data:')
                    for msg in data:
                        print (msg)
                print


问:
I'm not able to POST data using JavaScript Ajax
I'm able to get the data from the filltext web api using Ajax GET request ,but when i use Post request then i can't see anything returned to the console and also no errors, how do i solve this?

const xhr = new XMLHttpRequest();
const url = 'http://www.filltext.com/?rows=1&pretty=true&id={index}&fname={sahil}&lname={keshav}&company={business}';

let test = JSON.stringify({
    id:124,
    fname:'sunil',
    lname:'singh',
    company:'reebok'
});

function getData(){
    xhr.onreadystatechange = () => {
        if(this.readyState === 4 && this.status === 200){
            let tes = JSON.parse(this.responseText)
            console.log(tes);
        }
    }
    xhr.open('POST',url,true);
    xhr.setRequestHeader('Content-type','application/json');
    xhr.send(test);
}
```

答:
Make sure to console log all the information that will help you debug the request, and add an error handling function as well.

Also, the Developer Console is your friend. Check the browser's console and the Networks Tab (Chrome) to figure out what's going on. Make sure to check the XHR option in the Network's Tab to display only the XMLHttpRequest network requests.

Here's a StackOverflow post that can help you in that direction.

const xhr = new XMLHttpRequest();
const url = 'http://www.filltext.com/?rows=1&pretty=true&id={index}&fname={sahil}&lname={keshav}&company={business}';

let test = JSON.stringify({
           id:124,
           fname:'sunil',
           lname:'singh',
           company:'reebok'
});
    function getData(){
       xhr.onreadystatechange = () => {
           console.log( "onReadyStateChange:", xhr.readyState, xhr.status, xhr.statusText);
           if(this.readyState === 4 && this.status === 200){
               let tes = JSON.parse(this.responseText)
                 console.log(tes);
          }
      }
       xhr.open('POST',url,true);
       xhr.setRequestHeader('Content-type','application/json');
       xhr.send(test);
       // Add error handling:
       xhr.onerror = function(){
           console.log( "onError:", xhr.status, xhr.statusText);
           // Triggers when request couldn't be completed
       }
     }
```


问:
Switch Views Within UITabBar Tab Using Segmented Control
I am working on an app that allows two media galleries to be loaded into the same tab. They have separate XIB files and are loaded as such. However, once I switch views using the segmented control the UITabBar disappears.

This is how I am switching the views:

```<code>//Switch Views
- (IBAction)segmentSwitch:(id)sender
   {
   if([sender selectedSegmentIndex] == 0)
   {
      MediaViewController *vc = [[MediaViewController alloc] initWithNibName: @"MediaView" bundle:nil];
      vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
      [self presentModalViewController: vc animated: YES];
   }
   else if([sender selectedSegmentIndex] == 1)
   {
      MediaViewControllerTwo*v2 = [[MediaViewControllerTwo alloc] initWithNibName: @"MediaViewTwo" bundle:nil];
      v2.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
      [self presentModalViewController: v2 animated: YES];
   }
}
</code>```

答: You should not present them modally when using a UITabBarController. They are not the right tools. You should either switch the views attached to the view controller that is associated with the tab. How you would do it depends on how you got your tab bar modelled.

ContentLicense: CC BY-SA 3.0

Body:
I am working on an app that allows two media galleries to be loaded into the same tab. They have separate XIB files and are loaded as such. However, once I switch views using the segmented control the UITabBar disappears.

This is how I am switching the views:

//Switch Views
- (IBAction)segmentSwitch:(id)sender
   {
   if([sender selectedSegmentIndex] == 0)
   {
      MediaViewController *vc = [[MediaViewController alloc] initWithNibName: @"MediaView" bundle:nil];
      vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
      [self presentModalViewController: vc animated: YES];
   }
   else if([sender selectedSegmentIndex] == 1)
   {
      MediaViewControllerTwo*v2 = [[MediaViewControllerTwo alloc] initWithNibName: @"MediaViewTwo" bundle:nil];
      v2.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
      [self presentModalViewController: v2 animated: YES];
   }
}


问:
CSS - Box background color change on drop menu when hovering on it - Wordpress
Firstable i'm very noob in CSS/web coding so please forgive me...

I'm requesting your help because i'm still stuck on in my wordpress dev site customization.

I set up a border-radius, background color and hover style for my menu bar. The hover works well on the main navigation menu but when i scroll down the dropmenu with the border-radius configured, a "default" background appears with 4 grey corners. The background color should be the same as parent (#5b2121d4)

I didn't find an easy fix solution in Css code, and couldn't find the item target in google dev tools inspection.

Any idea about removing this "default" background ?

Menu

This is my website dev platform : http://dev.achete-local.fr/boutique/

Thanks for your help

答: Remove the background colour from the sub menu.</p>


问:
Athena Issue - query string in lowercase
I've table that contains JSON column_A.

Instead of setting column_A to a struct, I set column_A as a string to query JSON.

The problem is when I query column_A I receive the data in lowercase.

```<code>CREATE EXTERNAL TABLE `table_test`(
  `userid` string COMMENT 'from deserializer',
  `column_a` string COMMENT 'from deserializer',
  `createdat` string COMMENT 'from deserializer',
  `updatedat` string COMMENT 'from deserializer')
ROW FORMAT SERDE
  'org.openx.data.jsonserde.JsonSerDe'
WITH SERDEPROPERTIES (
  'paths'='column_a,userId')
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  's3://test-stackoverflow/'
TBLPROPERTIES (
  'classification'='json',
  'transient_lastDdlTime'='1567353697')
</code>```

I understand that related to SerDe but I don't know what should I change to.

What can I do to solve it?

The reasons I don't set column_A as struct are:

1. The key is changing every time and as far as I know, I need to set the key values when I define the struct.

2. I've empty string and key - Got errors for query struct with "" as key.

Thanks.

答:
Found the solution.

The problem is with SerDe

https://docs.aws.amazon.com/athena/latest/ug/json.html

need to add 'case.insensitive'= "FALSE" to Serde properties.

```<code>CREATE EXTERNAL TABLE `table_test`(
  `userid` string COMMENT 'from deserializer',
  `column_a` string COMMENT 'from deserializer',
  `createdat` string COMMENT 'from deserializer',
  `updatedat` string COMMENT 'from deserializer')
ROW FORMAT SERDE
  'org.openx.data.jsonserde.JsonSerDe'
WITH SERDEPROPERTIES (
  'case.insensitive'= "FALSE",
  'paths'='column_a,userId')
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  's3://test-stackoverflow/'
TBLPROPERTIES (
  'classification'='json',
  'transient_lastDdlTime'='1567353697')
</code>```

Hope this will help someone.

Body:
I've table that contains JSON column_A.

Instead of setting column_A to a struct, I set column_A as a string to query JSON.

The problem is when I query column_A I receive the data in lowercase.

CREATE EXTERNAL TABLE `table_test`(
  `userid` string COMMENT 'from deserializer',
  `column_a` string COMMENT 'from deserializer',
  `createdat` string COMMENT 'from deserializer',
  `updatedat` string COMMENT 'from deserializer')
ROW FORMAT SERDE
  'org.openx.data.jsonserde.JsonSerDe'
WITH SERDEPROPERTIES (
  'paths'='column_a,userId')
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  's3://test-stackoverflow/'
TBLPROPERTIES (
  'classification'='json',
  'transient_lastDdlTime'='1567353697')

I understand that related to SerDe but I don't know what should I change to.

What can I do to solve it?

The reasons I don't set column_A as struct are:

1. The key is changing every time and as far as I know, I need to set the key values when I define the struct.

2. I've empty string and key - Got errors for query struct with "" as key.

Thanks.

Body:
Found the solution.

The problem is with SerDe

https://docs.aws.amazon.com/athena/latest/ug/json.html

need to add 'case.insensitive'= "FALSE" to Serde properties.

CREATE EXTERNAL TABLE `table_test`(
  `userid` string COMMENT 'from deserializer',
  `column_a` string COMMENT 'from deserializer',
  `createdat` string COMMENT 'from deserializer',
  `updatedat` string COMMENT 'from deserializer')
ROW FORMAT SERDE
  'org.openx.data.jsonserde.JsonSerDe'
WITH SERDEPROPERTIES (
  'case.insensitive'= "FALSE",
  'paths'='column_a,userId')
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  's3://test-stackoverflow/'
TBLPROPERTIES (
  'classification'='json',
  'transient_lastDdlTime'='1567353697')

Hope this will help someone.


问:
React native on layout change (listen view position)
I want to listen the position of a view I am moving with a pan responder. I am using the onLayout prop to get the width, height, x and y positions, but it only runs when the first render. Any ideas?

Here is the code:

```<code>import React, { useState, useRef } from "react";
import {
  View,
  Animated,
  PanResponder,
  Dimensions,
  StyleSheet,
} from "react-native";

const WINDOW_HEIGHT = Dimensions.get("window").height;

export default function Cropper({ photo }) {
  const [height, setHeight] = useState(WINDOW_HEIGHT / 2); // Use in future

  const pan = useRef(new Animated.ValueXY()).current;

  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderMove: Animated.event([null, { dy: pan.y }]),
      onPanResponderRelease: () => {
        pan.flattenOffset();
      },
    })
  ).current;

 const onLayout = (event) => {
    const {
      nativeEvent: { layout },
    } = event;

    // Recalculate top and buttom views' height (setNativeProps)
  };

  const panStyle = {
    transform: pan.getTranslateTransform(),
  };

  return (
    <View style={styles.container}>
      <View style={styles.blurView} />
      <Animated.View
        onLayout={(event) => onLayout(event)}
        {...panResponder.panHandlers}
        style={[
          styles.cropper,
          panStyle,
          {
            height: height,
          },
        ]}
      />
      <View style={styles.blurView} />
      <View style={styles.bottomButtonsContainer}></View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  blurView: {
    flex: 1,
    width: "100%",
    backgroundColor: "rgba(0, 0, 0, .9)",
  },
  cropper: {
    width: "100%",
    backgroundColor: "red",
  },
  bottomButtonsContainer: {
    position: "absolute",
    bottom: 0,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    width: "100%",
    height: 120,
  },
});
</code>```

What I am trying to do is get the middle view position when the user moves it, and then recalculate the top and buttom views' height.

答:
Looks like you forgot const for your onLayout.

I've tried your code on snack expo i can get console.logs when moving the red view

Body:
I want to listen the position of a view I am moving with a pan responder. I am using the onLayout prop to get the width, height, x and y positions, but it only runs when the first render. Any ideas?

Here is the code:

import React, { useState, useRef } from "react";
import {
  View,
  Animated,
  PanResponder,
  Dimensions,
  StyleSheet,
} from "react-native";

const WINDOW_HEIGHT = Dimensions.get("window").height;

export default function Cropper({ photo }) {
  const [height, setHeight] = useState(WINDOW_HEIGHT / 2); // Use in future

  const pan = useRef(new Animated.ValueXY()).current;

  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderMove: Animated.event([null, { dy: pan.y }]),
      onPanResponderRelease: () => {
        pan.flattenOffset();
      },
    })
  ).current;

 const onLayout = (event) => {
    const {
      nativeEvent: { layout },
    } = event;

    // Recalculate top and buttom views' height (setNativeProps)
  };

  const panStyle = {
    transform: pan.getTranslateTransform(),
  };

  return (
    <View style={styles.container}>
      <View style={styles.blurView} />
      <Animated.View
        onLayout={(event) => onLayout(event)}
        {...panResponder.panHandlers}
        style={[
          styles.cropper,
          panStyle,
          {
            height: height,
          },
        ]}
      />
      <View style={styles.blurView} />
      <View style={styles.bottomButtonsContainer}></View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  blurView: {
    flex: 1,
    width: "100%",
    backgroundColor: "rgba(0, 0, 0, .9)",
  },
  cropper: {
    width: "100%",
    backgroundColor: "red",
  },
  bottomButtonsContainer: {
    position: "absolute",
    bottom: 0,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    width: "100%",
    height: 120,
  },
});

What I am trying to do is get the middle view position when the user moves it, and then recalculate the top and buttom views' height.


问:
Property 'reduce' does not exist on type 'IComponent'
How do I get rid of the error Property 'reduce' does not exist on type 'IComponent' on my method. Initially, components had an any type, so it worked fine. But now that I am strongly typing all my methods ad variables I am seeing issues.

```<code>  static addPlaceholdersOnMultiplePages(components: IComponent[]): IComponent[] {
    return components.map((obj) =>
      obj.reduce(
        (r, a) =>
          r.concat(a, {
            componentIndex: null,
            componentName: ActiveComponentsPartialSelector.Placeholder,
            componentId: `${ActiveComponents.Placeholder}-${UtilService.generateRandomString(8)}`,
            timestamp: new Date().getTime(),
          }),
        [
          {
            componentIndex: null,
            componentName: ActiveComponentsPartialSelector.Placeholder,
            componentId: `${ActiveComponents.Placeholder}-${UtilService.generateRandomString(8)}`,
            timestamp: new Date().getTime(),
          },
        ],
      ),
    );
  }
</code>```

My interface is as follows:

```<code>export interface IComponent
  extends IComponentDetail {
}
</code>```

答:
Try this : </p>

```<code>return components.map((obj) =>

[...Array(components[obj])].reduce( //...
</code>```

Body:
How do I get rid of the error Property 'reduce' does not exist on type 'IComponent' on my method. Initially, components had an any type, so it worked fine. But now that I am strongly typing all my methods ad variables I am seeing issues.

  static addPlaceholdersOnMultiplePages(components: IComponent[]): IComponent[] {
    return components.map((obj) =>
      obj.reduce(
        (r, a) =>
          r.concat(a, {
            componentIndex: null,
            componentName: ActiveComponentsPartialSelector.Placeholder,
            componentId: `${ActiveComponents.Placeholder}-${UtilService.generateRandomString(8)}`,
            timestamp: new Date().getTime(),
          }),
        [
          {
            componentIndex: null,
            componentName: ActiveComponentsPartialSelector.Placeholder,
            componentId: `${ActiveComponents.Placeholder}-${UtilService.generateRandomString(8)}`,
            timestamp: new Date().getTime(),
          },
        ],
      ),
    );
  }

My interface is as follows:

export interface IComponent
  extends IComponentDetail {
}

Body:
Try this :

return components.map((obj) =>

[...Array(components[obj])].reduce( //...


问:
Laravel WHERE AND CLAUSE not working properly
I want to update t_bapr with condition t_prbk and t_item but it doesn't work properly.

The datas something like this:

```<code>{
    "type": "success",
    "message": "Data updated successfully.",
    "data": [
        {
            "t_prbk": "SB1900003",
            "t_item": "         FCLADM31482BZ1700000",
            "t_bapr": "60.0"
        },
        {
            "t_prbk": "SB1900003",
            "t_item": "         FCLAHM43312K64N10100",
            "t_bapr": "60.0"
        },
        {
            "t_prbk": "SB1900003",
            "t_item": "         FCLAHM43312K64N10100",
            "t_bapr": "60.0"
        },
        {
            "t_prbk": "SB1900003",
            "t_item": "         FCLAHM-4331A-K2W -N002-IN",
            "t_bapr": "60.0"
        }
    ]
}
</code>```

and then this is the controller:

```<code>public function priceBookUpdate(Request $request, $t_prbk, $t_item)
    {
        $request->validate([
            't_bapr' => 'integer'
        ]);

        $price_book = PriceBookTtdpcg031::where('t_prbk', $t_prbk)
                    ->where('t_item', $t_item)
                    ->firstOrFail();

        $price_book->t_bapr = $request->t_bapr;
        $price_book->save();

        $data = PriceBookTtdpcg031::select('t_prbk', 't_item', 't_bapr')
                ->where('t_prbk', 'SB1900003')
                ->get();

        return response()->json([
            'type' => 'success',
            'message' => trans('message.update_success'),
            'data' => $data
        ], 201);
    }
</code>```

```<code>Route::post('/sales-price-update-pb/{t_prbk}/{t_item}', 'SalesPriceController@priceBookUpdate');
</code>```

When I click update I want the t_bapr column value to change according to the t_prbk and t_item parameters that I specify. But the parameters used are only t_prbk.

I'm using laravel 6.0 and SQL Server.

答:
Please try in following way.</p>

```<code>$price_book = PriceBookTtdpcg031::where('t_prbk', $t_prbk)
                    ->whereRaw('TRIM(t_item) = ?', [trim($t_item)])
                    ->firstOrFail();
</code>```

Body:
I want to update t_bapr with condition t_prbk and t_item but it doesn't work properly.

The datas something like this:

{
    "type": "success",
    "message": "Data updated successfully.",
    "data": [
        {
            "t_prbk": "SB1900003",
            "t_item": "         FCLADM31482BZ1700000",
            "t_bapr": "60.0"
        },
        {
            "t_prbk": "SB1900003",
            "t_item": "         FCLAHM43312K64N10100",
            "t_bapr": "60.0"
        },
        {
            "t_prbk": "SB1900003",
            "t_item": "         FCLAHM43312K64N10100",
            "t_bapr": "60.0"
        },
        {
            "t_prbk": "SB1900003",
            "t_item": "         FCLAHM-4331A-K2W -N002-IN",
            "t_bapr": "60.0"
        }
    ]
}

and then this is the controller:

public function priceBookUpdate(Request $request, $t_prbk, $t_item)
    {
        $request->validate([
            't_bapr' => 'integer'
        ]);

        $price_book = PriceBookTtdpcg031::where('t_prbk', $t_prbk)
                    ->where('t_item', $t_item)
                    ->firstOrFail();

        $price_book->t_bapr = $request->t_bapr;
        $price_book->save();

        $data = PriceBookTtdpcg031::select('t_prbk', 't_item', 't_bapr')
                ->where('t_prbk', 'SB1900003')
                ->get();

        return response()->json([
            'type' => 'success',
            'message' => trans('message.update_success'),
            'data' => $data
        ], 201);
    }

Route::post('/sales-price-update-pb/{t_prbk}/{t_item}', 'SalesPriceController@priceBookUpdate');

When I click update I want the t_bapr column value to change according to the t_prbk and t_item parameters that I specify. But the parameters used are only t_prbk.

I'm using laravel 6.0 and SQL Server.

Body:
Please try in following way.

$price_book = PriceBookTtdpcg031::where('t_prbk', $t_prbk)
                    ->whereRaw('TRIM(t_item) = ?', [trim($t_item)])
                    ->firstOrFail();


问:
Joining item in list of strings with a string outside of list
Most of the solutions I've come across involve joining items within a list, but my question is about joining an item from a list of strings with another string outside of the list.

In the script below, the desired output is "USD.JPY.SPOT.SPR" as a string, and then the subsequent pairings.

I've tried pairing.join(".SPOT.SPR") and pairing+".SPOT.SPR" but they've not generated the desired output.

```<code>pairings = ["USD.JPY", "USD.HKD", "AUD.USD", "EUR.USD", "GBP.USD", "USD.SGD"]
for pairing in pairings:
    print(pairing.join(".SPOT.SPR"))
</code>```

答:
Just replace your join with string concatenation</p>

```<code>pairings = ["USD.JPY", "USD.HKD", "AUD.USD", "EUR.USD", "GBP.USD", "USD.SGD"]
for pairing in pairings:
    print(pairing+".SPOT.SPR")
</code>```

Body:
Most of the solutions I've come across involve joining items within a list, but my question is about joining an item from a list of strings with another string outside of the list.

In the script below, the desired output is "USD.JPY.SPOT.SPR" as a string, and then the subsequent pairings.

I've tried pairing.join(".SPOT.SPR") and pairing+".SPOT.SPR" but they've not generated the desired output.

pairings = ["USD.JPY", "USD.HKD", "AUD.USD", "EUR.USD", "GBP.USD", "USD.SGD"]
for pairing in pairings:
    print(pairing.join(".SPOT.SPR"))

Body:
Just replace your join with string concatenation

pairings = ["USD.JPY", "USD.HKD", "AUD.USD", "EUR.USD", "GBP.USD", "USD.SGD"]
for pairing in pairings:
    print(pairing+".SPOT.SPR")


问:
IEnumerable yield return function with excel
I start in C #, as well as in the use of Interop.

My goal was to create a windows application that can return the value of the Excel.

My problem is that when it came to making a loop, I ended up with only the first value because the "return" closed the loop.

What i did To try to solve this I used "IEnumerable" on my function while keeping the type "string".

return of function SDExpFormsApp1.Excel+d__6

i dont understand why the return is the the name of the class following by "d__6"

I tried to find something interesting here :
https://learn.microsoft.com/fr-fr/dotnet/api/system.collections.generic.ienumerator-1?view=netcore-3.1

My event fucntion

```<code>private void button1_Click(object sender, EventArgs e)
    {
        openFileDialog1.ShowDialog();
        string filename = openFileDialog1.FileName;
        int sheet = int.Parse(textBox1.Text);
        Excel excel = new Excel(filename, sheet);
        string SuperClass = excel.ReadCell(1, 1);
        string ClassName = excel.ReadCell(2, 1);
        string ClassLabel = excel.ReadCell(3, 1);
        string AttrName = excel.ReadCell2(8, 1).ToString();
        richTextBox1.Text =  "" + AttrName;

    }
</code>```

My function to read the excel

```<code>public IEnumerable<string> ReadCell2(int i, int j)
    {
        try
        {

            while (ws.Cells[i, j].Value2 != null)
            {
                Console.WriteLine(ws.Cells[i, j].Value2);
                yield return ws.Cells[i, j].Value2;
                i++;
            }
        }
        finally
        {

        }
        yield return "nothing";
    }
</code>```

答:
ToString is not usually overloaded for collection/enumerables and returns type name by default and will not enumerate underlying IEnumerable, so you need to use string.Join:

```<code>string AttrName = string.Join("", excel.ReadCell2(8, 1));
</code>```

As for why ToString returns SDExpFormsApp1.Excel+d__6 in this particular case - it is because yield return is actually a syntactic sugar and compiler will generate IEnumerable<T> implementation for you which will have containing type name as a part of it's own. You can read more about it in answers to this question for example.

Body:
I start in C #, as well as in the use of Interop.

My goal was to create a windows application that can return the value of the Excel.

My problem is that when it came to making a loop, I ended up with only the first value because the "return" closed the loop.

What i did To try to solve this I used "IEnumerable" on my function while keeping the type "string".

return of function SDExpFormsApp1.Excel+d__6

i dont understand why the return is the the name of the class following by "d__6"

I tried to find something interesting here :
https://learn.microsoft.com/fr-fr/dotnet/api/system.collections.generic.ienumerator-1?view=netcore-3.1

My event fucntion

private void button1_Click(object sender, EventArgs e)
    {
        openFileDialog1.ShowDialog();
        string filename = openFileDialog1.FileName;
        int sheet = int.Parse(textBox1.Text);
        Excel excel = new Excel(filename, sheet);
        string SuperClass = excel.ReadCell(1, 1);
        string ClassName = excel.ReadCell(2, 1);
        string ClassLabel = excel.ReadCell(3, 1);
        string AttrName = excel.ReadCell2(8, 1).ToString();
        richTextBox1.Text =  "" + AttrName;

    }

My function to read the excel

public IEnumerable<string> ReadCell2(int i, int j)
    {
        try
        {

            while (ws.Cells[i, j].Value2 != null)
            {
                Console.WriteLine(ws.Cells[i, j].Value2);
                yield return ws.Cells[i, j].Value2;
                i++;
            }
        }
        finally
        {

        }
        yield return "nothing";
    }

Body:
ToString is not usually overloaded for collection/enumerables and returns type name by default and will not enumerate underlying IEnumerable, so you need to use string.Join:

string AttrName = string.Join("", excel.ReadCell2(8, 1));

As for why ToString returns SDExpFormsApp1.Excel+d__6 in this particular case - it is because yield return is actually a syntactic sugar and compiler will generate IEnumerable<T> implementation for you which will have containing type name as a part of it's own. You can read more about it in answers to this question for example.


问:
Problem with Java function using tree recursion
I'm having a problem in translating code from Racket to Java.

I wrote a procedure, in Racket, that resolves a 3D version of the "Streets of Manhattan" problem.

The problem is that, in Racket, the creation of a tree type recursion to resolve the problem, is extremely easy, while, in Java, I'm having some problems.
I learned that I should use Nodes for tree recursion in Java, but I have no idea of how they work.
Any hints?

Here is the original Racket code that I need to translate in Java:

```<code>(define (manhattan-3d i j k)
    (cond
      [(and (= i 0) (= j 0)) 1]
      [(and (= i 0) (= k 0)) 1]
      [(and (= j 0) (= k 0)) 1]
      [(or (= i -1) (= j -1) (= k -1)) 0]
      [(or (and (> i 0) (> j 0)) (and (> i 0) (> k 0)) (and (> j 0) (> k 0))) (+ (manhattan-3d (- i 1) j k) (manhattan-3d i (- j 1) k) (manhattan-3d i j (- k 1)))]
     )
  )
</code>```

As you can see, in Racket it's a pretty easy and short procedure, but I have no idea of how to resolve it in Java.

Any kind of help is appreciated!

答:
I don't see any tree in this code.

While I don't know racket, the code seems understandable enough.

It looks like all you need are several conditions:

```<code>public static int manhattan3d (int i, int j, int k)
{
    if (i == 0 && j == 0)
        return 1;
    else if (i == 0 && k == 0)
        return 1;
    else if (j == 0 && k == 0)
        return 1;
    else if (i == -1 || j == -1 || k == -1)
        return 0;
    else
        return manhattan3d (i - 1, j, k) + manhattan3d (i, j - 1, k) + manhattan3d (i, j k - 1);
}
</code>```

Body:
I'm having a problem in translating code from Racket to Java.

I wrote a procedure, in Racket, that resolves a 3D version of the "Streets of Manhattan" problem.

The problem is that, in Racket, the creation of a tree type recursion to resolve the problem, is extremely easy, while, in Java, I'm having some problems.
I learned that I should use Nodes for tree recursion in Java, but I have no idea of how they work.
Any hints?

Here is the original Racket code that I need to translate in Java:

(define (manhattan-3d i j k)
    (cond
      [(and (= i 0) (= j 0)) 1]
      [(and (= i 0) (= k 0)) 1]
      [(and (= j 0) (= k 0)) 1]
      [(or (= i -1) (= j -1) (= k -1)) 0]
      [(or (and (> i 0) (> j 0)) (and (> i 0) (> k 0)) (and (> j 0) (> k 0))) (+ (manhattan-3d (- i 1) j k) (manhattan-3d i (- j 1) k) (manhattan-3d i j (- k 1)))]
     )
  )

As you can see, in Racket it's a pretty easy and short procedure, but I have no idea of how to resolve it in Java.

Any kind of help is appreciated!

Body:
I don't see any tree in this code.

While I don't know racket, the code seems understandable enough.

It looks like all you need are several conditions:

public static int manhattan3d (int i, int j, int k)
{
    if (i == 0 && j == 0)
        return 1;
    else if (i == 0 && k == 0)
        return 1;
    else if (j == 0 && k == 0)
        return 1;
    else if (i == -1 || j == -1 || k == -1)
        return 0;
    else
        return manhattan3d (i - 1, j, k) + manhattan3d (i, j - 1, k) + manhattan3d (i, j k - 1);
}


问:
BigQuery SQL - Combine multiple rows from 1 column that match rows from another table?
I'm new to Big Query and SQL in general, having really on spent a few days with it so far.
I've spent quite a few hours on my current goal and can't seem to find a way to achieve my objective...

I think I've got the Concat right, but am getting duplicated that I can't get rid off as there's one row for each SPECID.

Also not sure once I get rid of them, how I join in the third table without more duplicates?

DATA:

```<code>t1
SUMID   Reference   Type    Size
1001    234         Round   120
1002    234         Square  60

t2
DETID   SUMID   SPECID  Value
2001    1001    1       TRUE
2002    1001    2       TRUE
2003    1001    3       FALSE
2004    1001    4       TRUE
2005    1001    5       FALSE
2006    1001    6       TRUE
2007    1002    1       FALSE
2008    1002    2       TRUE
2009    1002    3       FALSE
2010    1002    4       TRUE
2011    1002    5       TRUE
2012    1002    6       TRUE

t3
SPECID  Description
1       Blue
2       Red
3       Green
4       Orange
5       Yellow
6       Purple
</code>```

OUTPUT

```<code>t1.Reference    t1.Type  t1.Size  t3.Description
234             Round     120     Blue, Red, Orange, Purple
234             Square     60     Red, Orange, Yellow, Purple
</code>```

I've made it as far as the following, but for the life of me, I can't get my head around it.

```<code>#standardSQL
SELECT
t1.SUMID, t1.Reference, t1.Type, t1.Size, t2.Description

FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.T2_ID = t2.T2_ID

LEFT JOIN (
SELECT *
FROM (
select SUMID, Value,
  CONCAT(
    STRING_AGG(CAST(SPECID AS STRING), ', ') OVER(PARTITION BY SUMID, Value)
        ) SPEC_IDs

from Table2
)) t2 ON t1.SUMID = t2.SUMID

WHERE t2.Value = TRUE
</code>```

If anyone could break this down for me I'd be really appreciative?
I'm hoping once I see how it works it'll just click.

答:
If I understand correctly, this is some JOINs with aggregation:

```<code>SELECT t1.Reference, t1.Type, t1.Size,
       STRING_AGG(t3.Description, ', ')
FROM Table1 t1 LEFT JOIN
     Table2 t2
     ON t2.T2_ID = t1.T2_ID AND
        t2.Value LEFT JOIN
     Table3 t3
     ON t3.SPECID = t2.SPECID
GROUP BY t1.Reference, t1.Type, t1.Size;
</code>```

Body:
I'm new to Big Query and SQL in general, having really on spent a few days with it so far.
I've spent quite a few hours on my current goal and can't seem to find a way to achieve my objective...

I think I've got the Concat right, but am getting duplicated that I can't get rid off as there's one row for each SPECID.

Also not sure once I get rid of them, how I join in the third table without more duplicates?

DATA:

t1
SUMID   Reference   Type    Size
1001    234         Round   120
1002    234         Square  60

t2
DETID   SUMID   SPECID  Value
2001    1001    1       TRUE
2002    1001    2       TRUE
2003    1001    3       FALSE
2004    1001    4       TRUE
2005    1001    5       FALSE
2006    1001    6       TRUE
2007    1002    1       FALSE
2008    1002    2       TRUE
2009    1002    3       FALSE
2010    1002    4       TRUE
2011    1002    5       TRUE
2012    1002    6       TRUE

t3
SPECID  Description
1       Blue
2       Red
3       Green
4       Orange
5       Yellow
6       Purple

OUTPUT

t1.Reference    t1.Type  t1.Size  t3.Description
234             Round     120     Blue, Red, Orange, Purple
234             Square     60     Red, Orange, Yellow, Purple

I've made it as far as the following, but for the life of me, I can't get my head around it.

#standardSQL
SELECT
t1.SUMID, t1.Reference, t1.Type, t1.Size, t2.Description

FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.T2_ID = t2.T2_ID

LEFT JOIN (
SELECT *
FROM (
select SUMID, Value,
  CONCAT(
    STRING_AGG(CAST(SPECID AS STRING), ', ') OVER(PARTITION BY SUMID, Value)
        ) SPEC_IDs

from Table2
)) t2 ON t1.SUMID = t2.SUMID

WHERE t2.Value = TRUE

If anyone could break this down for me I'd be really appreciative?
I'm hoping once I see how it works it'll just click.

Body:
If I understand correctly, this is some JOINs with aggregation:

SELECT t1.Reference, t1.Type, t1.Size,
       STRING_AGG(t3.Description, ', ')
FROM Table1 t1 LEFT JOIN
     Table2 t2
     ON t2.T2_ID = t1.T2_ID AND
        t2.Value LEFT JOIN
     Table3 t3
     ON t3.SPECID = t2.SPECID
GROUP BY t1.Reference, t1.Type, t1.Size;


问:
How to insert a string to a text field programatically in JavaScript
I would like to add a string of text to a text field using JavaScript but I don't want to use the onClick or onLoad events to do so.

I simply want the JavaScript to be executed as soon as the browser reads it and the JavaScript will be within the body of the html.

The text field is something like:

```<code><form action="" method="post" name="formname" id="user-registration-form">
    <input type="text" name="edit-form" id="edit-form" />
</form>
</code>```

I have tried something like this but it doesn't work:

```<code><script type="text/javascript"> edit-form.value="the new value"; </script>
</code>```

How can I do this?

答:
Try </p>

```<code>document.getElementById("edit-mail").value="he new value"
</code>```

Body:
I would like to add a string of text to a text field using JavaScript but I don't want to use the onClick or onLoad events to do so.

I simply want the JavaScript to be executed as soon as the browser reads it and the JavaScript will be within the body of the html.

The text field is something like:

<form action="" method="post" name="formname" id="user-registration-form">
    <input type="text" name="edit-form" id="edit-form" />
</form>

I have tried something like this but it doesn't work:

How can I do this?

Body:
Try

document.getElementById("edit-mail").value="he new value"


问:
Vue.js with webpack does not serve compressed GZIP .js files
My Server does not serve GZIPd JavaScript files to the client.

I have a Simple Vue.js application, hosted on Heroku. When I build the site via "npm run build" in my console, it populates the /dist/js directory with 4 files for each JavaScript file, as I would expect it to.

So for example:

```<code>chunk-vendors.e26db277.js
chunk-vendors.e26db277.js.gz
chunk-vendors.e26db277.js.map
chunk-vendors.e26db277.js.map.gz
</code>```

To enable the compression, I installed webpack using the following command:

```<code>    npm install --save-dev compression-webpack-plugin
</code>```

Then I set my vue.config.js to the following:

```<code>    const CompressionPlugin = require('compression-webpack-plugin');

    module.exports = {
      chainWebpack(config) {
        config.plugins.delete('prefetch');

        config.plugin('CompressionPlugin').use(CompressionPlugin);
      }
    };
</code>```

Basically I followed this  tutorial:
https://medium.com/@aetherus.zhou/vue-cli-3-performance-optimization-55316dcd491c

When I check the HTTP request in the browser, it says it accepts gzip:

```<code>Accept-Encoding: gzip, deflate, br
</code>```

The point where I get stuck is, making the server actually deliver the .gz files.

In the tutorial it says "The server block of such a static website looks like this:

```<code>    server {
      listen 80;
      server_name www.example.io;
      root /path/to/the/directory;
      index index.html;
      gzip_static on;

      location /index.html {
        etag on;
      }
      location / {
        etag off;
        add_header Cache-Control max-age=315360000, immutable;
      }
    }
</code>```

But where do I find this block?

This is my server.js:

```<code>const express = require('express')
const serveStatic = require('serve-static')
const path = require('path')

const app = express()

//here we are configuring dist to serve app files
app.use('/', serveStatic(path.join(__dirname, '/dist')))

// this * route is to serve project on different page routes except root `/`
app.get(/.*/, function (req, res) {
  res.sendFile(path.join(__dirname, '/dist/index.html'))
})

const port = process.env.PORT || 8080;
app.listen(port);
</code>```

答:
The server block is exemplary for NGINX.

When using express, a Node.js compression middleware must be installed.

For Example:

```<code>$ npm install compression
</code>```

The Server js must be adjusted as follows:

```<code>const compression = require('compression') // <-- import this library
const express = require('express')
const serveStatic = require('serve-static')
const path = require('path')

const app = express()

// use compression
app.use(compression()) // <-- use the library
[...]
</code>```

Body:
My Server does not serve GZIPd JavaScript files to the client.

I have a Simple Vue.js application, hosted on Heroku. When I build the site via "npm run build" in my console, it populates the /dist/js directory with 4 files for each JavaScript file, as I would expect it to.

So for example:

chunk-vendors.e26db277.js
chunk-vendors.e26db277.js.gz
chunk-vendors.e26db277.js.map
chunk-vendors.e26db277.js.map.gz

To enable the compression, I installed webpack using the following command:

    npm install --save-dev compression-webpack-plugin

Then I set my vue.config.js to the following:

    const CompressionPlugin = require('compression-webpack-plugin');

    module.exports = {
      chainWebpack(config) {
        config.plugins.delete('prefetch');

        config.plugin('CompressionPlugin').use(CompressionPlugin);
      }
    };

Basically I followed this  tutorial:
https://medium.com/@aetherus.zhou/vue-cli-3-performance-optimization-55316dcd491c

When I check the HTTP request in the browser, it says it accepts gzip:

Accept-Encoding: gzip, deflate, br

The point where I get stuck is, making the server actually deliver the .gz files.

In the tutorial it says "The server block of such a static website looks like this:

    server {
      listen 80;
      server_name www.example.io;
      root /path/to/the/directory;
      index index.html;
      gzip_static on;

      location /index.html {
        etag on;
      }
      location / {
        etag off;
        add_header Cache-Control max-age=315360000, immutable;
      }
    }

But where do I find this block?

This is my server.js:

const express = require('express')
const serveStatic = require('serve-static')
const path = require('path')

const app = express()

//here we are configuring dist to serve app files
app.use('/', serveStatic(path.join(__dirname, '/dist')))

// this * route is to serve project on different page routes except root `/`
app.get(/.*/, function (req, res) {
  res.sendFile(path.join(__dirname, '/dist/index.html'))
})

const port = process.env.PORT || 8080;
app.listen(port);

Body:
The server block is exemplary for NGINX.

When using express, a Node.js compression middleware must be installed.

For Example:

$ npm install compression

The Server js must be adjusted as follows:

const compression = require('compression') // <-- import this library
const express = require('express')
const serveStatic = require('serve-static')
const path = require('path')

const app = express()

// use compression
app.use(compression()) // <-- use the library
[...]


问:
Keyboard "done" button pressed event for UIWebView and WKWebView
There are resources for this when using UITextView. How do I register for the Done key button press event? The keyboard shows up when the user focuses a form inside the webview.

答:
@Ducky
 answers is for UIWebView

here is a solution for WkWebview

extend ViewController as WKNavigationDelegate

```<code> webView.navigationDelegate = self
</code>```

implement and override function
get your button id and write on  document.getElementById
this method called on page load finish

```<code>func webView(_ webView: WKWebView,didFinish navigation: WKNavigation!) {
    print("loaded")

                let doneJS = """
    document.getElementById('m_ara_input').addEventListener('focusout', function () {
    var frame = document.createElement('iframe');
    frame.src = 'doneEditing://';
    document.body.appendChild(frame);
    setTimeout(function () { document.body.removeChild(frame); }, 0);
    }, false);
    """

                webView.evaluateJavaScript(doneJS, completionHandler: nil)

}
</code>```

override below method

```<code>   func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

        guard let url = navigationAction.request.url else {return}

        if (url.scheme == "doneediting") {

             executeSubmit()

         }

        decisionHandler(.allow)
    }
</code>```

write this function

```<code>    func executeSubmit(){

        let js = """
var a = document.getElementsByClassName("btn btn-default pull-left");
a.ara_buton.click();
"""
        webView.evaluateJavaScript(js, completionHandler: nil)

    }
</code>```

in javascript  ara_buton  is the attribute of "name" of button

Body:
@Ducky
 answers is for UIWebView

here is a solution for WkWebview

extend ViewController as WKNavigationDelegate

 webView.navigationDelegate = self

implement and override function
get your button id and write on  document.getElementById
this method called on page load finish

func webView(_ webView: WKWebView,didFinish navigation: WKNavigation!) {
    print("loaded")

                let doneJS = """
    document.getElementById('m_ara_input').addEventListener('focusout', function () {
    var frame = document.createElement('iframe');
    frame.src = 'doneEditing://';
    document.body.appendChild(frame);
    setTimeout(function () { document.body.removeChild(frame); }, 0);
    }, false);
    """

                webView.evaluateJavaScript(doneJS, completionHandler: nil)

}

override below method

   func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

        guard let url = navigationAction.request.url else {return}

        if (url.scheme == "doneediting") {

             executeSubmit()

         }

        decisionHandler(.allow)
    }

write this function

    func executeSubmit(){

        let js = """
var a = document.getElementsByClassName("btn btn-default pull-left");
a.ara_buton.click();
"""
        webView.evaluateJavaScript(js, completionHandler: nil)

    }

in javascript  ara_buton  is the attribute of "name" of button


问:
C# binary data from port convert to hex string
I found a source code and changed it a little bit so i can retrieve data from a receiver that is on com6. The data i am receiving is binary. Now I want to convert it to a hex string. If it's a hex string we can cut parts of the string and decode them seperately. how can i do this?

The following is the code:

```<code>using System;
using System.IO.Ports;
using System.Threading;
public class PortChat
{
    static bool _continue;
    static SerialPort _serialPort;
    public static void Main()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);

        // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();

        // Allow the user to set the appropriate properties.
        _serialPort.PortName = SetPortName(_serialPort.PortName);
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
        _serialPort.Parity = SetPortParity(_serialPort.Parity);
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

        // Set the read/write timeouts
        _serialPort.ReadTimeout = 1000;
        _serialPort.WriteTimeout = 1000;

        _serialPort.Open();
        _continue = true;
        readThread.Start();

        Console.Write("Name: ");
        name = Console.ReadLine();

        Console.WriteLine("Type QUIT to exit");

        while (_continue)
        {
            message = Console.ReadLine();

            if (stringComparer.Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
                _serialPort.WriteLine(
                    String.Format("<{0}>: {1}", name, message));
            }
        }

        readThread.Join();
        _serialPort.Close();
    }

    public static void Read()
    {
        while (_continue)
        {

            try
            {

                string message = _serialPort.ReadLine();
                Console.WriteLine(message);

            catch (TimeoutException) { }
        }
    }

    public static string SetPortName(string defaultPortName)
    {
        string portName;

            portName = "COM6";

        return portName;
    }

    public static int SetPortBaudRate(int defaultPortBaudRate)
    {
        string baudRate;

        baudRate = "9600";

        return int.Parse(baudRate);
    }

    public static Parity SetPortParity(Parity defaultPortParity)
    {
        string parity;

        parity = "None";

        return (Parity)Enum.Parse(typeof(Parity), parity);
    }

    public static int SetPortDataBits(int defaultPortDataBits)
    {
        string dataBits;

        dataBits = "8";

        return int.Parse(dataBits);
    }

    public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
    {
        string stopBits;

        stopBits = "One";

        return (StopBits)Enum.Parse(typeof(StopBits), stopBits);
    }

    public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
    {
        string handshake;

        handshake = "None";

        return (Handshake)Enum.Parse(typeof(Handshake), handshake);
    }
}
</code>```

答:
Try this

```<code>    string Data = "123";
    string hex = "";
    foreach (char c in Data)
    {
        hex += String.Format("{0:x2}", (byte)c);
    }
</code>```

hex contains string as you wanted

Body:
I found a source code and changed it a little bit so i can retrieve data from a receiver that is on com6. The data i am receiving is binary. Now I want to convert it to a hex string. If it's a hex string we can cut parts of the string and decode them seperately. how can i do this?

The following is the code:

using System;
using System.IO.Ports;
using System.Threading;
public class PortChat
{
    static bool _continue;
    static SerialPort _serialPort;
    public static void Main()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);

        // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();

        // Allow the user to set the appropriate properties.
        _serialPort.PortName = SetPortName(_serialPort.PortName);
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
        _serialPort.Parity = SetPortParity(_serialPort.Parity);
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

        // Set the read/write timeouts
        _serialPort.ReadTimeout = 1000;
        _serialPort.WriteTimeout = 1000;

        _serialPort.Open();
        _continue = true;
        readThread.Start();

        Console.Write("Name: ");
        name = Console.ReadLine();

        Console.WriteLine("Type QUIT to exit");

        while (_continue)
        {
            message = Console.ReadLine();

            if (stringComparer.Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
                _serialPort.WriteLine(
                    String.Format("<{0}>: {1}", name, message));
            }
        }

        readThread.Join();
        _serialPort.Close();
    }

    public static void Read()
    {
        while (_continue)
        {

            try
            {

                string message = _serialPort.ReadLine();
                Console.WriteLine(message);

            catch (TimeoutException) { }
        }
    }

    public static string SetPortName(string defaultPortName)
    {
        string portName;

            portName = "COM6";

        return portName;
    }

    public static int SetPortBaudRate(int defaultPortBaudRate)
    {
        string baudRate;

        baudRate = "9600";

        return int.Parse(baudRate);
    }

    public static Parity SetPortParity(Parity defaultPortParity)
    {
        string parity;

        parity = "None";

        return (Parity)Enum.Parse(typeof(Parity), parity);
    }

    public static int SetPortDataBits(int defaultPortDataBits)
    {
        string dataBits;

        dataBits = "8";

        return int.Parse(dataBits);
    }

    public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
    {
        string stopBits;

        stopBits = "One";

        return (StopBits)Enum.Parse(typeof(StopBits), stopBits);
    }

    public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
    {
        string handshake;

        handshake = "None";

        return (Handshake)Enum.Parse(typeof(Handshake), handshake);
    }
}

Body:
Try this

    string Data = "123";
    string hex = "";
    foreach (char c in Data)
    {
        hex += String.Format("{0:x2}", (byte)c);
    }

hex contains string as you wanted


问:
Pushing to Github Repo from Eclipse, how to hide sensitive data, but make repo public?
I am wondering how I can push to my Github repo (which I need to be public so I can showcase to employers), without showing sensitive info. I am using Eclipse/Java.

I have made a project which runs tests with Selenium webdriver in Chrome, I don't want people to be able to see the login information in my code, for obvious reasons.

The stuff online about Git/Github is a bit of a minefield for a beginner like me and I am finding it hard to understand.

Thanks in advance,

答:
Split all (hardcoded) configuration data into a separate file, for example Config.java or application.xml or some format you like.

Create a .gitignore file in your project directory, listing all the files / folders that should be ignored, for example the configuration file mentioned above, and some other generated file, compile output, jar file, etc.

If you have accidently added some sensitive data that exists in your Git history, use git filter-branch to remove those file from history.


问:
Add cookie for site that redirects in Chrome DevTools?
I need to set login cookies manually in Chrome when testing our site in certain testing environments because the normal login process doesn't work there.

I can get the cookies manually using Postman.

Normally I'd use F12 -> Application -> Cookies but our site immediately redirects you to a our centralized login page (which is on a different domain).

Any idea how to add a cookie to a domain in Chrome if I can't open the domain for long enough?

答: I found an extension that allows me to do it, called EditThisCookie. I installed it in a separate Chrome account (just for safety) and then I could add a cookie to a site even when it is not currently opened, thus avoiding the redirect:


问:
Bash gotcha: cat FILE | while read A ; do ... exit .. done
I had a long pause in writing bash script, and I got trapped again:

```<code>cat FILE | while read SPID ; do
        if ls $ODIR/*$SPID*.csv > /dev/null 2>&1 ; then
                echo Error: some files exist in the directory $ODIR:
                ls -la $ODIR/*$SPID*.csv
                exit
        fi
done
</code>```

I happily assumed the exit will exit the whole bash script, as it should, but as it is in pipe, it probably exits just the sub-process dispatched to run while part.

I already forgot how to easily workaround this. Please remind me! :-)

**EDIT: ** now I have changed the code (for some other reason) to use variable instead, and I am looking for workaround for this:

```<code>EXIST="no"
cat FILE | while read SPID ; do
        if ls $ODIR/*$SPID*.csv > /dev/null 2>&1 ; then
                echo Error: some files exist in the directory $ODIR:
                ls -la $ODIR/*$SPID*.csv
                EXIST="yes"
        fi
done
</code>```

but I guess this is the same case, I need the inside of the loop to be run with the same shell as runs the whole script.

答:
From bash manual pipelines:

Each command in a pipeline is executed in its own subshell [...]

The sides of | are run in a subshell. Environment changes are not visible from the subshell in the parent shell.

```<code>( exit; )                   # exits the subshell only
: | exit                    # exits the subshell only
a=1; ( a=5; ); echo $a      # prints 1, a=5 is executed in a subshell
a=1; : | a=5;  echo $a      # prints 1, a=5 is executed in a subshell
</code>```

Pipe the file to stdin to execute the while loop in parent shell context.

```<code> while IFS= read -r spid; do
    ...
 done <file
</code>```

Note that UPPER CASE variables are by convention reserved for environment exported variables, like IFS, LINES, COLUMNS, PWD, UID etc. Prefer to use lower case variables.

Recommended reads: I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read? and how to read a file line by line.

Body:
I had a long pause in writing bash script, and I got trapped again:

cat FILE | while read SPID ; do
        if ls $ODIR/*$SPID*.csv > /dev/null 2>&1 ; then
                echo Error: some files exist in the directory $ODIR:
                ls -la $ODIR/*$SPID*.csv
                exit
        fi
done

I happily assumed the exit will exit the whole bash script, as it should, but as it is in pipe, it probably exits just the sub-process dispatched to run while part.

I already forgot how to easily workaround this. Please remind me! :-)

**EDIT: ** now I have changed the code (for some other reason) to use variable instead, and I am looking for workaround for this:

EXIST="no"
cat FILE | while read SPID ; do
        if ls $ODIR/*$SPID*.csv > /dev/null 2>&1 ; then
                echo Error: some files exist in the directory $ODIR:
                ls -la $ODIR/*$SPID*.csv
                EXIST="yes"
        fi
done

but I guess this is the same case, I need the inside of the loop to be run with the same shell as runs the whole script.

Body:
From bash manual pipelines:

Each command in a pipeline is executed in its own subshell [...]

The sides of | are run in a subshell. Environment changes are not visible from the subshell in the parent shell.

( exit; )                   # exits the subshell only
: | exit                    # exits the subshell only
a=1; ( a=5; ); echo $a      # prints 1, a=5 is executed in a subshell
a=1; : | a=5;  echo $a      # prints 1, a=5 is executed in a subshell

Pipe the file to stdin to execute the while loop in parent shell context.

 while IFS= read -r spid; do
    ...
 done <file

Note that UPPER CASE variables are by convention reserved for environment exported variables, like IFS, LINES, COLUMNS, PWD, UID etc. Prefer to use lower case variables.

Recommended reads: I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read? and how to read a file line by line.


问:
escaping string - php in html element
i know this is really obvious but i just don't know what I'm missing. </p>

```<code>$option[] = "<option value='user' selected=' " . ($row[5]=='admin') ? echo 'selected' : null. "'>user </option>";`
</code>```

<p>thanks </p>

答:
Try this:

```<code>$option[] = '<option value="user" . ($row[5]=='admin' ? 'selected' : '') . '>user </option>';`
</code>```

Three differences from your code:

I reversed your use of quotes...easier to wrap a PHP string that contains HTML in single quotes (since HTML uses double quotes).

I modified the parenthesis around your ternary operator...it was only wrapped around the condition, and not the true/false return values.

In your "true" return value in the ternary operation, you were calling echo, which isn't necessary in a concatenation operation.

Title: escaping string - php in html element

Body:
i know this is really obvious but i just don't know what I'm missing.

$option[] = "<option value='user' selected=' " . ($row[5]=='admin') ? echo 'selected' : null. "'>user </option>";`

thanks

Body:
Try this:

$option[] = '<option value="user" . ($row[5]=='admin' ? 'selected' : '') . '>user </option>';`

Three differences from your code:

I reversed your use of quotes...easier to wrap a PHP string that contains HTML in single quotes (since HTML uses double quotes).

I modified the parenthesis around your ternary operator...it was only wrapped around the condition, and not the true/false return values.

In your "true" return value in the ternary operation, you were calling echo, which isn't necessary in a concatenation operation.


问:
Microsoft Teams bot - debug link unfurling
I'm trying to implement pretty simple teams bot but constantly facing an issues with unpredictable behavior. E.g. documentation clearly says that Teams applies Adaptive card as link unfurling response but when I'm sending pretty simple response like:

```<code>var card = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0));
card.Body.Add(new AdaptiveTextBlock { Text = "Title", Size = AdaptiveTextSize.ExtraLarge });
var attachment = new MessagingExtensionAttachment { ContentType = AdaptiveCard.ContentType, Content = card };
var result = new MessagingExtensionResult(AttachmentLayoutTypes.List, "result", new[] { attachment });
return new MessagingExtensionResponse(result);
</code>```

Teams doesn't render anything or follback to the default behavior.
So the question is - are there any way to debug why it doesn't work?

答:
Had the same issue, the problem is this is not documented at all. You'll need to send a hero card (maybe something else works as well?) as preview and the adaptive card as full card:

```<code>return {
        composeExtension: {
            type: 'result',
            attachmentLayout: 'list',
            attachments: [{
                preview: CardFactory.heroCard("title", "description")
                ...CardFactory.adaptiveCard(card)
            }]
        }
    };
</code>```

This will display an "expandable" hero card which resolves to the adaptive card.

Body:
I'm trying to implement pretty simple teams bot but constantly facing an issues with unpredictable behavior. E.g. documentation clearly says that Teams applies Adaptive card as link unfurling response but when I'm sending pretty simple response like:

var card = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0));
card.Body.Add(new AdaptiveTextBlock { Text = "Title", Size = AdaptiveTextSize.ExtraLarge });
var attachment = new MessagingExtensionAttachment { ContentType = AdaptiveCard.ContentType, Content = card };
var result = new MessagingExtensionResult(AttachmentLayoutTypes.List, "result", new[] { attachment });
return new MessagingExtensionResponse(result);

Teams doesn't render anything or follback to the default behavior.
So the question is - are there any way to debug why it doesn't work?

Body:
Had the same issue, the problem is this is not documented at all. You'll need to send a hero card (maybe something else works as well?) as preview and the adaptive card as full card:

return {
        composeExtension: {
            type: 'result',
            attachmentLayout: 'list',
            attachments: [{
                preview: CardFactory.heroCard("title", "description")
                ...CardFactory.adaptiveCard(card)
            }]
        }
    };

This will display an "expandable" hero card which resolves to the adaptive card.


问:
Bootstrap 4 - Flex wrap after 5th item
I'm trying to achieve quite a specific layout using the newest Bootstrap 4. How it should work/look:
- first element/child should be a kind of 'hero', visible on 100% of container width
- all other items should be as thumbs
- the 'thumbs' row should include 4 items, next one should break/wrap to another row

So in theory new row should appear after 5th element (hero + 4 thumbs), but I have no clue how to approach that. My current code looks as follows:

HTML

```<code><section id="videos">
  <div class="row gallery">
    <div class="col-lg-12">
      <dl class="d-flex justify-content-between flex-wrap thumbs">
        <dt class="p-2 main-frame">
          <a href="#" title="test it">
            <img src="https://picsum.photos/seed/picsum/1920/1080" class="img-fluid" />
          </a>
        </dt>
        <dt class="p-2">
          <a href="#" title="test it">
            <img src="https://picsum.photos/seed/111/1920/1080" class="img-fluid" />
          </a>
        </dt>
        <dt class="p-2">
          <a href="#" title="test it">
            <img src="https://picsum.photos/seed/354/1920/1080" class="img-fluid" />
          </a>
        </dt>
        <dt class="p-2">
          <a href="#" title="test it">
            <img src="https://picsum.photos/1920/1080" class="img-fluid" />
          </a>
        </dt>
        <dt class="p-2">
          <a href="#" title="test it">
            <img src="https://picsum.photos/1920/1080" class="img-fluid" />
          </a>
        </dt>
        <dt class="p-2">
          <a href="#" title="test it">
            <img src="https://picsum.photos/1920/1080" class="img-fluid" />
          </a>
        </dt>
      </dl>
    </div>
  </div>
</section>
</code>```

CSS

```<code>.thumbs dt:not(:first-child) {
  flex: 1;
}

.thumbs dt:nth-child(1) {
  width: 100%;
}
</code>```

Jsfiddle

What I'm doing wrong? Is it doable without additional js?

答:
for every fourth img you can do:

```<code><div class="row">
 <div class="col-12">
  Hero goes here
 </div>
</div>
<div class="row img">
 <div class="col-3">
  img1
 </div>
 <div class="col-3">
  img2
 </div>
 <div class="col-3">
  img3
 </div>
 <div class="col-3">
    img4
 </div>
</div>
</code>```

And then add same structure for the next 4 images.. if 4 images are to be shown per row.. The hero might not be desired to be added for each image row.

Some condition like

if(videoNr%4 == 0) // add image row with the next four

If you must use flex layout. This is a way to solve it, it will wrap to new line every fourth image without the need of any additional CSS:

```<code><div class="d-flex flex-wrap">
  <div class="flex-fill w-25">img1</div>
  <div class="flex-fill w-25">img2</div>
  <div class="flex-fill w-25">img3</div>
  <div class="flex-fill w-25">img4</div>
  <div class="flex-fill w-25">img5</div>
  <div class="flex-fill w-25">img6</div>
  <div class="flex-fill w-25">img7</div>
  <div class="flex-fill w-25">img8</div>
  <div class="flex-fill w-25">img9</div>
</div>
</code>```

Title: Bootstrap 4 - Flex wrap after 5th item

Body:
I'm trying to achieve quite a specific layout using the newest Bootstrap 4. How it should work/look:
- first element/child should be a kind of 'hero', visible on 100% of container width
- all other items should be as thumbs
- the 'thumbs' row should include 4 items, next one should break/wrap to another row

So in theory new row should appear after 5th element (hero + 4 thumbs), but I have no clue how to approach that. My current code looks as follows:

HTML

CSS

.thumbs dt:not(:first-child) {
  flex: 1;
}

.thumbs dt:nth-child(1) {
  width: 100%;
}

Jsfiddle

What I'm doing wrong? Is it doable without additional js?

Body:
for every fourth img you can do:

<div class="row">
 <div class="col-12">
  Hero goes here
 </div>
</div>
<div class="row img">
 <div class="col-3">
  img1
 </div>
 <div class="col-3">
  img2
 </div>
 <div class="col-3">
  img3
 </div>
 <div class="col-3">
    img4
 </div>
</div>

And then add same structure for the next 4 images.. if 4 images are to be shown per row.. The hero might not be desired to be added for each image row.

Some condition like

if(videoNr%4 == 0) // add image row with the next four

If you must use flex layout. This is a way to solve it, it will wrap to new line every fourth image without the need of any additional CSS:

<div class="d-flex flex-wrap">
  <div class="flex-fill w-25">img1</div>
  <div class="flex-fill w-25">img2</div>
  <div class="flex-fill w-25">img3</div>
  <div class="flex-fill w-25">img4</div>
  <div class="flex-fill w-25">img5</div>
  <div class="flex-fill w-25">img6</div>
  <div class="flex-fill w-25">img7</div>
  <div class="flex-fill w-25">img8</div>
  <div class="flex-fill w-25">img9</div>
</div>


答:
You shoul use Nodes in java to create a tree.

A Node class in java is a class who contains at least a name and a list of nodes called childrens.

Here the node 1 has 2 and 3 as its childrens.

The node 2 has 4 and 5 as its children, ...

Each node of a tree is an instance of the class node. To go to a node you have to use a recursive method.

Title: Problem with Java function using tree recursion

Body:
I'm having a problem in translating code from Racket to Java.

I wrote a procedure, in Racket, that resolves a 3D version of the "Streets of Manhattan" problem.

The problem is that, in Racket, the creation of a tree type recursion to resolve the problem, is extremely easy, while, in Java, I'm having some problems.
I learned that I should use Nodes for tree recursion in Java, but I have no idea of how they work.
Any hints?

Here is the original Racket code that I need to translate in Java:

(define (manhattan-3d i j k)
    (cond
      [(and (= i 0) (= j 0)) 1]
      [(and (= i 0) (= k 0)) 1]
      [(and (= j 0) (= k 0)) 1]
      [(or (= i -1) (= j -1) (= k -1)) 0]
      [(or (and (> i 0) (> j 0)) (and (> i 0) (> k 0)) (and (> j 0) (> k 0))) (+ (manhattan-3d (- i 1) j k) (manhattan-3d i (- j 1) k) (manhattan-3d i j (- k 1)))]
     )
  )

As you can see, in Racket it's a pretty easy and short procedure, but I have no idea of how to resolve it in Java.

Any kind of help is appreciated!


问:
Use the pumping lemma to show that the following languages are not regular languages L = {anbm | n = 2m}
Use the pumping lemma to show that the following languages are not regular languages L = {an bm | n = 2m} </p>

答: Choose a string a^2p b^p. The pumping lemma says we can write this as w = uvx such that |uv| <= p, |v| < 0 and for all natural numbers n, u(v^n)x is also a string in the language. Because |uv| <= p, the substring uv of w consists entirely of instances of the symbol a. Pumping up or down by choosing a value for n other than one guarantees that the number of a's in the resulting string will change, while the number of b's stays the same. Since the number of a's is twice the number of b's only when n = 1, this is a contradiction. Therefore, the language cannot be regular.</p>


问:
Is there a way of processing list of number integers entered via terminal without saving them into list?
I am trying to write a similar code in Python, but I am new to it.

int counts[] = { 0, 0, 0, 0, 0 };
for (int i = 0; i < groups; i++) {
    int groups_size;
    scanf(" %d", &groups_size);

    counts[groups_size] += 1;
}
```

<p>Please note that it does not all the save the numbers into memory.</p>

<p>I tried to do this in Python as:</p>

```for group in range(groups):
    num = int(input().strip())
    counts[num] += 1
```

This does not work. When I enter 1 2 3 4 5 into terminal, I get ValueError: invalid literal for int() with base 10: '1 2 3 4 5'.

Is there a way of doing this in Python the same as I did in C?

答:
In python, it will not automatically take one number and then loop for the other. You input() command will read the whole line at once. So, what you can do is read the whole line in a string and then split it into a list as follows -

```<code>str = input()
num = list(map(int,str.split()))
</code>```

Now you have all the input given by user stored in the num variable. You can just iterate over it and complete your process as follows -

```<code>counts = [0]*5       #assuming you want it to be of size 5 as in your question
for inp in num :
    counts[inp] = counts[inp] + 1
</code>```

Hope this helps!

Body:
I am trying to write a similar code in Python, but I am new to it.

int counts[] = { 0, 0, 0, 0, 0 };
for (int i = 0; i < groups; i++) {
    int groups_size;
    scanf(" %d", &groups_size);

    counts[groups_size] += 1;
}

Please note that it does not all the save the numbers into memory.

I tried to do this in Python as:

for group in range(groups):
    num = int(input().strip())
    counts[num] += 1

This does not work. When I enter 1 2 3 4 5 into terminal, I get ValueError: invalid literal for int() with base 10: '1 2 3 4 5'.

Is there a way of doing this in Python the same as I did in C?

Body:
In python, it will not automatically take one number and then loop for the other. You input() command will read the whole line at once. So, what you can do is read the whole line in a string and then split it into a list as follows -

str = input()
num = list(map(int,str.split()))

Now you have all the input given by user stored in the num variable. You can just iterate over it and complete your process as follows -

counts = [0]*5       #assuming you want it to be of size 5 as in your question
for inp in num :
    counts[inp] = counts[inp] + 1

Hope this helps!


问:
Multiple Tables In Android Room Database
I wonder how to have multiple tables and using relations in the android room database??
I need a little bit of explanation or if you have a good tutorial, I will appreciate

Thanks.

答:
You can have multiples table by defining different entity class for each table for example if we have two tables FactCategory and Facts, each FactCategory can have multiple facts.

Fact Category:

```<code>@Entity(tableName = "categories")
data class FactCategory(@PrimaryKey var id: String, var title: String)
</code>```

Facts:

```<code>@Entity(tableName = "facts")
class Fact(
    @field:PrimaryKey val id: String,
    val title: String,
    val description: String?,
    val imageHref: String?,
    val catId: String
)
</code>```

In your database class, add all the required entity classes. You can not link two tables from different database.

Add the entities in your database class

```<code>@Database(entities = [::class, FactCategory::class], version = 1)
</code>```

then in your DAO object, you can join two tables:

```<code>@Query("select f.id, f.title, c.title, f.description from categories c join  facts f on  c.id = f.catId")
</code>```

Body:
You can have multiples table by defining different entity class for each table for example if we have two tables FactCategory and Facts, each FactCategory can have multiple facts.

Fact Category:

@Entity(tableName = "categories")
data class FactCategory(@PrimaryKey var id: String, var title: String)

Facts:

@Entity(tableName = "facts")
class Fact(
    @field:PrimaryKey val id: String,
    val title: String,
    val description: String?,
    val imageHref: String?,
    val catId: String
)

In your database class, add all the required entity classes. You can not link two tables from different database.

Add the entities in your database class

@Database(entities = [::class, FactCategory::class], version = 1)

then in your DAO object, you can join two tables:

@Query("select f.id, f.title, c.title, f.description from categories c join  facts f on  c.id = f.catId")


问:
How can i create and run Jar file from spring batch
I have a spring batch application which contains two job, the application in eclipse work correctly but when i create jar and run it, not working i need execute it using CommandLineJobRunner.

I try create a jar using severeal ways:

I using the maven comand mvn clean install and mvn clean package, in this case if I run the jar using ->

java -jar  org.springframework.batch.core.launch.support.CommandLineJobRunner    the jar always execute all jobs.

in other case if i try it using java -cp i get:

Error: Could not find or load main class org.springframework.batch.core.launch.support.CommandLineJobRunner
Caused by: java.lang.ClassNotFoundException: org.springframework.batch.core.launch.support.CommandLineJobRunner

Using ecilpse to export jar file

In eclipse export -> jar -> runneableJar, in this case:

if i use java -cp i get FileNotFoundException application.properties, but this file is in resources.

if i use java -jar i get no main manifest attribute.

In eclipse export -> jar -> Jar file, in this case:

if i use java -cp i get -> Error: Could not find or load main class org.springframework.batch.core.launch.support.CommandLineJobRunner
Caused by: java.lang.ClassNotFoundException: org.springframework.batch.core.launch.support.CommandLineJobRunner

if i use java -jar i get no main manifest attribute.

I don't know what to try.
thancks and sorry for my english, is not my native languaje

答: it works now, the problem was the plugin, as Mahmoud said, was necessary use the maven plugin but on other hand i had the db2 dependency with scope provided, Maven dependency scope provided is used during build and test the project. They are also required to run, but should not exported, because the dependency will be provided by the runtime, for instance, by servlet container or application server.</p>


问:
Msys2: Maintaining two python installations
I am using Msys2 portable under Win 10.
I have 2 python 3.8 installations. The original question asked if that is so. I am now certain it is, so for the time being I want to deal with their maintenance.

I also posted another related question Msys2: readline in two python installations

I am posting below information on both.

My questions are:

Can they interfere with each other?
If so, what steps/configuration should I deal with? (PYTHONPATH, site-packages, etc.)

Would it be safe removing any one of them, without breaking the other?
Dependencies below seem to me this implies no risk, but I am not certain that is enough information to answer this.

Which would be the best one to keep?
I mean to use numpy, pandas, gcc-toolchain and debugger via Eclipse CDT, and a number of other packages.

PS1:
This is in addition to python2, for which the same questions would apply.

PS2:
It seems strange to me that the available subversions are not exactly the same, even if versions are both 3.8.2.

PS3:
These two pythons are likely upgrades from the main characters of this "play", python 3.8 (3.8.1 before) upgraded to mingw-w64-x86_64-python 3.8.2-2 and python 3.7 upgraded to python 3.8.2-1.

Packages providing python

```<code>$ pacman -Sl | grep "python " | grep "installed"
mingw64 mingw-w64-x86_64-python 3.8.2-2 [installed]
msys python 3.8.2-1 [installed]
</code>```

Additional info on each (dependencies, etc.)

```<code>$ pacman -Qi mingw-w64-x86_64-python
Name            : mingw-w64-x86_64-python
Version         : 3.8.2-2
Description     : A high-level scripting language (mingw-w64)
Architecture    : any
URL             : https://www.python.org/
Licenses        : PSF
Groups          : None
Provides        : mingw-w64-x86_64-python3=3.8.2
Depends On      : mingw-w64-x86_64-gcc-libs  mingw-w64-x86_64-expat  mingw-w64-x86_64-bzip2  mingw-w64-x86_64-libffi  mingw-w64-x86_64-mpdecimal
                  mingw-w64-x86_64-ncurses  mingw-w64-x86_64-openssl  mingw-w64-x86_64-sqlite3  mingw-w64-x86_64-tcl  mingw-w64-x86_64-tk  mingw-w64-x86_64-zlib
                  mingw-w64-x86_64-xz
Optional Deps   : None
Required By     : mingw-w64-x86_64-gdb  mingw-w64-x86_64-glib2  mingw-w64-x86_64-gtest  mingw-w64-x86_64-mono  mingw-w64-x86_64-postgresql
                  mingw-w64-x86_64-python-apipkg  mingw-w64-x86_64-python-appdirs  mingw-w64-x86_64-python-atomicwrites  mingw-w64-x86_64-python-attrs
                  mingw-w64-x86_64-python-cairo  mingw-w64-x86_64-python-colorama  mingw-w64-x86_64-python-contextlib2  mingw-w64-x86_64-python-cycler
                  mingw-w64-x86_64-python-defusedxml  mingw-w64-x86_64-python-imagesize  mingw-w64-x86_64-python-importlib-metadata  mingw-w64-x86_64-python-iniconfig
                  mingw-w64-x86_64-python-jdcal  mingw-w64-x86_64-python-kiwisolver  mingw-w64-x86_64-python-lxml  mingw-w64-x86_64-python-more-itertools
                  mingw-w64-x86_64-python-numpy  mingw-w64-x86_64-python-olefile  mingw-w64-x86_64-python-ordered-set  mingw-w64-x86_64-python-packaging
                  mingw-w64-x86_64-python-pathlib2  mingw-w64-x86_64-python-pillow  mingw-w64-x86_64-python-pluggy  mingw-w64-x86_64-python-py
                  mingw-w64-x86_64-python-pyparsing  mingw-w64-x86_64-python-pytest  mingw-w64-x86_64-python-pytz  mingw-w64-x86_64-python-scandir
                  mingw-w64-x86_64-python-seaborn  mingw-w64-x86_64-python-setuptools  mingw-w64-x86_64-python-sip  mingw-w64-x86_64-python-six
                  mingw-w64-x86_64-python-wcwidth  mingw-w64-x86_64-python-zipp  mingw-w64-x86_64-vapoursynth
Optional For    : mingw-w64-x86_64-vtk
Conflicts With  : mingw-w64-x86_64-python3  mingw-w64-x86_64-python2<2.7.16-7
Replaces        : mingw-w64-x86_64-python3
Installed Size  : 112.87 MiB
Packager        : Alexey Pavlov <alexpux@gmail.com>
Build Date      : Thu, Apr 9, 2020 10:17:39 AM
Install Date    : Wed, Apr 22, 2020 10:04:36 AM
Install Reason  : Explicitly installed
Install Script  : No
Validated By    : Signature

$ pacman -Qi python
Name            : python
Version         : 3.8.2-1
Description     : Next generation of the python high-level scripting language
Architecture    : i686
URL             : https://www.python.org/
Licenses        : custom
Groups          : None
Provides        : python3
Depends On      : libbz2  libexpat  libffi  liblzma  ncurses  libopenssl  libreadline  mpdecimal  libsqlite  zlib
Optional Deps   : None
Required By     : gdb  python3-appdirs  python3-attrs  python3-pip  python3-pyparsing  python3-six  scons
Optional For    : None
Conflicts With  : None
Replaces        : python3
Installed Size  : 47.27 MiB
Packager        : Alexey Pavlov <alexpux@gmail.com>
Build Date      : Thu, Apr 16, 2020 12:31:48 PM
Install Date    : Wed, Apr 22, 2020 10:15:54 AM
Install Reason  : Explicitly installed
Install Script  : No
Validated By    : Signature
</code>```

Packages providing python2

```<code>$ pacman -Sl | grep "python2 " | grep "installed"
mingw64 mingw-w64-x86_64-python2 2.7.18-1 [installed: 2.7.17-2]
msys python2 2.7.18-1 [installed: 2.7.17-1]
</code>```

答:
I use 2 Python different versions in MSYS2 shell (version 2 + 3).

What I do is the following:

Neither is of the Python paths is included in the PATH environment variable, so if something needs Python it fails.

When Python is needed I prepend PATH=<python_path>:$PATH to the command that needs it (e.g. PATH=/D/Prog/Python/WinPython-64bit-2.7.13.1Zero/python-2.7.13.amd64:$PATH make) or if the command supports setting PYTHON in the environment I prepend PYTHON=<python_path>/python.exe before the command. In some cases where Makefile or configure accept a PYTHON variable it may also be possible to append PYTHON=<python_path>/python.exe after the make command.

In case Python wants to load certain modules it may also be necessary to set the PYTHONPATH variable (e.g. PYTHONPATH=<python_path>/Lib/site-packages)

This works well for me and always forces me to choose which Python I use.

Body:
I am using Msys2 portable under Win 10.
I have 2 python 3.8 installations. The original question asked if that is so. I am now certain it is, so for the time being I want to deal with their maintenance.

I also posted another related question Msys2: readline in two python installations

I am posting below information on both.

My questions are:

Can they interfere with each other?
If so, what steps/configuration should I deal with? (PYTHONPATH, site-packages, etc.)

Would it be safe removing any one of them, without breaking the other?
Dependencies below seem to me this implies no risk, but I am not certain that is enough information to answer this.

Which would be the best one to keep?
I mean to use numpy, pandas, gcc-toolchain and debugger via Eclipse CDT, and a number of other packages.

PS1:
This is in addition to python2, for which the same questions would apply.

PS2:
It seems strange to me that the available subversions are not exactly the same, even if versions are both 3.8.2.

PS3:
These two pythons are likely upgrades from the main characters of this "play", python 3.8 (3.8.1 before) upgraded to mingw-w64-x86_64-python 3.8.2-2 and python 3.7 upgraded to python 3.8.2-1.

Packages providing python

$ pacman -Sl | grep "python " | grep "installed"
mingw64 mingw-w64-x86_64-python 3.8.2-2 [installed]
msys python 3.8.2-1 [installed]

Additional info on each (dependencies, etc.)

$ pacman -Qi mingw-w64-x86_64-python
Name            : mingw-w64-x86_64-python
Version         : 3.8.2-2
Description     : A high-level scripting language (mingw-w64)
Architecture    : any
URL             : https://www.python.org/
Licenses        : PSF
Groups          : None
Provides        : mingw-w64-x86_64-python3=3.8.2
Depends On      : mingw-w64-x86_64-gcc-libs  mingw-w64-x86_64-expat  mingw-w64-x86_64-bzip2  mingw-w64-x86_64-libffi  mingw-w64-x86_64-mpdecimal
                  mingw-w64-x86_64-ncurses  mingw-w64-x86_64-openssl  mingw-w64-x86_64-sqlite3  mingw-w64-x86_64-tcl  mingw-w64-x86_64-tk  mingw-w64-x86_64-zlib
                  mingw-w64-x86_64-xz
Optional Deps   : None
Required By     : mingw-w64-x86_64-gdb  mingw-w64-x86_64-glib2  mingw-w64-x86_64-gtest  mingw-w64-x86_64-mono  mingw-w64-x86_64-postgresql
                  mingw-w64-x86_64-python-apipkg  mingw-w64-x86_64-python-appdirs  mingw-w64-x86_64-python-atomicwrites  mingw-w64-x86_64-python-attrs
                  mingw-w64-x86_64-python-cairo  mingw-w64-x86_64-python-colorama  mingw-w64-x86_64-python-contextlib2  mingw-w64-x86_64-python-cycler
                  mingw-w64-x86_64-python-defusedxml  mingw-w64-x86_64-python-imagesize  mingw-w64-x86_64-python-importlib-metadata  mingw-w64-x86_64-python-iniconfig
                  mingw-w64-x86_64-python-jdcal  mingw-w64-x86_64-python-kiwisolver  mingw-w64-x86_64-python-lxml  mingw-w64-x86_64-python-more-itertools
                  mingw-w64-x86_64-python-numpy  mingw-w64-x86_64-python-olefile  mingw-w64-x86_64-python-ordered-set  mingw-w64-x86_64-python-packaging
                  mingw-w64-x86_64-python-pathlib2  mingw-w64-x86_64-python-pillow  mingw-w64-x86_64-python-pluggy  mingw-w64-x86_64-python-py
                  mingw-w64-x86_64-python-pyparsing  mingw-w64-x86_64-python-pytest  mingw-w64-x86_64-python-pytz  mingw-w64-x86_64-python-scandir
                  mingw-w64-x86_64-python-seaborn  mingw-w64-x86_64-python-setuptools  mingw-w64-x86_64-python-sip  mingw-w64-x86_64-python-six
                  mingw-w64-x86_64-python-wcwidth  mingw-w64-x86_64-python-zipp  mingw-w64-x86_64-vapoursynth
Optional For    : mingw-w64-x86_64-vtk
Conflicts With  : mingw-w64-x86_64-python3  mingw-w64-x86_64-python2<2.7.16-7
Replaces        : mingw-w64-x86_64-python3
Installed Size  : 112.87 MiB
Packager        : Alexey Pavlov <alexpux@gmail.com>
Build Date      : Thu, Apr 9, 2020 10:17:39 AM
Install Date    : Wed, Apr 22, 2020 10:04:36 AM
Install Reason  : Explicitly installed
Install Script  : No
Validated By    : Signature

$ pacman -Qi python
Name            : python
Version         : 3.8.2-1
Description     : Next generation of the python high-level scripting language
Architecture    : i686
URL             : https://www.python.org/
Licenses        : custom
Groups          : None
Provides        : python3
Depends On      : libbz2  libexpat  libffi  liblzma  ncurses  libopenssl  libreadline  mpdecimal  libsqlite  zlib
Optional Deps   : None
Required By     : gdb  python3-appdirs  python3-attrs  python3-pip  python3-pyparsing  python3-six  scons
Optional For    : None
Conflicts With  : None
Replaces        : python3
Installed Size  : 47.27 MiB
Packager        : Alexey Pavlov <alexpux@gmail.com>
Build Date      : Thu, Apr 16, 2020 12:31:48 PM
Install Date    : Wed, Apr 22, 2020 10:15:54 AM
Install Reason  : Explicitly installed
Install Script  : No
Validated By    : Signature

Packages providing python2

$ pacman -Sl | grep "python2 " | grep "installed"
mingw64 mingw-w64-x86_64-python2 2.7.18-1 [installed: 2.7.17-2]
msys python2 2.7.18-1 [installed: 2.7.17-1]