问:
React js cant interpret axios call the right way, data is undefined
When I perform a REST call (get) with axios from my react app, it says that the response is undefined. But when I try to do the same call in Postman, it clearly gives the right response. React cannot get the right response. How do I resolve this problem?

Response gives 'undefined' and response.data also gives 'undefined'.

```<code>class Blogpost extends React. Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

componentDidMount() {
const response = axios.get({
      URL: 'http://178.62.198.162/api/posts',
      headers: {'token' : 'pj11daaQRz7zUIH56B9Z'}
    })
    const items = response.data;
    this.setState({
      isLoaded: false,
      items: items,
    });
    console.log(this.items);
  }

render() {
    const {error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <ul>
          {this.items.map(item => (
            <li key={item.name}>
            {item.name}
            </li>
          ))}
        </ul>
      );
    }
  }
}
</code>```

The expected result would be an array of collections. But actually it is given back 'undefined'.

How can I make it work so response gives the right array?

EDIT
There seems to be a problem with the GET request. The promise gets rejected with fail code 404.

```<code>componentDidMount() {
const response = axios.get({
  URL: 'http://178.62.198.162/api/posts',
  headers: {'token' : 'pj11daaQRz7zUIH56B9Z'}
})
response.catch((error) => {
  console.log(error)
});
</code>```

}

Is this a problem on the server side, or on the client side and how do I resolve it?

答:
you should use async/await syntax to make sure response variable will be filled with right http get response before initializing</p>

```<code>async componentDidMount() {
  const response = await axios.get({
    URL: 'http://178.62.198.162/api/posts',
    headers: {'token' : 'pj11daaQRz7zUIH56B9Z'}
  })
  const items = response.data;
  this.setState({
  isLoaded: false,
  items: items,
});
}
</code>```

Body:
When I perform a REST call (get) with axios from my react app, it says that the response is undefined. But when I try to do the same call in Postman, it clearly gives the right response. React cannot get the right response. How do I resolve this problem?

Response gives 'undefined' and response.data also gives 'undefined'.

class Blogpost extends React. Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

componentDidMount() {
const response = axios.get({
      URL: 'http://178.62.198.162/api/posts',
      headers: {'token' : 'pj11daaQRz7zUIH56B9Z'}
    })
    const items = response.data;
    this.setState({
      isLoaded: false,
      items: items,
    });
    console.log(this.items);
  }

render() {
    const {error, isLoaded, items } = this.state;
    if (error) {
      return
Error: {error.message}
;
    } else if (!isLoaded) {
      return
Loading...
;
    } else {
      return (

          {this.items.map(item => (

            {item.name}

          ))}

      );
    }
  }
}

The expected result would be an array of collections. But actually it is given back 'undefined'.

How can I make it work so response gives the right array?

EDIT
There seems to be a problem with the GET request. The promise gets rejected with fail code 404.

componentDidMount() {
const response = axios.get({
  URL: 'http://178.62.198.162/api/posts',
  headers: {'token' : 'pj11daaQRz7zUIH56B9Z'}
})
response.catch((error) => {
  console.log(error)
});

}

Is this a problem on the server side, or on the client side and how do I resolve it?

Body:
you should use async/await syntax to make sure response variable will be filled with right http get response before initializing

async componentDidMount() {
  const response = await axios.get({
    URL: 'http://178.62.198.162/api/posts',
    headers: {'token' : 'pj11daaQRz7zUIH56B9Z'}
  })
  const items = response.data;
  this.setState({
  isLoaded: false,
  items: items,
});
}


来源: stackexchange

问:
Which is best free distributable code to html converter
In my application, I have a requirement to convert Java/VB/VB.net/etc program to HTML, and then use that HTML page (to insert in Word doc).

Sure we can write code for this, but this will entail programming for this too, and from more than one programming languages, and dealing with bugs. Whereas it needs to be released ASAP. Using 3rd party tool for this HTML generation is not an issue.

However this 3rd party tool, code to html formatter, should be free, robust, and should convert upto Java 1.5, and other language's recent version.

Do you know of any such converter (code to html converter/formatter) which is free, distributable, robust, and converts upto recent versions of more than one languages (including Java)?

To elaborate further, I am interested in a utility which will take source code file as input, and will generate HTML file as output. The HTML file should not use javascript to color the code, because then inserting in Word the coloring will be lost.

答: If you want to go with the JavaDoc way, I would recommend using Natural Docs. However, if you want to simply show the Java and convert into a CSS formatted HTML section on your page, I would recommend using Google's Code Prettify. Check out the link to README for examples. You can also check out the Java Test Page to see how the Java will look.</p>

OwnerDisplayName: vikramsjn

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: vikramsjn

OwnerDisplayName: Ascalonian


问:
AND Operator cannot work with bool and string
I have a LINQ2SQL statement where I am using two criteria:

```<code>var query1 = from r in dt.Test
                                where r.ID == 92
                                && r.Status = '"I"
                                select r.ID && r.Status = "I"
</code>```

But its giving me an err that AND (&&) operator cannot work with string and bool. Whats the turnaround for this?

答:
= is used for assignment and == is used for equality.

I am not sure what result you're expecting, but select r.ID && r.Status == "I" (even with 2 equal signs) is not valid in any case.

Depending on what you want to select, if the result is the amount of the rows qualifying for your search consider using Count().
If you want to select these two values, use a POCO class or an anonymous type:

```<code>var query1 = from r in dt.Test
             where r.ID == 92 && r.Status == "I"
             select new { ID = r.ID, Status = r.Status };
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a LINQ2SQL statement where I am using two criteria:

var query1 = from r in dt.Test
                                where r.ID == 92
                                && r.Status = '"I"
                                select r.ID && r.Status = "I"

But its giving me an err that AND (&&) operator cannot work with string and bool. Whats the turnaround for this?

Body:
= is used for assignment and == is used for equality.

I am not sure what result you're expecting, but select r.ID && r.Status == "I" (even with 2 equal signs) is not valid in any case.

Depending on what you want to select, if the result is the amount of the rows qualifying for your search consider using Count().
If you want to select these two values, use a POCO class or an anonymous type:

var query1 = from r in dt.Test
             where r.ID == 92 && r.Status == "I"
             select new { ID = r.ID, Status = r.Status };


问:
-[ECSlidingViewController notifyWhenInteractionChangesUsingBlock:]: unrecognized selector sent to instance
I recently updated Xcode to version 11.3.1 and after that i am not able to run my application. I've been getting the following exception:

2020-02-11 16:13:04.767795-0600 UVM[5204:80616] -[ECSlidingViewController notifyWhenInteractionChangesUsingBlock:]: unrecognized selector sent to instance 0x7f8258016c00

2020-02-11 16:13:04.785346-0600 UVM[5204:80616] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ECSlidingViewController notifyWhenInteractionChangesUsingBlock:]: unrecognized selector sent to instance 0x7f8258016c00'

It was working fine before i did the Xcode update. Can anyone help me how to fix this issue?

答:
It looks like the following method was deprecated and it was the one throwing the exception during launch.

```<code>- (void)notifyWhenInteractionEndsUsingBlock:(void(^)(id<UIViewControllerTransitionCoordinatorContext>context))handler {
    self.coordinatorInteractionEnded = handler;
}
</code>```

It was in ECSlidingViewController.m

If we comment out that method and add the following method the app is working fine again:

```<code>- (void)notifyWhenInteractionChangesUsingBlock:(nonnull void (^)(id<UIViewControllerTransitionCoordinatorContext> _Nonnull))handler {
    self.coordinatorInteractionEnded = handler;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
It looks like the following method was deprecated and it was the one throwing the exception during launch.

- (void)notifyWhenInteractionEndsUsingBlock:(void(^)(id<UIViewControllerTransitionCoordinatorContext>context))handler {
    self.coordinatorInteractionEnded = handler;
}

It was in ECSlidingViewController.m

If we comment out that method and add the following method the app is working fine again:

- (void)notifyWhenInteractionChangesUsingBlock:(nonnull void (^)(id<UIViewControllerTransitionCoordinatorContext> _Nonnull))handler {
    self.coordinatorInteractionEnded = handler;
}


问:
The value for key CFBundleShortVersionString [3.0.0] in the Info.plist file must contain a higher version than that of the previously approved version
I am uploading my IPA file to app store and it throw me below error:

ERROR ITMS-90062: "This bundle is invalid. The value for key CFBundleShortVersionString [3.0.0] in the Info.plist file must contain a higher version than that of the previously approved version [3.0.1]."

Below is my config for IOS:

```<code> "ios": {
      "bundleIdentifier": "com.test.test.test",
      "buildNumber": "5",
      "icon": "./assets/images/test.png",
      "config": {
        "googleSignIn": {
          "reservedClientId": ""
        }
      },
      "infoPlist": {
        "NSLocationWhenInUseUsageDescription": "Your current location will be displayed on the map and used for directions, nearby search results, and estimated travel times.",
        "CFBundleShortVersionString":"3.0.3",
        "CFBundleIdentifier": "com.test.test.test"
      }
    }
</code>```

答:
You have to reject the build in iTunesConnect and submit a new build
 with a higher build number</p>

Body:
I am uploading my IPA file to app store and it throw me below error:

ERROR ITMS-90062: "This bundle is invalid. The value for key CFBundleShortVersionString [3.0.0] in the Info.plist file must contain a higher version than that of the previously approved version [3.0.1]."

Below is my config for IOS:

 "ios": {
      "bundleIdentifier": "com.test.test.test",
      "buildNumber": "5",
      "icon": "./assets/images/test.png",
      "config": {
        "googleSignIn": {
          "reservedClientId": ""
        }
      },
      "infoPlist": {
        "NSLocationWhenInUseUsageDescription": "Your current location will be displayed on the map and used for directions, nearby search results, and estimated travel times.",
        "CFBundleShortVersionString":"3.0.3",
        "CFBundleIdentifier": "com.test.test.test"
      }
    }


问:
GNU Linker Script - move flash memory to new region
I am attempting to move sections of memory around using a linker script for an STM32F446ZE micro controller. My original setup consisted of this:

```<code>MEMORY
{
RAM (xrw)      : ORIGIN = 0x20000000, LENGTH = 128K
FLASH (rx)      : ORIGIN = 0x8000000, LENGTH = 512K - 128k
DATA (rwx)      : ORIGIN = 0x08060000, LENGTH = 5120
}

SECTIONS
{
  .user_data :
  {
    . = ALIGN(4);
    KEEP(*(.user_data))
    . = ALIGN(4);
  } >DATA
  .isr_vector :
  {
    . = ALIGN(4);
    KEEP(*(.isr_vector)) /* Startup code */
    . = ALIGN(4);
  } >FLASH

  .text :
  {
    . = ALIGN(4);
    *(.text)           /* .text sections (code) */
    *(.text*)          /* .text* sections (code) */
    *(.glue_7)         /* glue arm to thumb code */
    *(.glue_7t)        /* glue thumb to arm code */
    *(.eh_frame)
    KEEP (*(.init))
    KEEP (*(.fini))
    . = ALIGN(4);
    _etext = .;        /* define a global symbols at end of code */
  } >FLASH

  .rodata :
  {
    . = ALIGN(4);
    *(.rodata)         /* .rodata sections (constants, strings, etc.) */
    *(.rodata*)        /* .rodata* sections (constants, strings, etc.) */
    . = ALIGN(4);
  } >FLASH

  .data :
  {
    . = ALIGN(4);
    _sdata = .;        /* create a global symbol at data start */
    *(.data)           /* .data sections */
    *(.data*)          /* .data* sections */
    . = ALIGN(4);
    _edata = .;        /* define a global symbol at data end */
  } >RAM AT> FLASH

  . = ALIGN(4);
  .bss :
  {
    /* This is used by the startup in order to initialize the .bss secion */
    _sbss = .;         /* define a global symbol at bss start */
    __bss_start__ = _sbss;
    *(.bss)
    *(.bss*)
    *(COMMON)
    . = ALIGN(4);
    _ebss = .;         /* define a global symbol at bss end */
    __bss_end__ = _ebss;
  } >RAM

  /* User_heap_stack section, used to check that there is enough RAM left */
  ._user_heap_stack :
  {
    . = ALIGN(4);
    PROVIDE ( end = . );
    PROVIDE ( _end = . );
    . = . + _Min_Heap_Size;
    . = . + _Min_Stack_Size;
    . = ALIGN(4);
  } >RAM
</code>```

What I want to do is move the DATA to start at 0x08000000 (where flash is currently starting) and start FLASH at 0x08040000 (after DATA). I can change that in the memory section easy enough, but my program wont start. I believe some of the code in the SECTIONS block may have to be changed, but I'm not sure how. Question is: how can I move flash (where the program code is) to a later memory address.

答:
As P__J__ mentioned you can not move whole data region to the address 0x0800 0000 because MCU expects the interrupt vector to start there. When the MCU is booted from the flash memory the address 0x0800 0000 is mapped to the address 0x0000 0000.
What you can do instead is to create another region for the length of vector table and move the other parts of your sections as you please.

```<code>MEMORY
{
RAM (xrw)       : ORIGIN = 0x20000000, LENGTH = 128K
VECTORS (rx)    : ORIGIN = 0x08000000, LENGTH = 0xB8
FLASH (rx)      : ORIGIN = 0x080000B8, LENGTH = 512K - 128k - 0xB8
DATA (rwx)      : ORIGIN = 0x08060000, LENGTH = 5120
}

  .isr_vector :
  {
    KEEP(*(.isr_vector))
  } > VECTORS

</code>```

Body:
I am attempting to move sections of memory around using a linker script for an STM32F446ZE micro controller. My original setup consisted of this:

MEMORY
{
RAM (xrw)      : ORIGIN = 0x20000000, LENGTH = 128K
FLASH (rx)      : ORIGIN = 0x8000000, LENGTH = 512K - 128k
DATA (rwx)      : ORIGIN = 0x08060000, LENGTH = 5120
}

SECTIONS
{
  .user_data :
  {
    . = ALIGN(4);
    KEEP(*(.user_data))
    . = ALIGN(4);
  } >DATA
  .isr_vector :
  {
    . = ALIGN(4);
    KEEP(*(.isr_vector)) /* Startup code */
    . = ALIGN(4);
  } >FLASH

  .text :
  {
    . = ALIGN(4);
    *(.text)           /* .text sections (code) */
    *(.text*)          /* .text* sections (code) */
    *(.glue_7)         /* glue arm to thumb code */
    *(.glue_7t)        /* glue thumb to arm code */
    *(.eh_frame)
    KEEP (*(.init))
    KEEP (*(.fini))
    . = ALIGN(4);
    _etext = .;        /* define a global symbols at end of code */
  } >FLASH

  .rodata :
  {
    . = ALIGN(4);
    *(.rodata)         /* .rodata sections (constants, strings, etc.) */
    *(.rodata*)        /* .rodata* sections (constants, strings, etc.) */
    . = ALIGN(4);
  } >FLASH

  .data :
  {
    . = ALIGN(4);
    _sdata = .;        /* create a global symbol at data start */
    *(.data)           /* .data sections */
    *(.data*)          /* .data* sections */
    . = ALIGN(4);
    _edata = .;        /* define a global symbol at data end */
  } >RAM AT> FLASH

  . = ALIGN(4);
  .bss :
  {
    /* This is used by the startup in order to initialize the .bss secion */
    _sbss = .;         /* define a global symbol at bss start */
    __bss_start__ = _sbss;
    *(.bss)
    *(.bss*)
    *(COMMON)
    . = ALIGN(4);
    _ebss = .;         /* define a global symbol at bss end */
    __bss_end__ = _ebss;
  } >RAM

  /* User_heap_stack section, used to check that there is enough RAM left */
  ._user_heap_stack :
  {
    . = ALIGN(4);
    PROVIDE ( end = . );
    PROVIDE ( _end = . );
    . = . + _Min_Heap_Size;
    . = . + _Min_Stack_Size;
    . = ALIGN(4);
  } >RAM

What I want to do is move the DATA to start at 0x08000000 (where flash is currently starting) and start FLASH at 0x08040000 (after DATA). I can change that in the memory section easy enough, but my program wont start. I believe some of the code in the SECTIONS block may have to be changed, but I'm not sure how. Question is: how can I move flash (where the program code is) to a later memory address.

Body:
As P__J__ mentioned you can not move whole data region to the address 0x0800 0000 because MCU expects the interrupt vector to start there. When the MCU is booted from the flash memory the address 0x0800 0000 is mapped to the address 0x0000 0000.
What you can do instead is to create another region for the length of vector table and move the other parts of your sections as you please.

MEMORY
{
RAM (xrw)       : ORIGIN = 0x20000000, LENGTH = 128K
VECTORS (rx)    : ORIGIN = 0x08000000, LENGTH = 0xB8
FLASH (rx)      : ORIGIN = 0x080000B8, LENGTH = 512K - 128k - 0xB8
DATA (rwx)      : ORIGIN = 0x08060000, LENGTH = 5120
}

  .isr_vector :
  {
    KEEP(*(.isr_vector))
  } > VECTORS


问:
Installing last libreoffice by apt-get
How to install the last LibreOffice version by the apt-get command? I ran the followed commands at a Ubuntu 16.04 and just got version 6.2.8.2 but the last official one is 6.4.

```<code>sudo apt-add-repository ppa:libreoffice/ppa
sudo apt update
sudo apt upgrade
sudo apt install libreoffice
</code>```

答:
Second the official developers, LibreOffice-official-version Ubuntu 16.04 should be 5.1.6~rc2-0ubuntu1~xenial10. Because I had manually added sudo apt-add-repository ppa:libreoffice/ppa I was able to got libreoffice 6.2.8.2.

To achieve the 6.4 and newer installation they recommend to download the package or simple use sudo snap install libreoffice.

Title: Installing last libreoffice by apt-get

Body:
How to install the last LibreOffice version by the apt-get command? I ran the followed commands at a Ubuntu 16.04 and just got version 6.2.8.2 but the last official one is 6.4.

sudo apt-add-repository ppa:libreoffice/ppa
sudo apt update
sudo apt upgrade
sudo apt install libreoffice


问:
Can I use WPF in win32 application?
Our company has a software in Alaska Xbase++. I want to modernize the GUI with WPF, without rewriting the software in C#. In this Alaska Xbase++ language, I have the ability to call C/C++ functions. I beleive, it is possible to create hybrid DLL, which has managed code, yet callable from unmanaged language, so doing a stdcall.

So my plan is that I write a wrapper DLL which manages all the things to create a WPF window and controls (and eventloop, everything). In this Alaska Xbase++ language I would call this wrapper DLL to create WPF window and controls in my Application.

For example:
-WpfWrapper.DLL In C# DLL (or application which listens data from Xbase++ app):

```<code>Function CreateWpfWindow(title) {..}
Function CreateWpfButton(caption, x, y, parent) {..}
</code>```

C# DLL doing the "WPF things".

-In Alaska Xbase++ language I have a main window. But I want to modernize the GUI, I want to create some WPF window in that old Win32 app, so I call the DLL:

```<code>nHandle=CreateWpfWindow("My WPF window in Alaska Xbase++!")
CreateWpfButton("My button", 100, 100, nHandle)
</code>```

This is just my thoughts.. Maybe there is other way. But I wonder is it possible to integrate IN ANY WAY WPF window and controls to an old Win32 Application? I beleive it does, either via some wrapper DLL or via some wrapper application.

Please give me some guidance how this could work. The created WPF window in my old app must be in focus, and above other windows. I have the HWND of my main window, I beleive it is neccesary.

答:
I don't know what "Alaska Xbase++" is but my guess is the question you are asking is the reverse of what you should try. You shouldn't try to build a GUI application by calling into C# from some obscure programming environment. You should try to wrap your business logic, implemented in an obscure programming environment, in a DLL and call into that from C#.

Does Xbase++ expose a C interface?

If so make a custom DLL that calls your Xbase++ code and DllImport that DLL into a WPF application.

Title: Can I use WPF in win32 application?

Body:
Our company has a software in Alaska Xbase++. I want to modernize the GUI with WPF, without rewriting the software in C#. In this Alaska Xbase++ language, I have the ability to call C/C++ functions. I beleive, it is possible to create hybrid DLL, which has managed code, yet callable from unmanaged language, so doing a stdcall.

So my plan is that I write a wrapper DLL which manages all the things to create a WPF window and controls (and eventloop, everything). In this Alaska Xbase++ language I would call this wrapper DLL to create WPF window and controls in my Application.

For example:
-WpfWrapper.DLL In C# DLL (or application which listens data from Xbase++ app):

Function CreateWpfWindow(title) {..}
Function CreateWpfButton(caption, x, y, parent) {..}

C# DLL doing the "WPF things".

-In Alaska Xbase++ language I have a main window. But I want to modernize the GUI, I want to create some WPF window in that old Win32 app, so I call the DLL:

nHandle=CreateWpfWindow("My WPF window in Alaska Xbase++!")
CreateWpfButton("My button", 100, 100, nHandle)

This is just my thoughts.. Maybe there is other way. But I wonder is it possible to integrate IN ANY WAY WPF window and controls to an old Win32 Application? I beleive it does, either via some wrapper DLL or via some wrapper application.

Please give me some guidance how this could work. The created WPF window in my old app must be in focus, and above other windows. I have the HWND of my main window, I beleive it is neccesary.


问:
Java Lucene IndexReader not working correctly
The story is this. I want to mimic the behavior of a relational database using a Lucene index in java. I need to be able to do searching(reading) and writing at the same time.

For example, I want to save Project information into an index. For simplicity, let's say that the project has 2 fields - id and name. Now, before adding a new project to the index, I'm searching if a project with a given id is already present. For this I'm using an IndexSearcher. This operation completes with success (namely the IndexSearcher returns the internal doc id for the document that contains the project id I'm looking for).
Now I want to actually read the value of this project ID, so I'm using now an IndexReader to get the indexed Lucene document from which I can extract the project id field.
The problem is that the IndexReader return a Document that has all of the fields NULL. So, to repeat IndexSearcher works correctly, IndexReader returns bogus stuff.

I'm thinking that somehow this has to do with the fact that the document fields data does not get saved on the hard disk when the IndexWriter is flushed. The thing is that the first time I do this indexing operation, IndexReader works good. However after a restart of my application, the above mentioned situation happens. So I'm thinking that the first time around data floats in RAM, but doesn't get flushed correctly (or totally since IndexSearcher works) on the hard drive.

Maybe it will help if I give you the source code, so here it is (you can safely ignore the tryGetIdFromMemory part, I'm using that as an speed optimization trick):

```<code>public class ProjectMetadataIndexer {
private File indexFolder;
private Directory directory;
private IndexSearcher indexSearcher;
private IndexReader indexReader;
private IndexWriter indexWriter;
private Version luceneVersion = Version.LUCENE_31;

private Map<String, Integer> inMemoryIdHolder;
private final int memoryCapacity = 10000;

public ProjectMetadataIndexer() throws IOException {
    inMemoryIdHolder = new HashMap<String, Integer>();

    indexFolder = new File(ConfigurationSingleton.getInstance()
            .getProjectMetaIndexFolder());

    directory = FSDirectory.open(indexFolder);
    IndexWriterConfig config = new IndexWriterConfig(luceneVersion,
            new WhitespaceAnalyzer(luceneVersion));
    indexWriter = new IndexWriter(directory, config);

    indexReader = IndexReader.open(indexWriter, false);

    indexSearcher = new IndexSearcher(indexReader);

}

public int getProjectId(String projectName) throws IOException {
    int fromMemoryId = tryGetProjectIdFromMemory(projectName);
    if (fromMemoryId >= 0) {
        return fromMemoryId;
    } else {
        int projectId;

        Term projectNameTerm = new Term("projectName", projectName);
        TermQuery projectNameQuery = new TermQuery(projectNameTerm);

        BooleanQuery query = new BooleanQuery();
        query.add(projectNameQuery, Occur.MUST);

        TopDocs docs = indexSearcher.search(query, 1);
        if (docs.totalHits == 0) {
            projectId = IDStore.getInstance().getProjectId();
            indexMeta(projectId, projectName);
        } else {
            int internalId = docs.scoreDocs[0].doc;
            indexWriter.close();
            indexReader.close();
            indexSearcher.close();

            indexReader = IndexReader.open(directory);
            Document document = indexReader.document(internalId);
            List<Fieldable> fields = document.getFields();
            System.out.println(document.get("projectId"));
            projectId = Integer.valueOf(document.get("projectId"));
        }

        storeInMemory(projectName, projectId);

        return projectId;
    }
}

private int tryGetProjectIdFromMemory(String projectName) {
    String key = projectName;
    Integer id = inMemoryIdHolder.get(key);
    if (id == null) {
        return -1;
    } else {
        return id.intValue();
    }
}

private void storeInMemory(String projectName, int projectId) {
    if (inMemoryIdHolder.size() > memoryCapacity) {
        inMemoryIdHolder.clear();
    }
    String key = projectName;
    inMemoryIdHolder.put(key, projectId);
}

private void indexMeta(int projectId, String projectName)
        throws CorruptIndexException, IOException {
    Document document = new Document();

    Field idField = new Field("projectId", String.valueOf(projectId),
            Store.NO, Index.ANALYZED);
    document.add(idField);

    Field nameField = new Field("projectName", projectName, Store.NO,
            Index.ANALYZED);
    document.add(nameField);

    indexWriter.addDocument(document);
}

public void close() throws CorruptIndexException, IOException {
    indexReader.close();
    indexWriter.close();
}
</code>```

}

To be more precise all the problems occur in this if:

```<code>if (docs.totalHits == 0) {
        projectId = IDStore.getInstance().getProjectId();
        indexMeta(projectId, projectName);
    } else {
        int internalId = docs.scoreDocs[0].doc;

        Document document = indexReader.document(internalId);
        List<Fieldable> fields = document.getFields();
        System.out.println(document.get("projectId"));
        projectId = Integer.valueOf(document.get("projectId"));
    }
</code>```

On the else branch...
I don't know what is wrong.

答:
Do you store the respective fields? If not, the fields are "only" stored in the reverse index part, i.e. the field value is mapped to the document, but the document itself doesn't contain the field value.

The part of the code where you save the document might be helpful.

Body:
The story is this. I want to mimic the behavior of a relational database using a Lucene index in java. I need to be able to do searching(reading) and writing at the same time.

For example, I want to save Project information into an index. For simplicity, let's say that the project has 2 fields - id and name. Now, before adding a new project to the index, I'm searching if a project with a given id is already present. For this I'm using an IndexSearcher. This operation completes with success (namely the IndexSearcher returns the internal doc id for the document that contains the project id I'm looking for).
Now I want to actually read the value of this project ID, so I'm using now an IndexReader to get the indexed Lucene document from which I can extract the project id field.
The problem is that the IndexReader return a Document that has all of the fields NULL. So, to repeat IndexSearcher works correctly, IndexReader returns bogus stuff.

I'm thinking that somehow this has to do with the fact that the document fields data does not get saved on the hard disk when the IndexWriter is flushed. The thing is that the first time I do this indexing operation, IndexReader works good. However after a restart of my application, the above mentioned situation happens. So I'm thinking that the first time around data floats in RAM, but doesn't get flushed correctly (or totally since IndexSearcher works) on the hard drive.

Maybe it will help if I give you the source code, so here it is (you can safely ignore the tryGetIdFromMemory part, I'm using that as an speed optimization trick):

public class ProjectMetadataIndexer {
private File indexFolder;
private Directory directory;
private IndexSearcher indexSearcher;
private IndexReader indexReader;
private IndexWriter indexWriter;
private Version luceneVersion = Version.LUCENE_31;

private Map<String, Integer> inMemoryIdHolder;
private final int memoryCapacity = 10000;

public ProjectMetadataIndexer() throws IOException {
    inMemoryIdHolder = new HashMap<String, Integer>();

    indexFolder = new File(ConfigurationSingleton.getInstance()
            .getProjectMetaIndexFolder());

    directory = FSDirectory.open(indexFolder);
    IndexWriterConfig config = new IndexWriterConfig(luceneVersion,
            new WhitespaceAnalyzer(luceneVersion));
    indexWriter = new IndexWriter(directory, config);

    indexReader = IndexReader.open(indexWriter, false);

    indexSearcher = new IndexSearcher(indexReader);

}

public int getProjectId(String projectName) throws IOException {
    int fromMemoryId = tryGetProjectIdFromMemory(projectName);
    if (fromMemoryId >= 0) {
        return fromMemoryId;
    } else {
        int projectId;

        Term projectNameTerm = new Term("projectName", projectName);
        TermQuery projectNameQuery = new TermQuery(projectNameTerm);

        BooleanQuery query = new BooleanQuery();
        query.add(projectNameQuery, Occur.MUST);

        TopDocs docs = indexSearcher.search(query, 1);
        if (docs.totalHits == 0) {
            projectId = IDStore.getInstance().getProjectId();
            indexMeta(projectId, projectName);
        } else {
            int internalId = docs.scoreDocs[0].doc;
            indexWriter.close();
            indexReader.close();
            indexSearcher.close();

            indexReader = IndexReader.open(directory);
            Document document = indexReader.document(internalId);
            List<Fieldable> fields = document.getFields();
            System.out.println(document.get("projectId"));
            projectId = Integer.valueOf(document.get("projectId"));
        }

        storeInMemory(projectName, projectId);

        return projectId;
    }
}

private int tryGetProjectIdFromMemory(String projectName) {
    String key = projectName;
    Integer id = inMemoryIdHolder.get(key);
    if (id == null) {
        return -1;
    } else {
        return id.intValue();
    }
}

private void storeInMemory(String projectName, int projectId) {
    if (inMemoryIdHolder.size() > memoryCapacity) {
        inMemoryIdHolder.clear();
    }
    String key = projectName;
    inMemoryIdHolder.put(key, projectId);
}

private void indexMeta(int projectId, String projectName)
        throws CorruptIndexException, IOException {
    Document document = new Document();

    Field idField = new Field("projectId", String.valueOf(projectId),
            Store.NO, Index.ANALYZED);
    document.add(idField);

    Field nameField = new Field("projectName", projectName, Store.NO,
            Index.ANALYZED);
    document.add(nameField);

    indexWriter.addDocument(document);
}

public void close() throws CorruptIndexException, IOException {
    indexReader.close();
    indexWriter.close();
}

}

To be more precise all the problems occur in this if:

if (docs.totalHits == 0) {
        projectId = IDStore.getInstance().getProjectId();
        indexMeta(projectId, projectName);
    } else {
        int internalId = docs.scoreDocs[0].doc;

        Document document = indexReader.document(internalId);
        List<Fieldable> fields = document.getFields();
        System.out.println(document.get("projectId"));
        projectId = Integer.valueOf(document.get("projectId"));
    }

On the else branch...
I don't know what is wrong.


问:
Typing a pipe function in js with flow type
So I have the following pipe function in js that I have typed with flow:

```<code>const pipe = (...fns: $ReadOnlyArray<any>): any => (param: any) => fns.reduce((result, fn) => fn(result), param)
</code>```

and I was hoping to maybe allow some typing and use the mixed type like so:

```<code>const pipe = (...fns: $ReadOnlyArray<mixed>): mixed => (param: mixed) => fns.reduce((result, fn) => fn(result), param)
</code>```

But flow gives an error message of:

flow: error
  infer - fn (Cannot call 'fn' because mixed [1] is not a function.)

See online here: https://flow.org/try/#0PTAEAEDMBsHsHcBQBjWA7AzgF1ABwJa4CmoAvKABQB0NkmAXKACQBKRAhgCYDya0AngEEATsPb8APOzT8AfAEpG0-mVmVc7MQFslM+atB0MVYUU4BXZEQoVTGc9CwAaQ2n2k1dW0XuP5LjW15RBR0bDxCIgAmMkoaKiNGVg4ePiFRcQktfAAPMwVGbLzOAwpA9h1QIrN3T0wTM0trb19nV1rXFocsfzxNCvkgA

Its not the end of the world if i have to use the any type, but I was wondering why I cant use the mixed type? I mean it's allowed to take a function according to the docs: https://flow.org/en/docs/types/mixed/

答:
As defined, that function takes any number of arguments which can be anything. Yes, that includes functions, but it also includes, for example, numbers. What would happen if you called pipe(5)?

Instead, it seems like you want to restrict it to functions only. This is simple to do -- just replace $ReadOnlyArray<mixed> with ReadOnlyArray<mixed => mixed>. With that change, the function typechecks.

However, that's still not a very useful type. It will be frustrating to use the result, since it's mixed. That means that Flow doesn't know anything about its type, so you will be forced to refine it before using it. And, runtime refinements can only go so far.

This function would be much more useful if it were polymorphic:

```<code>const pipe = <T>(...fns: $ReadOnlyArray<T => T>): (T => T) => {
  return (param) => {
    return fns.reduce((result, fn) => fn(result), param);
  };
}

function plus5(x) { return x + 5; }
function times3(x) { return x * 3; }
const plus5times3 = pipe(plus5, times3);

(plus5times3(6): number);
// expected error
(plus5times3(6): string);
</code>```

(playground)

Now, you can actually call it and get a useful result. As written, you might sometimes get confusing type errors due to type inference, but that's typically resolved by adding additional type annotations. In particular I recommend adding a type annotation to the result of compose, e.g.

```<code>const plus5times3: number => number = pipe(plus5, times3);
</code>```

Body:
So I have the following pipe function in js that I have typed with flow:

const pipe = (...fns: $ReadOnlyArray<any>): any => (param: any) => fns.reduce((result, fn) => fn(result), param)

and I was hoping to maybe allow some typing and use the mixed type like so:

const pipe = (...fns: $ReadOnlyArray<mixed>): mixed => (param: mixed) => fns.reduce((result, fn) => fn(result), param)

But flow gives an error message of:

flow: error
  infer - fn (Cannot call 'fn' because mixed [1] is not a function.)

See online here: https://flow.org/try/#0PTAEAEDMBsHsHcBQBjWA7AzgF1ABwJa4CmoAvKABQB0NkmAXKACQBKRAhgCYDya0AngEEATsPb8APOzT8AfAEpG0-mVmVc7MQFslM+atB0MVYUU4BXZEQoVTGc9CwAaQ2n2k1dW0XuP5LjW15RBR0bDxCIgAmMkoaKiNGVg4ePiFRcQktfAAPMwVGbLzOAwpA9h1QIrN3T0wTM0trb19nV1rXFocsfzxNCvkgA

Its not the end of the world if i have to use the any type, but I was wondering why I cant use the mixed type? I mean it's allowed to take a function according to the docs: https://flow.org/en/docs/types/mixed/

Body:
As defined, that function takes any number of arguments which can be anything. Yes, that includes functions, but it also includes, for example, numbers. What would happen if you called pipe(5)?

Instead, it seems like you want to restrict it to functions only. This is simple to do -- just replace $ReadOnlyArray<mixed> with ReadOnlyArray<mixed => mixed>. With that change, the function typechecks.

However, that's still not a very useful type. It will be frustrating to use the result, since it's mixed. That means that Flow doesn't know anything about its type, so you will be forced to refine it before using it. And, runtime refinements can only go so far.

This function would be much more useful if it were polymorphic:

const pipe = <T>(...fns: $ReadOnlyArray<T => T>): (T => T) => {
  return (param) => {
    return fns.reduce((result, fn) => fn(result), param);
  };
}

function plus5(x) { return x + 5; }
function times3(x) { return x * 3; }
const plus5times3 = pipe(plus5, times3);

(plus5times3(6): number);
// expected error
(plus5times3(6): string);

(playground)

Now, you can actually call it and get a useful result. As written, you might sometimes get confusing type errors due to type inference, but that's typically resolved by adding additional type annotations. In particular I recommend adding a type annotation to the result of compose, e.g.

const plus5times3: number => number = pipe(plus5, times3);


问:
How can I make an Acumatica, multiline PXGridColumn display new lines?
I am customizing the description field on the Project Quotes form (Screen PM304500).  I need the description field to be multi-line and it must preserve new lines.

I have customized the field itself to allow for very long strings and I have customized the corresponding PXGridColumn with Multiline="true".  With this I am able to edit the field value and with shift-enter I am able to insert newlines in the string.  Also, the grid column, when not editing, will display the string on multiple lines, but new lines are ignored as if the value is being displayed as HTML.  I know the newlines are preserved since, when I again edit the value, the newlines are present.

Further, I have been able to use the developer console in Chrome to drill down to the  that results from the PXGridColumn.  That  is styled with "white-space: normal".  If I change this to "white-space: pre-wrap" the column looks as I want it to.

I have also tried munging the value of the field to replace the newlines with
 tags.  Unfortunately, when I do this, I see the literal "
" in the value rather than a new line.

Ideally, I would like to just change the styling on the  elements that result from the PXGridColumn to "white-space: pre-wrap".  Is there an attribute/property for PXGridColumn that will allow me to do that? Alternatively, I would be okay with the replacing new lines with
 approach if I could get the value to render as HTML.  Of course, I am open to other approaches.

答:
As of Acumatica 2020 R1 (or perhaps earlier versions also), you can solve this by setting the Layout -> WrapText property to True on the Grid:
Acumatica WrapText</p>


问:
Doctrine & Symfony - Get data from database with parameter on array column
Good afternoon,

I try to find, from my database specific users with a role which is passed in parameter to the query. However, I have "null" result currently.

The users class is like this example from Symfony Documentation.

This is my CustomerRepository:

```<code>class CustomerRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Customer::class);
    }

    public function findByRole(string $role)
    {
        return $this->getEntityManager()->createQuery(
            'SELECT c
             FROM App\Entity\Customer c
              WHERE c.roles IN (:role)'
        )
            ->setParameter(':role', $role)
            ->getResult()
        ;
    }
}
</code>```

I expect to return an array which contains one or several users who have the role.

答:
c.roles is a list that can contains multiple items (roles), so please can you reverse the where like this :

```<code>WHERE :role IN c.roles
</code>```

PS: insure the case of string $role is upper (e.g "ROLE_ADMIN").

Body:
Good afternoon,

I try to find, from my database specific users with a role which is passed in parameter to the query. However, I have "null" result currently.

The users class is like this example from Symfony Documentation.

This is my CustomerRepository:

class CustomerRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Customer::class);
    }

    public function findByRole(string $role)
    {
        return $this->getEntityManager()->createQuery(
            'SELECT c
             FROM App\Entity\Customer c
              WHERE c.roles IN (:role)'
        )
            ->setParameter(':role', $role)
            ->getResult()
        ;
    }
}

I expect to return an array which contains one or several users who have the role.

Body:
c.roles is a list that can contains multiple items (roles), so please can you reverse the where like this :

WHERE :role IN c.roles

PS: insure the case of string $role is upper (e.g "ROLE_ADMIN").


问:
Print key if any nested value matches a set value
This is best explained with expected input and output.

Given this input:

```<code>{
  "27852380038": {
    "compute_id": 34234234,
    "to_compute": [
      {
        "asset_id": 304221854,
        "new_scheme": "mynewscheme",
        "original_host": "oldscheme1234.location.com"
      },
      {
        "asset_id": 12123121,
        "new_scheme": "myotherscheme",
        "original_host": "olderscheme1234.location.com"
      }
    ]
  },
  "31352333022": {
    "compute_id": 43888877,
    "to_compute": [
      {
        "asset_id": 404221555,
        "new_scheme": "mynewscheme",
        "original_host": "oldscheme1234.location.com"
      },
      {
        "asset_id": 52123444,
        "new_scheme": "myotherscheme",
        "original_host": "olderscheme1234.location.com"
      }
    ]
  }
}
</code>```

And the asset_id that I'm searching for, 12123121, the output should be:

```<code>27852380038
</code>```

So I want the top level keys where any of the asset_ids in to_compute match my input asset_id.

I haven't seen any jq example so far that combines nested access with an any test / if else.

答:
With some help from a coworker I was able to figure it out:</p>

```<code>$ export ASSET_ID=12123121
$ cat input.json | jq -r "to_entries[] | .value.to_compute[] + {job: .key} | select(.asset_id==$ASSET_ID) | .job"
27852380038
</code>```

Body:
This is best explained with expected input and output.

Given this input:

{
  "27852380038": {
    "compute_id": 34234234,
    "to_compute": [
      {
        "asset_id": 304221854,
        "new_scheme": "mynewscheme",
        "original_host": "oldscheme1234.location.com"
      },
      {
        "asset_id": 12123121,
        "new_scheme": "myotherscheme",
        "original_host": "olderscheme1234.location.com"
      }
    ]
  },
  "31352333022": {
    "compute_id": 43888877,
    "to_compute": [
      {
        "asset_id": 404221555,
        "new_scheme": "mynewscheme",
        "original_host": "oldscheme1234.location.com"
      },
      {
        "asset_id": 52123444,
        "new_scheme": "myotherscheme",
        "original_host": "olderscheme1234.location.com"
      }
    ]
  }
}

And the asset_id that I'm searching for, 12123121, the output should be:

27852380038

So I want the top level keys where any of the asset_ids in to_compute match my input asset_id.

I haven't seen any jq example so far that combines nested access with an any test / if else.

Body:
With some help from a coworker I was able to figure it out:

$ export ASSET_ID=12123121
$ cat input.json | jq -r "to_entries[] | .value.to_compute[] + {job: .key} | select(.asset_id==$ASSET_ID) | .job"
27852380038


问:
php checkbox array access
```<code>$i=0;
while (db_data) {
$i++;
echo '<input type="checkbox" name="v['.$i.']" value="'.$url.'"';
if ($v[$i]) {
  echo ' checked';
  $s .= $url;
}
echo '/>';

}
</code>```

I have the above array of checkboxes. It worked on my pc, but not on the server; it seems like the confusing part is on $v[$i].

$v is not defined, but sure used no where else. the problem is my checkbox selection never restored, and code never get into the if statement.

however, if i add the following, i can see the value. just the checkbox lost after the processing
    $v=$_POST['v'];
    while (list ($key,$val) = @each ($v)) {
    $x .= ' 11*'.$key.'-'.$val.'*22 ';
    }

my goal is to preserve the checkbox checked on the form, and i need the $s elsewhere. any solution to replace $v[$i]?

Can anybody help me fix this? Thank you.

答:
Try to print_r($_POST) and then print_r($v) and see if anything comes up.  If the $_POST works, then you know that it is being posted back to the page correctly.  Then if the $v is working, then you know you set $v = $_POST correctly.  Due to the fact that you don't actually give us any information on the db_data, I assume this is working correctly and displaying all the checkboxes on first load, so as long as it is posted and you are setting the $v variable, it should be working.

A side note is that you should validate the $_POST variables before using, but do that after you get things working.

Title: php checkbox array access

Body:
$i=0;
while (db_data) {
$i++;
echo '<input type="checkbox" name="v['.$i.']" value="'.$url.'"';
if ($v[$i]) {
  echo ' checked';
  $s .= $url;
}
echo '/>';

}

I have the above array of checkboxes. It worked on my pc, but not on the server; it seems like the confusing part is on $v[$i].

$v is not defined, but sure used no where else. the problem is my checkbox selection never restored, and code never get into the if statement.

however, if i add the following, i can see the value. just the checkbox lost after the processing
    $v=$_POST['v'];
    while (list ($key,$val) = @each ($v)) {
    $x .= ' 11*'.$key.'-'.$val.'*22 ';
    }

my goal is to preserve the checkbox checked on the form, and i need the $s elsewhere. any solution to replace $v[$i]?

Can anybody help me fix this? Thank you.


问:
How to override the default browser selection in Windows 7 when opening webppages with Python
I have a program written with Python 3.7.4 on Windows that opens web pages in a browser.  It displays the default browser and gives the user the chance to change which browser they want to use to open programs with.

The default browser is detected when the program is initialised using this technique:

```<code>from winreg import HKEY_CURRENT_USER, OpenKey, QueryValueEx

import webbroswer

reg_path = r'Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice'
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
firefox_path = 'C:/Program Files (x86)/Mozilla Firefox/firefox.exe %s'

with OpenKey(HKEY_CURRENT_USER, reg_path) as key:
    print(QueryValueEx(key, 'ProgId'))
    thedefaultbrowser = (QueryValueEx(key, 'ProgId'))
    thedefaultbrowser = (thedefaultbrowser[0])
    thedefaultbrowser = (thedefaultbrowser[0:2])
    if thedefaultbrowser == "Fi":
        browser_path = firefox_path
    if thedefaultbrowser == "Ch":
        browser_path = chrome_path
</code>```

And links are opened like this, as part of an infinite loop that happens later in the program:

```<code>while True:

    # [lots of GUI code that isn't relevant]

    event = input()

    if event == 'pleasegetmealinknao':
        x=open("C:/folder/atextfilewithalinkinit.txt", "r")
        the_url1 = x.read()
        webbrowser.get(browser_path).open(the_url1)
        x.close()
</code>```

In the same loop, input can be accepted from the user to change the browser type:

```<code>    elif event == "Firefox":
        browser_path = firefox_path
        continue
    elif event == "Chrome":
        browser_path = chrome_path
        continue
</code>```

So I can open a webpage with this just fine.  I can then change the browser type just fine, and then open another webpage in the newly user-selected browser, but - only in Windows 10.

In Windows 7, Firefox co-operates beautifully, and so does Chrome but only if Chrome is set as the default browser before the program runs.  However if Firefox is set as the default browser before the program is started, as soon as I switch to Chrome and then try to open anything in Chrome, the program gets very upset and stops running.  No crash, no error message or traceback, it just freezes completely and needs to be hard-restarted.  Sometimes I can rescue the program from its frozen state by closing the new browser window that was just opened, but this of course defeats the purpose of the program.

HOWEVER - if I scrap all this fancy business and just accept whatever the default browser is, like this:

```<code>    if event == 'pleasegetmealinknao':
        x=open("C:/folder/atextfilewithalinkinit.txt", "r")
        the_url1 = x.read()
        webbrowser.open(the_url1)
        x.close()
</code>```

Then the chosen link will open happily in whatever the system default browser is, whether it be Firefox, Chrome, Internet Explorer, or anything else.

So why is this happening and how can I fix?  Or do I just have to bury my dream of selectable browsers?

My guess is that this might have something to do with Chrome detecting that it is not the default browser and asking the user to change the default browser setting, that would make sense.  However then the question is, how do I make the Python program ignore whatever this behaviour is.  A popup related to this doesn't always appear.

EDIT: further testing and sometimes the Windows 7 pattern of behaviour also happens in Windows 10... but seemingly not all the time.  This makes me think even more that it's browser-related rather than strictly OS related and has a lot to do with Chrome asking for default status, but I'm still no closer to working out what to do about it.

答:
if i get it right you wanna open a tab in your desire browser rather than default browser
in this case you can use the get method in webbrowser library

the simple code that works for me was :

```<code>import webbrowser as wb

wb.get('google-chrome') #the return answer was : <webbrowser.Chrome object at 0x7fe787065a50>

wb.get('google-chrome').open('https://url')

</code>```

Here is the list for the supported browsers:

Body:
I have a program written with Python 3.7.4 on Windows that opens web pages in a browser.  It displays the default browser and gives the user the chance to change which browser they want to use to open programs with.

The default browser is detected when the program is initialised using this technique:

from winreg import HKEY_CURRENT_USER, OpenKey, QueryValueEx

import webbroswer

reg_path = r'Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice'
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
firefox_path = 'C:/Program Files (x86)/Mozilla Firefox/firefox.exe %s'

with OpenKey(HKEY_CURRENT_USER, reg_path) as key:
    print(QueryValueEx(key, 'ProgId'))
    thedefaultbrowser = (QueryValueEx(key, 'ProgId'))
    thedefaultbrowser = (thedefaultbrowser[0])
    thedefaultbrowser = (thedefaultbrowser[0:2])
    if thedefaultbrowser == "Fi":
        browser_path = firefox_path
    if thedefaultbrowser == "Ch":
        browser_path = chrome_path

And links are opened like this, as part of an infinite loop that happens later in the program:

while True:

    # [lots of GUI code that isn't relevant]

    event = input()

    if event == 'pleasegetmealinknao':
        x=open("C:/folder/atextfilewithalinkinit.txt", "r")
        the_url1 = x.read()
        webbrowser.get(browser_path).open(the_url1)
        x.close()

In the same loop, input can be accepted from the user to change the browser type:

    elif event == "Firefox":
        browser_path = firefox_path
        continue
    elif event == "Chrome":
        browser_path = chrome_path
        continue

So I can open a webpage with this just fine.  I can then change the browser type just fine, and then open another webpage in the newly user-selected browser, but - only in Windows 10.

In Windows 7, Firefox co-operates beautifully, and so does Chrome but only if Chrome is set as the default browser before the program runs.  However if Firefox is set as the default browser before the program is started, as soon as I switch to Chrome and then try to open anything in Chrome, the program gets very upset and stops running.  No crash, no error message or traceback, it just freezes completely and needs to be hard-restarted.  Sometimes I can rescue the program from its frozen state by closing the new browser window that was just opened, but this of course defeats the purpose of the program.

HOWEVER - if I scrap all this fancy business and just accept whatever the default browser is, like this:

    if event == 'pleasegetmealinknao':
        x=open("C:/folder/atextfilewithalinkinit.txt", "r")
        the_url1 = x.read()
        webbrowser.open(the_url1)
        x.close()

Then the chosen link will open happily in whatever the system default browser is, whether it be Firefox, Chrome, Internet Explorer, or anything else.

So why is this happening and how can I fix?  Or do I just have to bury my dream of selectable browsers?

My guess is that this might have something to do with Chrome detecting that it is not the default browser and asking the user to change the default browser setting, that would make sense.  However then the question is, how do I make the Python program ignore whatever this behaviour is.  A popup related to this doesn't always appear.

EDIT: further testing and sometimes the Windows 7 pattern of behaviour also happens in Windows 10... but seemingly not all the time.  This makes me think even more that it's browser-related rather than strictly OS related and has a lot to do with Chrome asking for default status, but I'm still no closer to working out what to do about it.

Body:
if i get it right you wanna open a tab in your desire browser rather than default browser
in this case you can use the get method in webbrowser library

the simple code that works for me was :

import webbrowser as wb

wb.get('google-chrome') #the return answer was : <webbrowser.Chrome object at 0x7fe787065a50>

wb.get('google-chrome').open('https://url')

Here is the list for the supported browsers:


问:
How to create subset groups by identifying unique strings within column names
I have a dataframe:

```<code>`df <- data.frame(Year = 1940:2000,
             sp99_002_04A_01 = rnorm(61, 1:100),
             sp99_002_04B_01 = rnorm(61, 1:100),
             sp99_002_05A_01 = rnorm(61, 1:100),
             sp99_006_01A_14 = rnorm(61, 1:100),
             sp99_023a_02B_06 = rnorm(61, 1:100),
             sp99_023a_05B_06 = rnorm(61, 1:100),
             sp99_010_03B_03 = rnorm(61, 1:100))`
</code>```

Each name is formatted: speciesyear_plot#(subset)_sample#_trial#, as shown above.

I need to group columns for further analysis by plot number. That means all columns sharing the same unique character string in xxxx_THIS_xxxx_xx location of the column names, without having to call each plot # by name.

答:
I ended up doing this:</p>

```<code>'mydt <- fread("data.csv")

mydt <- melt.data.table(mydt, id.vars = "Year", value.name = 'measure', variable.name
= "ID")
mydt <- na.omit(mydt)
mydt[, ID := as.character(ID)]

splitNames <- lapply(mydt$ID, FUN = function(x) {

splitUpID <- strsplit(x, split = "_")
plot <- splitUpID[[1]][2]

return(plot)
})
plots <- unlist(splitNames)
mydt[, plot := plots]'
</code>```

Body:
I have a dataframe:

`df <- data.frame(Year = 1940:2000,
             sp99_002_04A_01 = rnorm(61, 1:100),
             sp99_002_04B_01 = rnorm(61, 1:100),
             sp99_002_05A_01 = rnorm(61, 1:100),
             sp99_006_01A_14 = rnorm(61, 1:100),
             sp99_023a_02B_06 = rnorm(61, 1:100),
             sp99_023a_05B_06 = rnorm(61, 1:100),
             sp99_010_03B_03 = rnorm(61, 1:100))`

Each name is formatted: speciesyear_plot#(subset)_sample#_trial#, as shown above.

I need to group columns for further analysis by plot number. That means all columns sharing the same unique character string in xxxx_THIS_xxxx_xx location of the column names, without having to call each plot # by name.

Body:
I ended up doing this:

'mydt <- fread("data.csv")

mydt <- melt.data.table(mydt, id.vars = "Year", value.name = 'measure', variable.name
= "ID")
mydt <- na.omit(mydt)
mydt[, ID := as.character(ID)]

splitNames <- lapply(mydt$ID, FUN = function(x) {

splitUpID <- strsplit(x, split = "_")
plot <- splitUpID[[1]][2]

return(plot)
})
plots <- unlist(splitNames)
mydt[, plot := plots]'


问:
FCM returning 401 unauthorized error for iOS devices only with Google client API using PHP
I am using FCM HTTP v1 API for sending notifications to mobile devices. The backend is written using PHP and I am using Google API client library and using a service account to authorize my requests to FCM. But I am facing some weird issues like notifications are being sent to all Android devices, but fcm returns 401 unauthorized error for iOS devices. Also, I have tested using my own iOS device but fcm always returns 200 OK when I am using my own iOS device. I am so confused whether the issue is with my code or some configuration on the mobile device. Here is how I am sending the notifications.

```<code>$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$httpClient = $client->authorize();
$message = [
    "message" =>
    [
        "token" => $device_token,
        "notification" =>
        [
            "body" => $body,
            "title" => "xxxxx"
        ],
        "apns" =>
        [
            "payload" =>
            [
                "aps" =>
                [
                  "category" =>  "NEW_MESSAGE_CATEGORY",
                  "alert" =>  [
                     "body" =>  $body
                  ],
                  "badge" =>  3,
                  "sound" =>  "default",
                  "chat" => 2

                ]
            ]
        ]
    ]
];
$response = $httpClient->post("https://fcm.googleapis.com/v1/projects/xxxx-123/messages:send", ['json' => $message]);
</code>```

What am I doing wrong in authorization? Please help. Service account file is already added in GOOGLE_APPLICATION_CREDENTIALS env variable.

答:
FCM uses APNS (Apple Push Notification Service) to delivery messages to iOS devices, in order to do it, FCM need to connect to Apple server.

So we need to configure APNS credentials in firebase console. If there is any error in this configuration, FCM can't connect to Apple server, and return 401 error.

So check  all configs in Settings -> Project Configuration -> Cloud Messaging -> iOS Configuration -> APNS Authentication Key
In special, check if the "key code" are correct.

More info about this configs can be found at:

https://firebase.google.com/docs/cloud-messaging/ios/client#upload_your_apns_authentication_key

https://firebase.google.com/docs/cloud-messaging/ios/certs

Regards

Body:
I am using FCM HTTP v1 API for sending notifications to mobile devices. The backend is written using PHP and I am using Google API client library and using a service account to authorize my requests to FCM. But I am facing some weird issues like notifications are being sent to all Android devices, but fcm returns 401 unauthorized error for iOS devices. Also, I have tested using my own iOS device but fcm always returns 200 OK when I am using my own iOS device. I am so confused whether the issue is with my code or some configuration on the mobile device. Here is how I am sending the notifications.

$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$httpClient = $client->authorize();
$message = [
    "message" =>
    [
        "token" => $device_token,
        "notification" =>
        [
            "body" => $body,
            "title" => "xxxxx"
        ],
        "apns" =>
        [
            "payload" =>
            [
                "aps" =>
                [
                  "category" =>  "NEW_MESSAGE_CATEGORY",
                  "alert" =>  [
                     "body" =>  $body
                  ],
                  "badge" =>  3,
                  "sound" =>  "default",
                  "chat" => 2

                ]
            ]
        ]
    ]
];
$response = $httpClient->post("https://fcm.googleapis.com/v1/projects/xxxx-123/messages:send", ['json' => $message]);

What am I doing wrong in authorization? Please help. Service account file is already added in GOOGLE_APPLICATION_CREDENTIALS env variable.


问:
HTML Input Time but No Hour Rollover
I'm looking for an HTML element that stores time, but not the time of day, just hours:minutes:seconds.  So if something took 40 hours, 10 minutes, I want to be able to enter 40:10:00. I tried using an input time element in my html as below, but it operates as a clock, only letting you enter times of day (roll over at 12 hours, AM/PM label, etc.).  Is there an element that I can use for this?  Or is it possible to adjust the input/time properties so it behaves this way (looking over the properties I don't think so; there is a max setting but it didn't work for me)?

Alternatively I'm planning on using three input-number fields with max/min settings to simulate the idea, but that's obviously tougher to handle.  If there is a better solution please let me know.  Thank you.

```<code><!DOCTYPE html>
<html>
<body>
<input type="time" id="myTime" value="22:15:00">

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

答:
what you need  is  Time Input Mask / Validation

take a look at this  it's a Jquery plugin

download it

alex-time plugin

&  add it to your html

use it by calling .typeATime() on input element

$("#time").typeATime();

example:
https://codepen.io/alexousy/pen/QKNzdY

Title: HTML Input Time but No Hour Rollover

Body:
I'm looking for an HTML element that stores time, but not the time of day, just hours:minutes:seconds.  So if something took 40 hours, 10 minutes, I want to be able to enter 40:10:00. I tried using an input time element in my html as below, but it operates as a clock, only letting you enter times of day (roll over at 12 hours, AM/PM label, etc.).  Is there an element that I can use for this?  Or is it possible to adjust the input/time properties so it behaves this way (looking over the properties I don't think so; there is a max setting but it didn't work for me)?

Alternatively I'm planning on using three input-number fields with max/min settings to simulate the idea, but that's obviously tougher to handle.  If there is a better solution please let me know.  Thank you.

<!DOCTYPE html>

<input type="time" id="myTime" value="22:15:00">

Body:
what you need  is  Time Input Mask / Validation

take a look at this  it's a Jquery plugin

download it

alex-time plugin

&  add it to your html

<script src="alex-date-time.js"></script>

use it by calling .typeATime() on input element

$("#time").typeATime();

example:
https://codepen.io/alexousy/pen/QKNzdY


问:
Recursive function to convert from decimal to binary
My code has a  problem with conversion of the number 3

I would like to write a function which converts a decimal number into a binary one. The principle of recursion must be used. I have already written the following code.

```<code>    Function recursive(number As Integer) As String

        Dim result As String

        If number > 0 Then

            Dim binaryNumber As String
            Dim digit As Integer

            binaryNumber = recursive(number / 2)
            digit = number Mod 2
            result = result & binaryNumber & digit

        End If

        recursive = result

    End Function
</code>```

Right result:

Input: 10

Output: 1010

Wrong result:

Input: 3

Output: 101

It also works reasonably well, but I get a wrong result when I try to convert the decimal number 3. Where is the error?

答:
```<code>Function recursive(number As Integer) As String

        Dim result As String

        If number > 0 Then

            Dim binaryNumber As String
            Dim digit As Integer
            digit = number Mod 2
            number = Int(number / 2)
            binaryNumber = recursive(number)
            result = result & binaryNumber & digit

        End If

        recursive = result
End Function
</code>```

Body:
My code has a  problem with conversion of the number 3

I would like to write a function which converts a decimal number into a binary one. The principle of recursion must be used. I have already written the following code.

    Function recursive(number As Integer) As String

        Dim result As String

        If number > 0 Then

            Dim binaryNumber As String
            Dim digit As Integer

            binaryNumber = recursive(number / 2)
            digit = number Mod 2
            result = result & binaryNumber & digit

        End If

        recursive = result

    End Function

Right result:

Input: 10

Output: 1010

Wrong result:

Input: 3

Output: 101

It also works reasonably well, but I get a wrong result when I try to convert the decimal number 3. Where is the error?


问:
Public SQL database for educational purposes
I am looking for a publicly available SQL database with free access, where one can run some SELECT queries for free on some meaningful data (not item1, item2, item3). Have you seen any? Even better if it came together with some tutorial.

Vendor is not that relevant, as long as one can connect using a generic JDBC client.

答:
I like the concept of a game on pure SQL as implemented here: https://mystery.knightlab.com

It offers gamification of learning SQL and includes an optional tutorial-like introduction.

If you already know SQL but feel a little rusty, then this is fun to brush up.

For beginners it is an easy hand-help first contact.

The data are artificial and have a slightly steep drop-off when leaving the immediate game track, but I think it still matchs your requirement to be "meaningful". (And if you go intentionally off-track, then there are hints that some easter-eggs can be found, in the shape of jokes. I did not yet manage to get the query right to actually read them... So I think that even beyond the obvious game there is something for the more experienced to hunt for.)


问:
How to properly convert string to std::chrono::system_clock::time_point?
I have followed some good answers to similar questions like this one.

Yet my code seems to give output one hour later after converting string to time_point and back to string.

The code that gives the wrong answer:

```<code>#include <string>
#include <ctime>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>

using date_time = std::chrono::system_clock::time_point;

std::string dateTimeToString(date_time time) {
    std::time_t now_c = std::chrono::system_clock::to_time_t(time);
    auto tm = std::localtime(&now_c);
    char buffer[32];
    std::strftime(buffer, 32, "%Y-%m-%d %H:%M:%S", tm);
    return std::string(buffer);
}

date_time stringToDateTime(const std::string &s) {
    std::tm timeDate = {};
    std::istringstream ss(s);
    ss >> std::get_time(&timeDate, "%Y-%m-%d %H:%M:%S");
    return std::chrono::system_clock::from_time_t(mktime(&timeDate));
}

int main() {
    std::string birthday = "2000-06-05 20:20:00";
    std::cout << "Two birthday dates: \n" << birthday << " \nsecond one:\n" << dateTimeToString(stringToDateTime(birthday))
              << "\n******************\n";
    return 0;
}
</code>```

And the output:

Two birthday dates:
  2000-06-05 20:20:00
  second one:
  2000-06-05 21:20:00

I have thought that this has something to do with timezones, but I am unable to solve this problem. What is wrong with my code?

答:
You can use boost library for time management.

Look at boost::date_time::parse_date(const std::string& s, int order_spec = ymd_order_iso):

```<code>//! Generic function to parse a delimited date (eg: 2002-02-10)
/*! Accepted formats are: "2003-02-10" or " 2003-Feb-10" or
 * "2003-Feburary-10"
 * The order in which the Month, Day, & Year appear in the argument
 * string can be accomodated by passing in the appropriate ymd_order_spec
 */
</code>```

And at boost::date_time::parse_delimited_time_duration(const std::string& s):

```<code>//! Creates a time_duration object from a delimited string
/*! Expected format for string is "[-]h[h][:mm][:ss][.fff]".
 * If the number of fractional digits provided is greater than the
 * precision of the time duration type then the extra digits are
 * truncated.
 *
 * A negative duration will be created if the first character in
 * string is a '-', all other '-' will be treated as delimiters.
 * Accepted delimiters are "-:,.".
 */
</code>```

Boost made a wrapper function to those both methods, that can parse a date-time string:

```<code>template<class time_type>
inline time_type parse_delimited_time(const std::string& s, char sep) {
    typedef typename time_type::time_duration_type time_duration;
    typedef typename time_type::date_type date_type;

    //split date/time on a unique delimiter char such as ' ' or 'T'
    std::string date_string, tod_string;
    split(s, sep, date_string, tod_string);
    //call parse_date with first string
    date_type d = parse_date<date_type>(date_string);
    //call parse_time_duration with remaining string
    time_duration td = parse_delimited_time_duration<time_duration>(tod_string);
    //construct a time
    return time_type(d, td);

}
</code>```

If you want a different date format parser, I made a slightly different implementation:

```<code>posix_time::ptime parse_dmy_time(const std::string &s, char sep) {
    typedef typename posix_time::ptime::time_duration_type time_duration;
    typedef typename posix_time::ptime::date_type date_type;

    //split date/time on a unique delimiter char such as ' ' or 'T'
    std::string date_string, tod_string;
    split(s, sep, date_string, tod_string);
    //call parse_date with first string
    auto d = parse_date<date_type>(date_string, ymd_order_dmy);
    //call parse_time_duration with remaining string
    auto td = parse_delimited_time_duration<time_duration>(tod_string);
    //construct a time
    return {d, td};
}
</code>```

Body:
I have followed some good answers to similar questions like this one.

Yet my code seems to give output one hour later after converting string to time_point and back to string.

The code that gives the wrong answer:

#include <string>
#include <ctime>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>

using date_time = std::chrono::system_clock::time_point;

std::string dateTimeToString(date_time time) {
    std::time_t now_c = std::chrono::system_clock::to_time_t(time);
    auto tm = std::localtime(&now_c);
    char buffer[32];
    std::strftime(buffer, 32, "%Y-%m-%d %H:%M:%S", tm);
    return std::string(buffer);
}

date_time stringToDateTime(const std::string &s) {
    std::tm timeDate = {};
    std::istringstream ss(s);
    ss >> std::get_time(&timeDate, "%Y-%m-%d %H:%M:%S");
    return std::chrono::system_clock::from_time_t(mktime(&timeDate));
}

int main() {
    std::string birthday = "2000-06-05 20:20:00";
    std::cout << "Two birthday dates: \n" << birthday << " \nsecond one:\n" << dateTimeToString(stringToDateTime(birthday))
              << "\n******************\n";
    return 0;
}

And the output:

Two birthday dates:
  2000-06-05 20:20:00
  second one:
  2000-06-05 21:20:00

I have thought that this has something to do with timezones, but I am unable to solve this problem. What is wrong with my code?

Body:
You can use boost library for time management.

Look at boost::date_time::parse_date(const std::string& s, int order_spec = ymd_order_iso):

//! Generic function to parse a delimited date (eg: 2002-02-10)
/*! Accepted formats are: "2003-02-10" or " 2003-Feb-10" or
 * "2003-Feburary-10"
 * The order in which the Month, Day, & Year appear in the argument
 * string can be accomodated by passing in the appropriate ymd_order_spec
 */

And at boost::date_time::parse_delimited_time_duration(const std::string& s):

//! Creates a time_duration object from a delimited string
/*! Expected format for string is "[-]h[h][:mm][:ss][.fff]".
 * If the number of fractional digits provided is greater than the
 * precision of the time duration type then the extra digits are
 * truncated.
 *
 * A negative duration will be created if the first character in
 * string is a '-', all other '-' will be treated as delimiters.
 * Accepted delimiters are "-:,.".
 */

Boost made a wrapper function to those both methods, that can parse a date-time string:

template<class time_type>
inline time_type parse_delimited_time(const std::string& s, char sep) {
    typedef typename time_type::time_duration_type time_duration;
    typedef typename time_type::date_type date_type;

    //split date/time on a unique delimiter char such as ' ' or 'T'
    std::string date_string, tod_string;
    split(s, sep, date_string, tod_string);
    //call parse_date with first string
    date_type d = parse_date<date_type>(date_string);
    //call parse_time_duration with remaining string
    time_duration td = parse_delimited_time_duration<time_duration>(tod_string);
    //construct a time
    return time_type(d, td);

}

If you want a different date format parser, I made a slightly different implementation:

posix_time::ptime parse_dmy_time(const std::string &s, char sep) {
    typedef typename posix_time::ptime::time_duration_type time_duration;
    typedef typename posix_time::ptime::date_type date_type;

    //split date/time on a unique delimiter char such as ' ' or 'T'
    std::string date_string, tod_string;
    split(s, sep, date_string, tod_string);
    //call parse_date with first string
    auto d = parse_date<date_type>(date_string, ymd_order_dmy);
    //call parse_time_duration with remaining string
    auto td = parse_delimited_time_duration<time_duration>(tod_string);
    //construct a time
    return {d, td};
}


问:
Python function that takes lists and elements and makes one list
Hopefully an example could illustrate this better. I am creating a function that will take either a list of names, various lists of names, just a name or multiple names (not in a list) and make one list of them all (without importing... non-native libraries? I am ignorant here but I mean I want to use only what's already available in python).

```<code>def make_one_list(entry1, entry2, entry3 ...):
   #regardless of what is entered (well.. it has to be list or element)
   #extract elements from list and combine with single elements and...
   return one_big_list_of_all_elements

>>>make_one_list(['John','Mark'],'Mike',['Kate','Ally'],'Shawn','Marina'...)
['John','Mark','Mike','Kate','Ally','Shawn','Marina',...]
</code>```

My pseudo-code is not set in stone, obviously. I think, eventually, some input checking might be in order but not very pythonic in nature to do that. I am simply doing this as a personal communication function for my office.

THANKS!!

答:
We can do what you asked for by connecting all lists with (+)

```<code>def make_one_list(*args):
   result = []
   for i in args:
       if isinstance(i, list):
           result.append(list(i))
       else:
           result.append(i)
   return result

result = make_one_list(['John','Mark'], ['Kate','Ally'], ['Shawn','Marina'], 'Mike')
print(result)
</code>```

Body:
Hopefully an example could illustrate this better. I am creating a function that will take either a list of names, various lists of names, just a name or multiple names (not in a list) and make one list of them all (without importing... non-native libraries? I am ignorant here but I mean I want to use only what's already available in python).

def make_one_list(entry1, entry2, entry3 ...):
   #regardless of what is entered (well.. it has to be list or element)
   #extract elements from list and combine with single elements and...
   return one_big_list_of_all_elements

>>>make_one_list(['John','Mark'],'Mike',['Kate','Ally'],'Shawn','Marina'...)
['John','Mark','Mike','Kate','Ally','Shawn','Marina',...]

My pseudo-code is not set in stone, obviously. I think, eventually, some input checking might be in order but not very pythonic in nature to do that. I am simply doing this as a personal communication function for my office.

THANKS!!

Body:
We can do what you asked for by connecting all lists with (+)

def make_one_list(*args):
   result = []
   for i in args:
       if isinstance(i, list):
           result.append(list(i))
       else:
           result.append(i)
   return result

result = make_one_list(['John','Mark'], ['Kate','Ally'], ['Shawn','Marina'], 'Mike')
print(result)


问:
Fix a nested promise chain
I have an existing Promise chain that makes me very uncomfortable. I don't like nested callbacks, let alone nested promise chains. I have refactored it, but curious if it can be done better.

The reason for the refactor is that I need to add an additional functional call to this flow, right in the middle

EXISTING:

```<code>initFirestore()
  .then(() => {
    console.log('Firestore has been initialized.');
    seedServices()
      .then(customerId => {
// here is where my new function would need to live.
        seedFirestore()
          .then(() => {
            console.log('Seed created for Customer: ', customerId);
          })
          .catch(err => {
            console.log('Trouble seeding firestore with seedTemplates', err);
          });
      })
      .catch(customerId => {
        console.log('Seed created with warnings for  Customer: ', customerId);
      });
  })
  .catch(err => {
    throw new Error(err);
  });
</code>```

My Proposed update:

```<code>initFirestore()
  .then(() => {
    console.log('Firestore has been initialized.');
  })
  .catch(err => {
    throw new Error(err);
  })
  .then(() => seedServices())
  .then(customerId => customerId)
  .catch(err => {
    console.log('Trouble seeding firestore with seedTemplates', err);
  })
  .then(async customerId => {
    await myNewFunction().then(
      (response) => {
        console.log(response);
      }
    );
    return customerId;
  })
  .then(async customerId => {
    await seedFirestore();
    return customerId;
  })
  .then(customerId => {
    console.log('Seed created for Customer: ', customerId);
  })
  .catch(customerId => {
    console.log('Seed created with warnings for  Customer: ', customerId);
  });
</code>```

I'm not happy with the mixing of catch in the chain...How else could I do this?

答:
Actually what you are doing is ok, if you mean to catch errors, log a warning and then continue anyway.

This is the async/await equivalent:

```<code>let customerId;
try {

    try {
      await initFirestore()
      console.log('Firestore has been initialized.');
    } catch(err) {
      throw new Error(err);
    });

    try {
      customerId = await seedServices());
    } catch(err) {
      console.log('Trouble seeding firestore with seedTemplates', err);
    };

    const response = await myNewFunction();
    console.log(response);

    await seedFirestore();
    console.log('Seed created for Customer: ', customerId);

} catch (err) {
   console.log('Seed created with warnings for  Customer: ', customerId);
}
</code>```

What's strange here is:

Immediately re-throwing the error you got, wrapped in a new Error().

Using exceptions for warnings

And, you can probably clean up your code a bit by lifting the customerId variable outside the first then, so you don't have pass it around everywhere.

Edit there are problems with your code, not every path will correctly forward customerId to the next then() handler. If you want to use then()/catch() instead of async/await.

One question I would have is, do you really want to continue the operation even after seedServices fails. My guess is 'no', so that would cause me to rewrite your code to:

```<code>let customerId;

initFirestore()
  .then(() => {
    console.log('Firestore has been initialized.');
    return seedServices();
  })
  .then(cId => {
    customerId = cId;
    return myNewFunction();
  })
  .then(() => seedFireStore());
  .then(() => {
    console.log('Seed created for Customer: ', customerId);
  })
  .catch(customerId => {
    console.log('Error while creating seed for customer ', customerId);
  });
</code>```

async/await equivalent:

```<code>let customerId;

try {
  await initFirestore()
  const customerId = await seedServices();
  await myNewFunction();
  await seedFireStore());

  console.log('Seed created for Customer: ', customerId);

} catch(err) {
  console.log('Error while creating seed for customer ', customerId);
});
</code>```

If you did mean to catch errors and continue anyway (after seedServices), my recommendation would be to split your operations in a few different functions. This is always nicer than nesting your promise chains.

Title: Fix a nested promise chain

Body:
I have an existing Promise chain that makes me very uncomfortable. I don't like nested callbacks, let alone nested promise chains. I have refactored it, but curious if it can be done better.

The reason for the refactor is that I need to add an additional functional call to this flow, right in the middle

EXISTING:

initFirestore()
  .then(() => {
    console.log('Firestore has been initialized.');
    seedServices()
      .then(customerId => {
// here is where my new function would need to live.
        seedFirestore()
          .then(() => {
            console.log('Seed created for Customer: ', customerId);
          })
          .catch(err => {
            console.log('Trouble seeding firestore with seedTemplates', err);
          });
      })
      .catch(customerId => {
        console.log('Seed created with warnings for  Customer: ', customerId);
      });
  })
  .catch(err => {
    throw new Error(err);
  });

My Proposed update:

initFirestore()
  .then(() => {
    console.log('Firestore has been initialized.');
  })
  .catch(err => {
    throw new Error(err);
  })
  .then(() => seedServices())
  .then(customerId => customerId)
  .catch(err => {
    console.log('Trouble seeding firestore with seedTemplates', err);
  })
  .then(async customerId => {
    await myNewFunction().then(
      (response) => {
        console.log(response);
      }
    );
    return customerId;
  })
  .then(async customerId => {
    await seedFirestore();
    return customerId;
  })
  .then(customerId => {
    console.log('Seed created for Customer: ', customerId);
  })
  .catch(customerId => {
    console.log('Seed created with warnings for  Customer: ', customerId);
  });

I'm not happy with the mixing of catch in the chain...How else could I do this?

Body:
Actually what you are doing is ok, if you mean to catch errors, log a warning and then continue anyway.

This is the async/await equivalent:

let customerId;
try {

    try {
      await initFirestore()
      console.log('Firestore has been initialized.');
    } catch(err) {
      throw new Error(err);
    });

    try {
      customerId = await seedServices());
    } catch(err) {
      console.log('Trouble seeding firestore with seedTemplates', err);
    };

    const response = await myNewFunction();
    console.log(response);

    await seedFirestore();
    console.log('Seed created for Customer: ', customerId);

} catch (err) {
   console.log('Seed created with warnings for  Customer: ', customerId);
}

What's strange here is:

Immediately re-throwing the error you got, wrapped in a new Error().

Using exceptions for warnings

And, you can probably clean up your code a bit by lifting the customerId variable outside the first then, so you don't have pass it around everywhere.

Edit there are problems with your code, not every path will correctly forward customerId to the next then() handler. If you want to use then()/catch() instead of async/await.

One question I would have is, do you really want to continue the operation even after seedServices fails. My guess is 'no', so that would cause me to rewrite your code to:

let customerId;

initFirestore()
  .then(() => {
    console.log('Firestore has been initialized.');
    return seedServices();
  })
  .then(cId => {
    customerId = cId;
    return myNewFunction();
  })
  .then(() => seedFireStore());
  .then(() => {
    console.log('Seed created for Customer: ', customerId);
  })
  .catch(customerId => {
    console.log('Error while creating seed for customer ', customerId);
  });

async/await equivalent:

let customerId;

try {
  await initFirestore()
  const customerId = await seedServices();
  await myNewFunction();
  await seedFireStore());

  console.log('Seed created for Customer: ', customerId);

} catch(err) {
  console.log('Error while creating seed for customer ', customerId);
});

If you did mean to catch errors and continue anyway (after seedServices), my recommendation would be to split your operations in a few different functions. This is always nicer than nesting your promise chains.


问:
How can I create a URL based on controller and action method in Spring MVC?
I am using Spring MVC 3.0

I have a guestbook.jsp page where I want to create a link that points to GuestBookController's login method.

This is a simple task that most web frameworks handle this (e.g grails does it with g:link tag) but I couldn't find any documentation on this in the official SpringMVC docs.

So I am scratching my head - Is this functionality in some tag library? Does the framework expose it? Do I have to extend the framework to get this to work?

Note, I am not taking about hardcoding the url (which is an obvious but weak solution) but rather generating it based on controller and action name.

UPDATE:
Spring MVC doesn't provide this functionality. There is a JIRA ticket though. You can vote here https://jira.springsource.org/browse/SPR-5779

答:
Annotate your login method with @RequestMapping, like so:

```<code>@Controller
public class GuestBookController {
  ...
  @RequestMapping(value="/mycontextroot/login", method = RequestMethod.GET)
  public String login() {
    ...
  }
  ...
}
</code>```

Then, in your JSP, create a link something like this:

```<code><c:url var="loginlink" value="/mycontextroot/login.html">
</c:url>
<a href="${loginlink}">Login</a>
</code>```

This assumes that your dispatcher servlet is looking for *.html URLs.

Body:
Annotate your login method with @RequestMapping, like so:

@Controller
public class GuestBookController {
  ...
  @RequestMapping(value="/mycontextroot/login", method = RequestMethod.GET)
  public String login() {
    ...
  }
  ...
}

Then, in your JSP, create a link something like this:

<c:url var="loginlink" value="/mycontextroot/login.html">
</c:url>
<a href="${loginlink}">Login</a>

This assumes that your dispatcher servlet is looking for *.html URLs.


问:
Difference between two groups, data processing
I have this dataprocessing problem where I want to count the difference in goals between two teams in different matches. The data looks like this:

```<code>    matchId teamId   eventSec
1   2799331   6718  443.55984
2   2799331   6726 1152.62584
3   2799331   6718 2113.82370
4   2799331   6718 2066.28793
5   2799332   6710 1001.35775
6   2799332   6721 2469.32876
7   2799333   6734  744.35563
</code>```

So one of these lines represents a goal scored by a team, and matchId represents the match, teamId the teams in the match and eventSec the time of the goal. What i want to accomplish is a variable for each row that shows the difference in score, so the first row in this example data should have a goal difference of 1, row two should have goal difference by 0, row three a goal difference by 1, etc.

I want to apply this to a big dataset with alot of different match and teamIds, so I need a pretty general solution to solve this. I've tried different dplyr solutions but gotten stuck a million times and would really like some help.

Thanks alot in advance!

答:
I hope I am following your logic correctly, let me know.

```<code>library(tidyverse)

df %>%
  group_by(matchId) %>%
  mutate(point = if_else(teamId == first(teamId), 1, -1),
         goal_diff = cumsum(point))
</code>```

In addition, if you want to get the score for each match, you could add:

```<code>group_by(matchId, teamId) %>%
summarise(score = sum(abs(point)))
</code>```

Output

```<code># A tibble: 7 x 5
# Groups:   matchId [3]
  matchId teamId eventSec point goal_diff
    <int>  <int>    <dbl> <dbl>     <dbl>
1 2799331   6718     444.     1         1
2 2799331   6726    1153.    -1         0
3 2799331   6718    2114.     1         1
4 2799331   6718    2066.     1         2
5 2799332   6710    1001.     1         1
6 2799332   6721    2469.    -1         0
7 2799333   6734     744.     1         1
</code>```

Body:
I have this dataprocessing problem where I want to count the difference in goals between two teams in different matches. The data looks like this:

    matchId teamId   eventSec
1   2799331   6718  443.55984
2   2799331   6726 1152.62584
3   2799331   6718 2113.82370
4   2799331   6718 2066.28793
5   2799332   6710 1001.35775
6   2799332   6721 2469.32876
7   2799333   6734  744.35563

So one of these lines represents a goal scored by a team, and matchId represents the match, teamId the teams in the match and eventSec the time of the goal. What i want to accomplish is a variable for each row that shows the difference in score, so the first row in this example data should have a goal difference of 1, row two should have goal difference by 0, row three a goal difference by 1, etc.

I want to apply this to a big dataset with alot of different match and teamIds, so I need a pretty general solution to solve this. I've tried different dplyr solutions but gotten stuck a million times and would really like some help.

Thanks alot in advance!

Body:
I hope I am following your logic correctly, let me know.

library(tidyverse)

df %>%
  group_by(matchId) %>%
  mutate(point = if_else(teamId == first(teamId), 1, -1),
         goal_diff = cumsum(point))

In addition, if you want to get the score for each match, you could add:

group_by(matchId, teamId) %>%
summarise(score = sum(abs(point)))

Output

# A tibble: 7 x 5
# Groups:   matchId [3]
  matchId teamId eventSec point goal_diff
    <int>  <int>    <dbl> <dbl>     <dbl>
1 2799331   6718     444.     1         1
2 2799331   6726    1153.    -1         0
3 2799331   6718    2114.     1         1
4 2799331   6718    2066.     1         2
5 2799332   6710    1001.     1         1
6 2799332   6721    2469.    -1         0
7 2799333   6734     744.     1         1


问:
Column-wise modeling in Gurobi using java
Is there a way to use a column-wise approach creating models in Gurobi? Using the java API, is possible to create columns (GRBColumn type) and you have to add constraints for each column. However, to create constraints, you must refer to a variable in some way. Wasn't the idea to create variables in the end, passing the columns created as parameters?</p>

答:
You can build a model columnwise using addVars and the GRBColumn object.

Don't forget to set the right hand sides for the constraints as well.


问:
API Connection is failing with 'Forbidden'
I have a logic app inside an ISE which uses an API Connection to write to my storage account. Both ISE and storage account are in the same private VNet and my storage account has firewall rules enabled for each subnet of the ISE. Even so, all requests to the logic app fail to write to blob storage with the error:

```<code>{
  "status": 403,
  "message": "This request is not authorized to perform this operation.\r\nclientRequestId: ...",
  "error": {
    "message": "This request is not authorized to perform this operation."
  },
  "source": "azureblob-cus.azconn-cus.p.azurewebsites.net"
}
</code>```

If I disable the blob storage firewall rules, it can write to the storage account. Why can my logic app-inside the ISE which has firewall rules configured for the storage account-not write to my storage account?

答:
I figured it out. I was creating my API connections against the publicly available blob storage service rather than the managed connector inside my ISE. Instead of having

```<code>{
    "type": "Microsoft.Web/connections",
    "apiVersion": "2016-06-01",
    "location": "[resourceGroup().location]",
    "name": "[parameters('BackupStorageAccountName')]",
    "properties": {
        ...
        "api": {
            "id": "[concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Web/locations/', resourceGroup().location, '/managedApis/azureblob')]"
        }
    }
}
</code>```

I needed to have

```<code>{
    "type": "Microsoft.Web/connections",
    "apiVersion": "2016-06-01",
    "location": "[resourceGroup().location]",
    "name": "[parameters('BackupStorageAccountName')]",
    "properties": {
        ...
        "api": {
            "id": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', resourceGroup().name, '/providers/Microsoft.Logic/integrationServiceEnvironments/', parameters('iseName'), '/managedApis/azureblob')]"
        }
    }
}
</code>```

Body:
I have a logic app inside an ISE which uses an API Connection to write to my storage account. Both ISE and storage account are in the same private VNet and my storage account has firewall rules enabled for each subnet of the ISE. Even so, all requests to the logic app fail to write to blob storage with the error:

{
  "status": 403,
  "message": "This request is not authorized to perform this operation.\r\nclientRequestId: ...",
  "error": {
    "message": "This request is not authorized to perform this operation."
  },
  "source": "azureblob-cus.azconn-cus.p.azurewebsites.net"
}

If I disable the blob storage firewall rules, it can write to the storage account. Why can my logic app-inside the ISE which has firewall rules configured for the storage account-not write to my storage account?

Body:
I figured it out. I was creating my API connections against the publicly available blob storage service rather than the managed connector inside my ISE. Instead of having

{
    "type": "Microsoft.Web/connections",
    "apiVersion": "2016-06-01",
    "location": "[resourceGroup().location]",
    "name": "[parameters('BackupStorageAccountName')]",
    "properties": {
        ...
        "api": {
            "id": "[concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Web/locations/', resourceGroup().location, '/managedApis/azureblob')]"
        }
    }
}

I needed to have

{
    "type": "Microsoft.Web/connections",
    "apiVersion": "2016-06-01",
    "location": "[resourceGroup().location]",
    "name": "[parameters('BackupStorageAccountName')]",
    "properties": {
        ...
        "api": {
            "id": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', resourceGroup().name, '/providers/Microsoft.Logic/integrationServiceEnvironments/', parameters('iseName'), '/managedApis/azureblob')]"
        }
    }
}


答:
Use chain(iter1, iter2, ...), it is a native library. Though you need to handle the strings that are not in lists.

```<code>from itertools import chain

data = ['John','Mark'],'Mike',['Kate','Ally'],'Shawn','Marina'
r = chain(*[x if isinstance(x, list) else [x] for x in data])
print(list(r))
</code>```

Output:

```<code>['John', 'Mark', 'Mike', 'Kate', 'Ally', 'Shawn', 'Marina']
</code>```

Title: Python function that takes lists and elements and makes one list

Body:
Use chain(iter1, iter2, ...), it is a native library. Though you need to handle the strings that are not in lists.

from itertools import chain

data = ['John','Mark'],'Mike',['Kate','Ally'],'Shawn','Marina'
r = chain(*[x if isinstance(x, list) else [x] for x in data])
print(list(r))

Output:

['John', 'Mark', 'Mike', 'Kate', 'Ally', 'Shawn', 'Marina']


Title: Difference between two groups, data processing

Body:
Well, if your dataset is not like million rows, then try this:

x=structure(list(matchId = c(2799331L, 2799331L, 2799331L, 2799331L,
2799332L, 2799332L, 2799333L), teamId = c(6718L, 6726L, 6718L,
6718L, 6710L, 6721L, 6734L), eventSec = c(443.55984, 1152.62584,
2113.8237, 2066.28793, 1001.35775, 2469.32876, 744.35563)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7"))

library(dplyr)
x %>% group_by(matchId) %>% mutate(goalD=cumsum(ifelse(teamId==teamId[1],1,-1)))

# A tibble: 7 x 4
# Groups:   matchId [3]
  matchId teamId eventSec goalD
    <int>  <int>    <dbl> <dbl>
1 2799331   6718     444.     1
2 2799331   6726    1153.     0
3 2799331   6718    2114.     1
4 2799331   6718    2066.     2
5 2799332   6710    1001.     1
6 2799332   6721    2469.     0
7 2799333   6734     744.     1