问:
How to display the record with the highest value?
I'm new to python and would like to know how do I display the record with the highest value.

I already figured out how to display the largest value, but I want to display the value concatenated with name(id).

For now, I did the following:

```<code>import pandas as pd

data = pd.read_csv('datasets/kc_house_data.csv')
#what is the most expensive house (highest sale value)
print(max(data['price']))
</code>```

That way it's only displaying the value, I want to display the record.

I also tried as follows:

```<code>print(data[['id', 'price']].sort_values('price', ascending=False).head(1))
</code>```

This way it returned the name and value correctly, but I believe there is some way to do this using the max() function.

Can someone help me?

答:
As mentioned in the comments, you can do that with:

```<code> data['id'][data['price']==data['price'].max()]
</code>```

using the max function as needed.

Body:
I'm new to python and would like to know how do I display the record with the highest value.

I already figured out how to display the largest value, but I want to display the value concatenated with name(id).

For now, I did the following:

import pandas as pd

data = pd.read_csv('datasets/kc_house_data.csv')
#what is the most expensive house (highest sale value)
print(max(data['price']))

That way it's only displaying the value, I want to display the record.

I also tried as follows:

print(data[['id', 'price']].sort_values('price', ascending=False).head(1))

This way it returned the name and value correctly, but I believe there is some way to do this using the max() function.

Can someone help me?

Body:
As mentioned in the comments, you can do that with:

 data['id'][data['price']==data['price'].max()]

using the max function as needed.


来源: stackexchange

问:
Why cannot I set the value attribute of texarea by setAttribute?
```<code><textarea value="hello" id="id1"></textarea>
</code>```

The above textarea does not show "hello" in it.

document.getElementById('id1').setAttribute("value", "hello");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea value="hello" id="id1"></textarea></code>```

This textarea  does not show "hello", either. But the following one does show "hello" in it, why?

document.getElementById('id1').value = "hello";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea value="hello" id="id1"></textarea></code>```

The setAttribute works perfectly for <input> element:

document.getElementById('id1').setAttribute("value", "hello");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input value="" id="id1" /></code>```

答:
In DOM, input and textarea elements have a defaultValue property. This controls what is displayed in the element if the user doesn't type anything or if the form is reset.

For an input element the defaultValue property maps onto the value attribute.

For a textarea element the defaultValue property maps onto the text content of the element. textarea elements do not have a value attribute.

Both kinds of element have a value property which represents the current value.

That this has the same name as the input elements value attribute is unfortunate and a source of a fair bit of confusion.

ContentLicense: CC BY-SA 4.0

Body:
<textarea value="hello" id="id1"></textarea>

The above textarea does not show "hello" in it.

document.getElementById('id1').setAttribute("value", "hello");

<textarea value="hello" id="id1"></textarea>

This textarea  does not show "hello", either. But the following one does show "hello" in it, why?

document.getElementById('id1').value = "hello";

<textarea value="hello" id="id1"></textarea>

The setAttribute works perfectly for <input> element:

document.getElementById('id1').setAttribute("value", "hello");

<input value="" id="id1" />


问:
How to use neuralcoref in Spacy
I have been trying to use the library neuralcoref: State-of-the-art coreference resolution based on neural nets and spaCy. I am using Ubuntu 16.04, Python 3.7.3 in conda 1.9.7 and Spacy 2.2.4.

My code (from the https://spacy.io/universe/project/neuralcoref):

```<code>import spacy
import neuralcoref

nlp = spacy.load('en_core_web_sm')
neuralcoref.add_to_pipe(nlp)
doc1 = nlp('My sister has a dog. She loves him.')
print(doc1._.coref_clusters)

doc2 = nlp('Angela lives in Boston. She is quite happy in that city.')
for ent in doc2.ents:
    print(ent._.coref_cluster)
</code>```

I have got this error

```<code>/home/daniel/anaconda3/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: spacy.morphology.Morphology size changed, may indicate binary incompatibility. Expected 104 from C header, got 112 from PyObject
  return f(*args, **kwds)
/home/daniel/anaconda3/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: spacy.vocab.Vocab size changed, may indicate binary incompatibility. Expected 96 from C header, got 104 from PyObject
  return f(*args, **kwds)
/home/daniel/anaconda3/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: spacy.tokens.span.Span size changed, may indicate binary incompatibility. Expected 72 from C header, got 80 from PyObject
  return f(*args, **kwds)
</code>```

I have tried to downgrade the version of Spacy to 2.1.0 as suggested by this link:

```<code>conda config --append channels conda-forge
conda install spacy=2.1.0
</code>```

However, I am not able

```<code>PackagesNotFoundError: The following packages are not available from current channels:

  - spacy=2.1.0

Current channels:

  - https://conda.anaconda.org/conda-forge/linux-64
  - https://conda.anaconda.org/conda-forge/noarch
  - https://repo.anaconda.com/pkgs/main/linux-64
  - https://repo.anaconda.com/pkgs/main/noarch
  - https://repo.anaconda.com/pkgs/r/linux-64
  - https://repo.anaconda.com/pkgs/r/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.
</code>```

How can I solve this issue without downgrade? Is there any new updated version of neuralcoref?

答: This is not a direct answer to the question, but if you want to use neuralCoref, another option is to use the original version written in Java. The stanza library has a coreNLP client, which can access original coreNLP models. This doesn't require you to use (an outdated version of) Spacy.</p>

Title: How to use neuralcoref in Spacy

Body:
I have been trying to use the library neuralcoref: State-of-the-art coreference resolution based on neural nets and spaCy. I am using Ubuntu 16.04, Python 3.7.3 in conda 1.9.7 and Spacy 2.2.4.

My code (from the https://spacy.io/universe/project/neuralcoref):

import spacy
import neuralcoref

nlp = spacy.load('en_core_web_sm')
neuralcoref.add_to_pipe(nlp)
doc1 = nlp('My sister has a dog. She loves him.')
print(doc1._.coref_clusters)

doc2 = nlp('Angela lives in Boston. She is quite happy in that city.')
for ent in doc2.ents:
    print(ent._.coref_cluster)

I have got this error

/home/daniel/anaconda3/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: spacy.morphology.Morphology size changed, may indicate binary incompatibility. Expected 104 from C header, got 112 from PyObject
  return f(*args, **kwds)
/home/daniel/anaconda3/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: spacy.vocab.Vocab size changed, may indicate binary incompatibility. Expected 96 from C header, got 104 from PyObject
  return f(*args, **kwds)
/home/daniel/anaconda3/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: spacy.tokens.span.Span size changed, may indicate binary incompatibility. Expected 72 from C header, got 80 from PyObject
  return f(*args, **kwds)

I have tried to downgrade the version of Spacy to 2.1.0 as suggested by this link:

conda config --append channels conda-forge
conda install spacy=2.1.0

However, I am not able

PackagesNotFoundError: The following packages are not available from current channels:

  - spacy=2.1.0

Current channels:

  - https://conda.anaconda.org/conda-forge/linux-64
  - https://conda.anaconda.org/conda-forge/noarch
  - https://repo.anaconda.com/pkgs/main/linux-64
  - https://repo.anaconda.com/pkgs/main/noarch
  - https://repo.anaconda.com/pkgs/r/linux-64
  - https://repo.anaconda.com/pkgs/r/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.

How can I solve this issue without downgrade? Is there any new updated version of neuralcoref?


问:
(Vulkan 1.0 APIs missing from instance) when launching Android Emulator(Q API 29) via Android Studio 3.5 and 3.6 Canary 9
I created three AVDs base on Android Q (API 29), using these system images:

 Android 10(Google Play), Android 10(Google APIs), Android 10.

All of these emulators failed to launch.
With the following error:

```<code>18:38   Emulator: VK_VERSION_1_0 check failed: vkCreateInstance not found

18:38   Emulator: VK_VERSION_1_0 check failed: vkEnumerateInstanceExtensionProperties not found

18:38   Emulator: VK_VERSION_1_0 check failed: vkEnumerateInstanceLayerProperties not found

18:38   Emulator: createOrGetGlobalVkEmulation: Warning: Vulkan 1.0 APIs missing from instance

18:38   Emulator: Process finished with exit code 0
</code>```

I have referred to this link:

Emulator: Unexpected feature list: MultiDisplay VulkanNullOptionalStrings YUV420888toNV21 YUVCache

But this issue is different from my issue.

I tried in Android Studio 3.5, and Android Studio 3.6 Canary 9, the latest version in stable and preview channel. Both end with the same result.

https://source.android.google.cn/devices/graphics/implement-vulkan

According to this page, Vulkan 1.0 should already exists since Android 7.0, I have no idea why Vulkan 1.0 is missing on Android 10.

Or should I just wait for the newer version of system image after Google officially release Android 10?

答:
Windows

Had to manually install Nvidia Drivers, in order to update Vulkan Runtime. (Nvidia Gforce Experience not needed)

Body:
I created three AVDs base on Android Q (API 29), using these system images:

 Android 10(Google Play), Android 10(Google APIs), Android 10.

All of these emulators failed to launch.
With the following error:

18:38   Emulator: VK_VERSION_1_0 check failed: vkCreateInstance not found

18:38   Emulator: VK_VERSION_1_0 check failed: vkEnumerateInstanceExtensionProperties not found

18:38   Emulator: VK_VERSION_1_0 check failed: vkEnumerateInstanceLayerProperties not found

18:38   Emulator: createOrGetGlobalVkEmulation: Warning: Vulkan 1.0 APIs missing from instance

18:38   Emulator: Process finished with exit code 0

I have referred to this link:

Emulator: Unexpected feature list: MultiDisplay VulkanNullOptionalStrings YUV420888toNV21 YUVCache

But this issue is different from my issue.

I tried in Android Studio 3.5, and Android Studio 3.6 Canary 9, the latest version in stable and preview channel. Both end with the same result.

https://source.android.google.cn/devices/graphics/implement-vulkan

According to this page, Vulkan 1.0 should already exists since Android 7.0, I have no idea why Vulkan 1.0 is missing on Android 10.

Or should I just wait for the newer version of system image after Google officially release Android 10?


问:
What is the practical use of the identity function in R?
Base R defines an identity function, a trivial identity function returning its argument (quoting from ?identity).

It is defined as :

```<code>identity <- function (x){x}
</code>```

Why would such a trivial function ever be useful?  Why would it be included in base R?

答: Don't know about R, but in a functional language one often passes functions as arguments to other functions. In such cases, the constant function (which returns the same value for any argument) and the identity function play a similar role as 0 and 1 in multiplication, so  to speak.</p>

ContentLicense: CC BY-SA 3.0

Body:
Base R defines an identity function, a trivial identity function returning its argument (quoting from ?identity).

It is defined as :

identity <- function (x){x}

Why would such a trivial function ever be useful?  Why would it be included in base R?


问:
How to create file directory from reading spreadsheet in apps script
I have managed to record a folder's file/folder directory into a Google Sheet. From this Google Sheet I would like to copy this folder structure by reading each row.

Google Sheet Link: https://docs.google.com/spreadsheets/d/1qgDd8PEmHSYz5IsN9banYBjbmAyoLLVe3WMnOvmHdlE/edit?usp=sharing

```<code>function copyFolderTree() {
  const sourceFolderId = '1uTGq2MRHzbev23sQzzFCi3Pl-v-ntMql';
  const sourceFolder = DriveApp.getFolderById(sourceFolderId).getName();
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName('Sheet1');
  const data = ws.getDataRange().getValues();
  range.shift()
  const destinationRootFolder = DriveApp.createFolder(`${sourceFolder}`)

  data.forEach(function(row){
    Logger.log(row)
    let depth = row[4]
    if (row[4] === depth && row[2] === 'Folder') {
      Logger.log(`Name of folder is currently ${row[4]}`)
      Logger.log(`Depth is currently ${row[4]}`)
      Logger.log(`Type is currently ${row[2]}`)
      destinationRootFolder.createFolder(row[0])
      row.push('hello')
      Logger.log(row)
      range.setValues(values);
    }
    })
}

I realise this is the incorrect thinking. Do I need to place the newly created folder into it's copied parent folder using the folder's name?

Thank you,

  [1]: https://docs.google.com/spreadsheets/d/1qgDd8PEmHSYz5IsN9banYBjbmAyoLLVe3WMnOvmHdlE/edit?usp=sharing
</code>```

答:
For folder tree, you can try</p>
```<code>function copyFolderTree() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName('Sheet1');
  const range = ws.getDataRange();
  const values= range.getValues();
  var levels = []
  values.forEach(r => {
    if (r[2]=='Folder'){
      if (r[4]==0){ // root
        var dossier = DriveApp.createFolder(r[0]);
        levels[1] = dossier.getId(); // specific correction as 1 doesn't exists in the example provided
      }
      else {
        var parent = DriveApp.getFolderById(levels[r[4]-1]);
        var dossier = parent.createFolder(r[0]);
        levels[r[4]] = dossier.getId();
      }
    }
  })
}
</code>```

Body:
I have managed to record a folder's file/folder directory into a Google Sheet. From this Google Sheet I would like to copy this folder structure by reading each row.

Google Sheet Link: https://docs.google.com/spreadsheets/d/1qgDd8PEmHSYz5IsN9banYBjbmAyoLLVe3WMnOvmHdlE/edit?usp=sharing

function copyFolderTree() {
  const sourceFolderId = '1uTGq2MRHzbev23sQzzFCi3Pl-v-ntMql';
  const sourceFolder = DriveApp.getFolderById(sourceFolderId).getName();
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName('Sheet1');
  const data = ws.getDataRange().getValues();
  range.shift()
  const destinationRootFolder = DriveApp.createFolder(`${sourceFolder}`)

  data.forEach(function(row){
    Logger.log(row)
    let depth = row[4]
    if (row[4] === depth && row[2] === 'Folder') {
      Logger.log(`Name of folder is currently ${row[4]}`)
      Logger.log(`Depth is currently ${row[4]}`)
      Logger.log(`Type is currently ${row[2]}`)
      destinationRootFolder.createFolder(row[0])
      row.push('hello')
      Logger.log(row)
      range.setValues(values);
    }
    })
}

I realise this is the incorrect thinking. Do I need to place the newly created folder into it's copied parent folder using the folder's name?

Thank you,

  [1]: https://docs.google.com/spreadsheets/d/1qgDd8PEmHSYz5IsN9banYBjbmAyoLLVe3WMnOvmHdlE/edit?usp=sharing

Body:
For folder tree, you can try

function copyFolderTree() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName('Sheet1');
  const range = ws.getDataRange();
  const values= range.getValues();
  var levels = []
  values.forEach(r => {
    if (r[2]=='Folder'){
      if (r[4]==0){ // root
        var dossier = DriveApp.createFolder(r[0]);
        levels[1] = dossier.getId(); // specific correction as 1 doesn't exists in the example provided
      }
      else {
        var parent = DriveApp.getFolderById(levels[r[4]-1]);
        var dossier = parent.createFolder(r[0]);
        levels[r[4]] = dossier.getId();
      }
    }
  })
}


问:
Setting values and handling concurrency in EF 6
I am using EF 6.1 and my service update method looks like so

```<code>public async override Task<int> UpdateAsync(Module updated)
{
    var entity = await _context.Modules
        .Where(e => e.Id == updated.Id)
        .FirstOrDefaultAsync();

    // update existing values
    _context.Entry(entity).CurrentValues.SetValues(updated);

    // do not update
    _context.SetModified(entity, "AddOnlyProperty", false);

    return await base.UpdateAsync(entity);
}
</code>```

My base UpdateAsync looks like so

```<code>public async virtual Task<int> UpdateAsync(T updated)
{
    var results = await ValidateAsync(updated);

    if (!results.IsValid)
    {
        throw new ValidationException(results.Errors);
    }

    if (_context.GetState(updated) == EntityState.Detached)
    {
        _context.Set<T>().Attach(updated);
        _context.SetState(updated, EntityState.Modified);
    }

    // we do not want the createdDate to change when an update is being done
    _context.SetModified(updated, "CreatedDate", false);
    _context.SetModified(updated, "CreatedByUserId", false);

    return await _context.SaveChangesAsync();
}
</code>```

This method is very simple, it copies the changes from updated into the entity, that way EF will only apply the changes needed when it creates the SQL.

My problem is that concurrency doesnt seem to be working, i would expect a DbConcurrencyException to be thrown?

Here is my basic Module object

```<code>public class Module : EntityBase, IEntityVersion, IEntityDelete
{
    public long Id { get; set; }

    public string Name { get; set; }

    public byte[] RowVersion { get; set; }
}
</code>```

I have configured RowVersion as a rowVersion field in my Module.config file, like so

```<code>this.Property(e => e.RowVersion)
    .IsRowVersion();
</code>```

Now when i perform an update with an old rowVersion value, the update seems to still take place?  Have i missed a configuration setting or am i doing this wrong?

Should an exception be thrown, or should i be checking if the rowVersion values match myself?

答:
You must add this to force ef to add condition for checking RowVersion on update.</p>
```<code>dbContext.Entry(entity).OriginalValues["RowVersion "] = yourCurrentRowVersion;
</code>```

Body:
I am using EF 6.1 and my service update method looks like so

public async override Task<int> UpdateAsync(Module updated)
{
    var entity = await _context.Modules
        .Where(e => e.Id == updated.Id)
        .FirstOrDefaultAsync();

    // update existing values
    _context.Entry(entity).CurrentValues.SetValues(updated);

    // do not update
    _context.SetModified(entity, "AddOnlyProperty", false);

    return await base.UpdateAsync(entity);
}

My base UpdateAsync looks like so

public async virtual Task<int> UpdateAsync(T updated)
{
    var results = await ValidateAsync(updated);

    if (!results.IsValid)
    {
        throw new ValidationException(results.Errors);
    }

    if (_context.GetState(updated) == EntityState.Detached)
    {
        _context.Set<T>().Attach(updated);
        _context.SetState(updated, EntityState.Modified);
    }

    // we do not want the createdDate to change when an update is being done
    _context.SetModified(updated, "CreatedDate", false);
    _context.SetModified(updated, "CreatedByUserId", false);

    return await _context.SaveChangesAsync();
}

This method is very simple, it copies the changes from updated into the entity, that way EF will only apply the changes needed when it creates the SQL.

My problem is that concurrency doesnt seem to be working, i would expect a DbConcurrencyException to be thrown?

Here is my basic Module object

public class Module : EntityBase, IEntityVersion, IEntityDelete
{
    public long Id { get; set; }

    public string Name { get; set; }

    public byte[] RowVersion { get; set; }
}

I have configured RowVersion as a rowVersion field in my Module.config file, like so

this.Property(e => e.RowVersion)
    .IsRowVersion();

Now when i perform an update with an old rowVersion value, the update seems to still take place?  Have i missed a configuration setting or am i doing this wrong?

Should an exception be thrown, or should i be checking if the rowVersion values match myself?

Body:
You must add this to force ef to add condition for checking RowVersion on update.

dbContext.Entry(entity).OriginalValues["RowVersion "] = yourCurrentRowVersion;


问:
How do I select from IF(....) as 'A'
Sorry I Don't know what to say it.
It was like</p>
```<code>SELECT

(IF(ISNULL(fieldA),'it is null','fieldA')) AS 'I_want_this',

'I_want_this' as 'Show'

from table
</code>```

答:
Is it:

```<code>select
   case when fieldA is NULL then 'It is null' else fieldA as I_Want_This
from Table
</code>```

?

Title: How do I select from IF(....) as 'A'

Body:
Sorry I Don't know what to say it.
It was like

SELECT

(IF(ISNULL(fieldA),'it is null','fieldA')) AS 'I_want_this',

'I_want_this' as 'Show'

from table

Body:
Is it:

select
   case when fieldA is NULL then 'It is null' else fieldA as I_Want_This
from Table

?


问:
i stuck in leetcode problem 151. Reverse Words in a String
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.

class Solution {

public:

    string reverseWords(string s) {
        string ans;
        int i =0;
        int n = s.size();
        while(i<n)
        {
            while(i<n and s[i]==' ')
                i++;
            if(i>=n)
                break;
            int j =i+1;
            while(j<n and s[j]!=' ')
                j++;
            string word = s.substr(i,j-1);
            if(ans.size()==0)
                ans = word;
            else
                ans = word + " "+ ans;
            i = j+1;

        }
        return ans;
    }
};
```

Expected output-"blue is sky the"
my output-"blue is blue sky is th"

答:
You have only one small typo in your code.

The line

```<code>        string word = s.substr(i,j-1);
</code>```

should be

```<code>std::string word = s.substr(i, j - i);
</code>```

So you mixed up i with 1.

No big deal.

```<code>#include <string>
#include <iostream>

std::string reverseWords(std::string s) {
    std::string ans;
    int i = 0;
    int n = s.size();
    while (i < n)
    {
        while (i < n and s[i] == ' ')
            i++;
        if (i >= n)
            break;
        int j = i + 1;
        while (j < n and s[j] != ' ')
            j++;
        std::string word = s.substr(i, j - i);
        if (ans.size() == 0)
            ans = word;
        else
            ans = word + " " + ans;
        i = j + 1;

    }
    return ans;
}
int main() {
    std::cout << reverseWords("ab cd ef");
}
</code>```

Body:
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.

class Solution {

public:

    string reverseWords(string s) {
        string ans;
        int i =0;
        int n = s.size();
        while(i<n)
        {
            while(i<n and s[i]==' ')
                i++;
            if(i>=n)
                break;
            int j =i+1;
            while(j<n and s[j]!=' ')
                j++;
            string word = s.substr(i,j-1);
            if(ans.size()==0)
                ans = word;
            else
                ans = word + " "+ ans;
            i = j+1;

        }
        return ans;
    }
};

Expected output-"blue is sky the"
my output-"blue is blue sky is th"

Body:
You have only one small typo in your code.

The line

        string word = s.substr(i,j-1);

should be

std::string word = s.substr(i, j - i);

So you mixed up i with 1.

No big deal.

#include <string>
#include <iostream>

std::string reverseWords(std::string s) {
    std::string ans;
    int i = 0;
    int n = s.size();
    while (i < n)
    {
        while (i < n and s[i] == ' ')
            i++;
        if (i >= n)
            break;
        int j = i + 1;
        while (j < n and s[j] != ' ')
            j++;
        std::string word = s.substr(i, j - i);
        if (ans.size() == 0)
            ans = word;
        else
            ans = word + " " + ans;
        i = j + 1;

    }
    return ans;
}
int main() {
    std::cout << reverseWords("ab cd ef");
}


问:
Modal Bottom Sheet and Bloc
I get the following error when I run code similar to the below code: BlocProvider.of() called with a context that does not contain a Bloc.

To replicate

```<code>BlocProvider(
          create: (context) => getIt<TheBloc>()
          child: BlocBuilder<TheBloc, TheState>(
          build: (context, state) =>
          MaterialButton(
            onPressed: () => _showModal(context),
            child: const Text('SHOW BLOC MODAL'),
),
</code>```

...

```<code>void _showModal(BuildContext context) {
  showModalBottomSheet<void>(
    context: context,
    builder: (_) {
          return MaterialButton(
               onPressed() {
                       context.bloc<TheBloc>().add(
                         TheEvent.someEvent(),
                       );
               }
              child: Text('Press button to add event to bloc')
          );
    },
  );
}
</code>```

答:
Actually if you need this bloc only in bottom sheet and nowhere else, the better and cleaner solution is create the StatefullWidget for bottom sheet content, create the Bloc inside this widget in initState() work with bloc in build() method and free resources in dispose() method.

```<code>  showModalBottomSheet<void>(
    context: context,
    builder: (_) {
          return MyBottomSheet(); // your stateful widget
        );
    },
  );
</code>```

Using bloc like above guarantee that state of your bloc will be the same on each showModalBottomSheet call

Note. If you need to preserve state of bloc, you can try to use AutomaticKeepAliveClientMixin (did not tested)

Title: Modal Bottom Sheet and Bloc

Body:
I get the following error when I run code similar to the below code: BlocProvider.of() called with a context that does not contain a Bloc.

To replicate

BlocProvider(
          create: (context) => getIt<TheBloc>()
          child: BlocBuilder<TheBloc, TheState>(
          build: (context, state) =>
          MaterialButton(
            onPressed: () => _showModal(context),
            child: const Text('SHOW BLOC MODAL'),
),

...

void _showModal(BuildContext context) {
  showModalBottomSheet<void>(
    context: context,
    builder: (_) {
          return MaterialButton(
               onPressed() {
                       context.bloc<TheBloc>().add(
                         TheEvent.someEvent(),
                       );
               }
              child: Text('Press button to add event to bloc')
          );
    },
  );
}

Body:
Actually if you need this bloc only in bottom sheet and nowhere else, the better and cleaner solution is create the StatefullWidget for bottom sheet content, create the Bloc inside this widget in initState() work with bloc in build() method and free resources in dispose() method.

  showModalBottomSheet<void>(
    context: context,
    builder: (_) {
          return MyBottomSheet(); // your stateful widget
        );
    },
  );

Using bloc like above guarantee that state of your bloc will be the same on each showModalBottomSheet call

Note. If you need to preserve state of bloc, you can try to use AutomaticKeepAliveClientMixin (did not tested)


问:
Creating live updating display from multiple Google Sheets
I have updating results data in four Sheets within a Google Sheets spreadsheet. I want to display the live contents of each sheet in turn on an external display (screen/projector), with an update rate of 10 to 15 seconds between each change of sheet. I've been unable to find any complete solution to this.

Things I've looked at:

Copy the data from each page into Google Slides, maintaining live data update. Then publish the four slides, specifying a refresh rate. This works, but it doesn't update the Slides publication when data in the source Sheets changes. You have to go into Slides and do a manual refresh. Then you also have to refresh the webpage displaying the published slides. It does work, but I really want the displays to update as soon as data in the Sheets are updated.

Display the Google Sheets themselves, with a mechanism to select each sheet in turn every 10 seconds. This felt do-able, with a bit of AppsScript Java I can select individual sheets. Issues with this are I've been unable to resolve are the the minimum timer for a trigger is 1 minute, and I've been unable to get a Triggered function to select the sheets. I think the context for a Trigger may prevent this working.

Use 'something else' to extract the data from the Google Sheet, and create the live updating displays. I've been unable to find anything that would do this. I suspect someone with much better web coding than mine could achieve it, but I'm trying not to get too complicated.

Any suggestions greatfully received.

答:
You can create a local HTML file, show the spreadsheet inside an iframe and change the iframe-URL to the next
sheet every 15 seconds. This way, instead of using GAS triggers, the page gets updated using local JavaScript, so
you dont have to wait 1 minute.

Save the next code as an HTML file.

Update the spreadsheetUrl and sheetIds variables

Open the file in a browser (I recommend Firefox)

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>

     Your browser doesn't support iframes

```

Body:
You can create a local HTML file, show the spreadsheet inside an iframe and change the iframe-URL to the next
sheet every 15 seconds. This way, instead of using GAS triggers, the page gets updated using local JavaScript, so
you dont have to wait 1 minute.

Save the next code as an HTML file.

Update the spreadsheetUrl and sheetIds variables

Open the file in a browser (I recommend Firefox)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
</head>
<body>
    <iframe id="iframe1" src="" style="position:fixed; top:0; left:0; bottom:0; right:0; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"> Your browser doesn't support iframes
    </iframe>
</body>

<script>
    var spreadsheetUrl = "https://docs.google.com/spreadsheets/d/123/edit#gid=";
    var sheetIds = ["12345", "23456", "34567", "45678"];
    var currentSheet = 0; //0-3
    var myIframe = document.getElementById("iframe1");

    // Initializes iframe
    myIframe.src = spreadsheetUrl + sheetIds[currentSheet];

    // Updates iframe very 10,000 milliseconds
    setInterval(function() {
        // Increases sheet
        currentSheet++;

        // If 4th sheet has been shown, then go back to 1st sheet
        if (currentSheet > 3)
            currentSheet = 0;

        // Updates iframe
        myIframe.src = spreadsheetUrl + sheetIds[currentSheet];
    }, 10000);
</script>
</html>


问:
How do I get the name of the current executable in C#? (.NET 5 edition)
How do I get the name the executable was invoked as (equivalent to C's argv[0])? I actually need to handle somebody renaming the executable and stuff like that.

There's a famous question with lots of answers that don't work. Answers tried:

```<code>System.AppDomain.CurrentDomain.FriendlyName
</code>```

returns the name it was compiled as

```<code>System.Diagnostics.Process.GetCurrentProcess().ProcessName
</code>```

strips extension (ever rename a .exe to a .com?), also sees through symbolic links

```<code>Environment.GetCommandLineArgs()[0]
</code>```

It returns a name ending in .dll, clearly an error.

```<code>Assembly.GetEntryAssembly().Location
</code>```

Returns null

```<code>System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
</code>```

Returns a .dll name again.

The documentation for .net 5.0 says Environment.GetCommandLineArguments()[0] works; however it doesn't actually work. It somehow sees through symbolic links and returns the real executable name.

What I'm trying to do is link all of our stuff into a single multi-call binary so I can use the .net 5 framework reducer on the resulting binary so I don't have to ship about 30MB of .net 5 framework we're not using. I really don't want to do a platform ladder and P/Invoke a bunch of stuff unless I have to.

I'm after argv[0] directly, not the running process executable name. In the case of symbolic links, these differ.

答:
Came across this with .NET 6, where Process.GetCurrentProcess().MainModule?.FileName seems to be working fine now, and there's also Environment.ProcessPath.

If targeting Windows only, it might be safer (more predictable) to use interop. Below are some options, including the native GetModuleFileName and GetCommandLine:

using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;

Console.WriteLine("Process.GetCurrentProcess().MainModule?.FileName");
Console.WriteLine(Process.GetCurrentProcess().MainModule?.FileName);
Console.WriteLine();

Console.WriteLine("Assembly.GetExecutingAssembly().Location");
Console.WriteLine(Assembly.GetExecutingAssembly().Location);
Console.WriteLine();

Console.WriteLine("Environment.ProcessPath");
Console.WriteLine(Environment.ProcessPath);
Console.WriteLine();

Console.WriteLine("Environment.CommandLine");
Console.WriteLine(Environment.CommandLine);
Console.WriteLine();

Console.WriteLine("Environment.GetCommandLineArgs()[0]");
Console.WriteLine(Environment.GetCommandLineArgs()[0]);
Console.WriteLine();

Console.WriteLine("Win32.GetProcessPath()");
Console.WriteLine(Win32.GetProcessPath());
Console.WriteLine();

Console.WriteLine("Win32.GetProcessCommandLine()");
Console.WriteLine(Win32.GetProcessCommandLine());
Console.WriteLine();

public static class Win32
{
    private const int MAX_PATH = 260;
    private const int INSUFFICIENT_BUFFER = 0x007A;
    private const int MAX_UNICODESTRING_LEN = short.MaxValue;

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    private static extern IntPtr GetCommandLine();

    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    [PreserveSig]
    [return: MarshalAs(UnmanagedType.U4)]
    private static extern int GetModuleFileName(
        IntPtr hModule, StringBuilder lpFilename, [MarshalAs(UnmanagedType.U4)] int nSize);

    public static string GetProcessCommandLine()
    {
        return Marshal.PtrToStringUni(GetCommandLine()) ??
            throw new Win32Exception(nameof(GetCommandLine));
    }

    public static string GetProcessPath()
    {
        var buffer = new StringBuilder(MAX_PATH);
        while (true)
        {
            int size = GetModuleFileName(IntPtr.Zero, buffer, buffer.Capacity);
            if (size == 0)
            {
                throw new Win32Exception();
            }

            if (size == buffer.Capacity)
            {
                // double the buffer size and try again.
                buffer.EnsureCapacity(buffer.Capacity * 2);
                continue;
            }

            return Path.GetFullPath(buffer.ToString());
        }
    }
}
```
<p>The output when running via <code>dotnet run</code>:</p>
```
Process.GetCurrentProcess().MainModule?.FileName
C:\temp\ProcessPath\bin\Debug\net6.0\ProcessPath.exe

Assembly.GetExecutingAssembly().Location
C:\temp\ProcessPath\bin\Debug\net6.0\ProcessPath.dll

Environment.ProcessPath
C:\temp\ProcessPath\bin\Debug\net6.0\ProcessPath.exe

Environment.CommandLine
C:\temp\ProcessPath\bin\Debug\net6.0\ProcessPath.dll

Environment.GetCommandLineArgs()[0]
C:\temp\ProcessPath\bin\Debug\net6.0\ProcessPath.dll

Win32.GetProcessPath()
C:\temp\ProcessPath\bin\Debug\net6.0\ProcessPath.exe

Win32.GetProcessCommandLine()
"C:\temp\ProcessPath\bin\Debug\net6.0\ProcessPath.exe"
```
<p>Oh, and for a Windows Forms application, there always has been <code>Application.ExecutablePath</code>.</p>
<p><strong>Updated</strong>, running it on Ubuntu 22.04 with .NET 6.0.2 (with Win32 interop removed), either via <code>dotnet run</code> or directly as <code>./ProcessPath</code>:</p>
```
Process.GetCurrentProcess().MainModule?.FileName
/home/noseratio/ProcessPath/bin/Debug/net6.0/ProcessPath

Assembly.GetExecutingAssembly().Location
/home/noseratio/ProcessPath/bin/Debug/net6.0/ProcessPath.dll

Environment.ProcessPath
/home/noseratio/ProcessPath/bin/Debug/net6.0/ProcessPath

Environment.CommandLine
/home/noseratio/ProcessPath/bin/Debug/net6.0/ProcessPath.dll

Environment.GetCommandLineArgs()[0]
/home/noseratio/ProcessPath/bin/Debug/net6.0/ProcessPath.dll
```

Body:
How do I get the name the executable was invoked as (equivalent to C's argv[0])? I actually need to handle somebody renaming the executable and stuff like that.

There's a famous question with lots of answers that don't work. Answers tried:

System.AppDomain.CurrentDomain.FriendlyName

returns the name it was compiled as

System.Diagnostics.Process.GetCurrentProcess().ProcessName

strips extension (ever rename a .exe to a .com?), also sees through symbolic links

Environment.GetCommandLineArgs()[0]

It returns a name ending in .dll, clearly an error.

Assembly.GetEntryAssembly().Location

Returns null

System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName

Returns a .dll name again.

The documentation for .net 5.0 says Environment.GetCommandLineArguments()[0] works; however it doesn't actually work. It somehow sees through symbolic links and returns the real executable name.

What I'm trying to do is link all of our stuff into a single multi-call binary so I can use the .net 5 framework reducer on the resulting binary so I don't have to ship about 30MB of .net 5 framework we're not using. I really don't want to do a platform ladder and P/Invoke a bunch of stuff unless I have to.

I'm after argv[0] directly, not the running process executable name. In the case of symbolic links, these differ.

Body:
Came across this with .NET 6, where Process.GetCurrentProcess().MainModule?.FileName seems to be working fine now, and there's also Environment.ProcessPath.

If targeting Windows only, it might be safer (more predictable) to use interop. Below are some options, including the native GetModuleFileName and GetCommandLine:

using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;

Console.WriteLine("Process.GetCurrentProcess().MainModule?.FileName");
Console.WriteLine(Process.GetCurrentProcess().MainModule?.FileName);
Console.WriteLine();

Console.WriteLine("Assembly.GetExecutingAssembly().Location");
Console.WriteLine(Assembly.GetExecutingAssembly().Location);
Console.WriteLine();

Console.WriteLine("Environment.ProcessPath");
Console.WriteLine(Environment.ProcessPath);
Console.WriteLine();

Console.WriteLine("Environment.CommandLine");
Console.WriteLine(Environment.CommandLine);
Console.WriteLine();

Console.WriteLine("Environment.GetCommandLineArgs()[0]");
Console.WriteLine(Environment.GetCommandLineArgs()[0]);
Console.WriteLine();

Console.WriteLine("Win32.GetProcessPath()");
Console.WriteLine(Win32.GetProcessPath());
Console.WriteLine();

Console.WriteLine("Win32.GetProcessCommandLine()");
Console.WriteLine(Win32.GetProcessCommandLine());
Console.WriteLine();

public static class Win32
{
    private const int MAX_PATH = 260;
    private const int INSUFFICIENT_BUFFER = 0x007A;
    private const int MAX_UNICODESTRING_LEN = short.MaxValue;

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    private static extern IntPtr GetCommandLine();

    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    [PreserveSig]
    [return: MarshalAs(UnmanagedType.U4)]
    private static extern int GetModuleFileName(
        IntPtr hModule, StringBuilder lpFilename, [MarshalAs(UnmanagedType.U4)] int nSize);

    public static string GetProcessCommandLine()
    {
        return Marshal.PtrToStringUni(GetCommandLine()) ??
            throw new Win32Exception(nameof(GetCommandLine));
    }

    public static string GetProcessPath()
    {
        var buffer = new StringBuilder(MAX_PATH);
        while (true)
        {
            int size = GetModuleFileName(IntPtr.Zero, buffer, buffer.Capacity);
            if (size == 0)
            {
                throw new Win32Exception();
            }

            if (size == buffer.Capacity)
            {
                // double the buffer size and try again.
                buffer.EnsureCapacity(buffer.Capacity * 2);
                continue;
            }

            return Path.GetFullPath(buffer.ToString());
        }
    }
}

The output when running via dotnet run:

Process.GetCurrentProcess().MainModule?.FileName
C:\temp\ProcessPath\bin\Debug\net6.0\ProcessPath.exe

Assembly.GetExecutingAssembly().Location
C:\temp\ProcessPath\bin\Debug\net6.0\ProcessPath.dll

Environment.ProcessPath
C:\temp\ProcessPath\bin\Debug\net6.0\ProcessPath.exe

Environment.CommandLine
C:\temp\ProcessPath\bin\Debug\net6.0\ProcessPath.dll

Environment.GetCommandLineArgs()[0]
C:\temp\ProcessPath\bin\Debug\net6.0\ProcessPath.dll

Win32.GetProcessPath()
C:\temp\ProcessPath\bin\Debug\net6.0\ProcessPath.exe

Win32.GetProcessCommandLine()
"C:\temp\ProcessPath\bin\Debug\net6.0\ProcessPath.exe"

Oh, and for a Windows Forms application, there always has been Application.ExecutablePath.

Updated, running it on Ubuntu 22.04 with .NET 6.0.2 (with Win32 interop removed), either via dotnet run or directly as ./ProcessPath:

Process.GetCurrentProcess().MainModule?.FileName
/home/noseratio/ProcessPath/bin/Debug/net6.0/ProcessPath

Assembly.GetExecutingAssembly().Location
/home/noseratio/ProcessPath/bin/Debug/net6.0/ProcessPath.dll

Environment.ProcessPath
/home/noseratio/ProcessPath/bin/Debug/net6.0/ProcessPath

Environment.CommandLine
/home/noseratio/ProcessPath/bin/Debug/net6.0/ProcessPath.dll

Environment.GetCommandLineArgs()[0]
/home/noseratio/ProcessPath/bin/Debug/net6.0/ProcessPath.dll


问:
Calculating hours and minutes in python
I have a task in which i need to calculate the runtime of a marathon.
I'm given this as a start point

```<code>start_hour = 3
start_minute = 48
length = 172
</code>```

Basically the start is at 3:48 and it continues for 172 minutes.
My task is to find when the marathon ends.The endtime should look like this format 3:48 with minutes and hour converted to string and put together with ":".
I have spent like 1 and a half hour and i still can't manage to solve it.
This is what i have come out with:

```<code>endhour = start_hour + (length // 60)
endminute = start_minute + (length % 60)
end_minutee = endminute % 60
format(endhour)
endhourAsStr = str(endhour)
end_minuteeAsStr = str(end_minutee)
print(endhourAsStr + ":" + end_minuteeAsStr)
</code>```

But when i print the final hour is shorter then it should be with 1 hour.
I'm guessing that i need to do something with the > or < but i really can't figure it out.I guess that i only need that final push.
offtopic: I'm very new to proggraming i don't have experience whatsoever.

答:
```<code>hour = int(input("Starting time (hours): "))
mins = int(input("Starting time (minutes): "))
dura = int(input("Event duration (minutes): "))
new_hour=int((hour+round((dura/60)))%12)
new_mins=int((mins+(dura%60))%60)
print(new_hour,":",new_mins)
</code>```

Title: Calculating hours and minutes in python

Body:
I have a task in which i need to calculate the runtime of a marathon.
I'm given this as a start point

start_hour = 3
start_minute = 48
length = 172

Basically the start is at 3:48 and it continues for 172 minutes.
My task is to find when the marathon ends.The endtime should look like this format 3:48 with minutes and hour converted to string and put together with ":".
I have spent like 1 and a half hour and i still can't manage to solve it.
This is what i have come out with:

endhour = start_hour + (length // 60)
endminute = start_minute + (length % 60)
end_minutee = endminute % 60
format(endhour)
endhourAsStr = str(endhour)
end_minuteeAsStr = str(end_minutee)
print(endhourAsStr + ":" + end_minuteeAsStr)

But when i print the final hour is shorter then it should be with 1 hour.
I'm guessing that i need to do something with the > or < but i really can't figure it out.I guess that i only need that final push.
offtopic: I'm very new to proggraming i don't have experience whatsoever.


问:
Confusion about require and import
I am confused about require and import in node.js.

Some modules use require and some use import can we use only one or the other for all modules?

答:
Yes, you can exclusively use import statements to load modules.

You must configure Node to use the ESM loader. The most common method of doing this is setting the "type" field in package.json to "module":

// package.json
{
  "type": "module"
}
```

See Determining the module system in the docs.

Title: Confusion about require and import

Body:
Yes, you can exclusively use import statements to load modules.

You must configure Node to use the ESM loader. The most common method of doing this is setting the "type" field in package.json to "module":

// package.json
{
  "type": "module"
}

See Determining the module system in the docs.


问:
JavaScript parseInt not working with "10"?
I wrote the function that tokenizes arithmetic string expression into an array of tokens, such as numbers and operators. Everything's fine but I get a weird results when dealing with strings containing "10". Here's the code:

function tokenizeString(expressionString) {
    const tokenArray = [];

    let token = "";
    for (let i = 0; i < expressionString.length; i++) {
        if (parseInt(expressionString[i])) {
            token += expressionString[i];
        } else {
            tokenArray.push(parseInt(token));
            token = "";
            tokenArray.push(expressionString[i]);
        }
    }

    if (token !== "") {
        tokenArray.push(parseInt(token));
    }

    return tokenArray;
}

console.log(tokenizeString("14+2/8")); // [14, "+", 2, "/", 8]
console.log(tokenizeString("10+1")); // [1, '0', NaN, '-', 3] ??```

For now I can't come up with an idea, why this happens.

答:
Instead of parseInt in the
if(parseInt(expressionString[i])){}
you could use isNaN() to check if the string is number or not
isNaN() returns true if not a number so your if would
be
if (!isNaN(expressionString[i])){}

function tokenizeString(expressionString) {
    const tokenArray = [];

    let token = "";
    for (let i = 0; i < expressionString.length; i++) {
        if (!isNaN(expressionString[i])) {
            token += expressionString[i];
        } else {
            tokenArray.push(parseInt(token));
            token = "";
            tokenArray.push(expressionString[i]);
        }
    }

    if (token !== "") {
        tokenArray.push(parseInt(token));
    }

    return tokenArray;
}

console.log(tokenizeString("14+2/8")); // [14, "+", 2, "/", 8]
console.log(tokenizeString("10+1")); // [10, '+', 1] ??```

Body:
I wrote the function that tokenizes arithmetic string expression into an array of tokens, such as numbers and operators. Everything's fine but I get a weird results when dealing with strings containing "10". Here's the code:

function tokenizeString(expressionString) {
    const tokenArray = [];

    let token = "";
    for (let i = 0; i < expressionString.length; i++) {
        if (parseInt(expressionString[i])) {
            token += expressionString[i];
        } else {
            tokenArray.push(parseInt(token));
            token = "";
            tokenArray.push(expressionString[i]);
        }
    }

    if (token !== "") {
        tokenArray.push(parseInt(token));
    }

    return tokenArray;
}

console.log(tokenizeString("14+2/8")); // [14, "+", 2, "/", 8]
console.log(tokenizeString("10+1")); // [1, '0', NaN, '-', 3] ??

For now I can't come up with an idea, why this happens.


问:
Adjusting a firebase cloud function
I am having trouble adjusting the code (using cors) for a firebase cloud function I am working on.

Below is the code for the function:

```<code>import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import * as cors from "cors";
import { on } from "events"

const corsHandler = cors({origin: true});
admin.initializeApp();

exports.myFunc = functions.https.onRequest(function(req,    resp) {
  corsHandler(req, resp, async () => {
    if (req.query.from !== undefined) {
      const from = String(req.query.from);
      functions.logger.log("From (URL):", from);
    } else {
      functions.logger.log("req.query.from is undefined");
    }

    const from = req.body.from;
    functions.logger.log("Hello from --myFunc--");

    admin.auth().getUserByEmail(from)
        .then(function(userRecord) {
          console.log("Successfully fetched user data:",    userRecord.toJSON());
        })
        .catch(function(error) {
          console.log("Error fetching user data:", error);
        });
  }); // End corsHandler.
});
</code>```

When I call this function using this URL in the browser:

```<code>https://us-central1-myapp.cloudfunctions.net/myFunc?from=example@example.com
</code>```

I get what I expect in the logs, that is:

```<code>myFunc: From (URL): example@example.com
</code>```

On the other hand when I call the function using this Ajax code from a web-app:

```<code>var xhr = new XMLHttpRequest();
xhr.open("POST", "https://us-central1-myapp. cloudfunctions.net/myFunc", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send("from=example@example.com");
xhr.onload = function() {
    var data = JSON.parse(this.responseText);
    console.log('THE DATA:',data);
};
</code>```

I have a problem, getting the following in the web console logs:

```<code>Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-myapp.cloudfunctions.net/myFunc. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 400.
</code>```

I must be missing something. Can someone point out what it is ?

答:
I finally got it to work, using this code for the Ajax call from the web-app (hoping this might help someone facing the same kind of issue at some point):</p>
```<code>var xhr = new XMLHttpRequest();
xhr.open("POST", "https://us-central1-myapp. cloudfunctions.net/    myFunc", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
    from: 'example@example.com'
}));
xhr.onload = function() {
    var data = JSON.parse(this.responseText);
    console.log('THE DATA:',data);
};
</code>```

Title: Adjusting a firebase cloud function

Body:
I am having trouble adjusting the code (using cors) for a firebase cloud function I am working on.

Below is the code for the function:

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import * as cors from "cors";
import { on } from "events"

const corsHandler = cors({origin: true});
admin.initializeApp();

exports.myFunc = functions.https.onRequest(function(req,    resp) {
  corsHandler(req, resp, async () => {
    if (req.query.from !== undefined) {
      const from = String(req.query.from);
      functions.logger.log("From (URL):", from);
    } else {
      functions.logger.log("req.query.from is undefined");
    }

    const from = req.body.from;
    functions.logger.log("Hello from --myFunc--");

    admin.auth().getUserByEmail(from)
        .then(function(userRecord) {
          console.log("Successfully fetched user data:",    userRecord.toJSON());
        })
        .catch(function(error) {
          console.log("Error fetching user data:", error);
        });
  }); // End corsHandler.
});

When I call this function using this URL in the browser:

https://us-central1-myapp.cloudfunctions.net/myFunc?from=example@example.com

I get what I expect in the logs, that is:

myFunc: From (URL): example@example.com

On the other hand when I call the function using this Ajax code from a web-app:

var xhr = new XMLHttpRequest();
xhr.open("POST", "https://us-central1-myapp. cloudfunctions.net/myFunc", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send("from=example@example.com");
xhr.onload = function() {
    var data = JSON.parse(this.responseText);
    console.log('THE DATA:',data);
};

I have a problem, getting the following in the web console logs:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-myapp.cloudfunctions.net/myFunc. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 400.

I must be missing something. Can someone point out what it is ?

Body:
I finally got it to work, using this code for the Ajax call from the web-app (hoping this might help someone facing the same kind of issue at some point):

var xhr = new XMLHttpRequest();
xhr.open("POST", "https://us-central1-myapp. cloudfunctions.net/    myFunc", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
    from: 'example@example.com'
}));
xhr.onload = function() {
    var data = JSON.parse(this.responseText);
    console.log('THE DATA:',data);
};


问:
how to select records in MySQL where the occurrence of foreign key is only one
I have a table in my MQL database with foreign keys. Now I want to select the records form this MySQL tables using join where the occurrence of a specific foreign key is only one and skip the records where occurrence is more than 1.

For example if I use simple select query like

```<code>Select *
from table1
INNER Join table2 on table1.id=table2.id
where group_id=1
</code>```

it selects all the records where group_id is 1 and also those where others group_ids exists I mean more than one gourp_ids against the same foreign key.
is there any solution.

答:
GROUP BY ... HAVING ... syntax is exactly for this purpose:</p>
```<code>Select table1.id
from table1
INNER Join table2
on table1.id=table2.id
where group_id=1
group by table2.id
having count(*)=1
</code>```

Body:
I have a table in my MQL database with foreign keys. Now I want to select the records form this MySQL tables using join where the occurrence of a specific foreign key is only one and skip the records where occurrence is more than 1.

For example if I use simple select query like

Select *
from table1
INNER Join table2 on table1.id=table2.id
where group_id=1

it selects all the records where group_id is 1 and also those where others group_ids exists I mean more than one gourp_ids against the same foreign key.
is there any solution.

Body:
GROUP BY ... HAVING ... syntax is exactly for this purpose:

Select table1.id
from table1
INNER Join table2
on table1.id=table2.id
where group_id=1
group by table2.id
having count(*)=1


问:
How do I make a String inside annotation depend on active profile?
I have an entity that needs to be mapped to a DynamoDBTable. We have two tables, one for dev environment and one for production. How can I change the string within an annotation depending on my current active profile?

In the dev enviroment I want the entity to start with this:

```<code>@DynamoDBTable(tableName = "my-dynamodbtable-dev")
public class MyEntity{
</code>```

In the prod enviroment, I want it to start with this:

```<code>@DynamoDBTable(tableName = "my-dynamodbtable-prod")
public class MyEntity{
</code>```

答:
Can use below expression to arrive with values based on active profile:</p>
```<code>@Value(#{'${spring.profiles.active}' eq 'PROD' ? 'my-dynamodbtable-prod' : 'my-dynamodbtable-dev'})
</code>```

Body:
I have an entity that needs to be mapped to a DynamoDBTable. We have two tables, one for dev environment and one for production. How can I change the string within an annotation depending on my current active profile?

In the dev enviroment I want the entity to start with this:

@DynamoDBTable(tableName = "my-dynamodbtable-dev")
public class MyEntity{

In the prod enviroment, I want it to start with this:

@DynamoDBTable(tableName = "my-dynamodbtable-prod")
public class MyEntity{

Body:
Can use below expression to arrive with values based on active profile:

@Value(#{'${spring.profiles.active}' eq 'PROD' ? 'my-dynamodbtable-prod' : 'my-dynamodbtable-dev'})


问:
Invalid argument 'display' in 'plot' call. Possible values: [display.none, display.all]
I am writing a pine script code to plot some lines conditionally. I see pine script v5, plot() function has display argument, still I am getting an weird error. Any idea what it could be?

Code:

```<code>//@version=5

indicator(title="Gann Levels", shorttitle="GIL", overlay=false, timeframe="", timeframe_gaps=true)

from_previous_day_low = input.bool(title="Previous day low", defval=true)
from_previous_day_high = input.bool(title="Previous day high", defval=true)

[previous_day_high, previous_day_low] = request.security(syminfo.tickerid, "D", [high[1], low[1]])

sqrt_previous_day_low = math.round(math.sqrt(previous_day_low))
sqrt_previous_day_high = math.round(math.sqrt(previous_day_high))

display_supports() => from_previous_day_low ? display.none : display.all

display_resistances() => from_previous_day_high ? display.none : display.all

s1 = math.round(math.pow(sqrt_previous_day_high - 0.250, 2))
s2 = math.round(math.pow(sqrt_previous_day_high - 0.500, 2))
s3 = math.round(math.pow(sqrt_previous_day_high - 0.750, 2))

r1 = math.round(math.pow(sqrt_previous_day_low - 0.250, 2))
r2 = math.round(math.pow(sqrt_previous_day_low - 0.500, 2))
r3 = math.round(math.pow(sqrt_previous_day_low - 0.750, 2))

plot(series=s1, linewidth=2, color=color.new(#16F6DE, 10), display=display_supports())
plot(series=s2, linewidth=2, color=color.new(#16F6DE, 10), display=display_supports())
plot(series=s3, linewidth=2, color=color.new(#16F6DE, 10), display=display_supports())

plot(series=r1, linewidth=2, color=color.new(#16F6DE, 10), display=display_resistances())
plot(series=r2, linewidth=2, color=color.new(#16F6DE, 10), display=display_resistances())
plot(series=r3, linewidth=2, color=color.new(#16F6DE, 10), display=display_resistances())
</code>```

Errors:

```<code>line 26: Invalid argument 'display' in 'plot' call. Possible values: [display.none, display.all];
line 27: Invalid argument 'display' in 'plot' call. Possible values: [display.none, display.all];
line 28: Invalid argument 'display' in 'plot' call. Possible values: [display.none, display.all];
line 31: Invalid argument 'display' in 'plot' call. Possible values: [display.none, display.all];
line 32: Invalid argument 'display' in 'plot' call. Possible values: [display.none, display.all];
line 33: Invalid argument 'display' in 'plot' call. Possible values: [display.none, display.all]
</code>```

答:
You should apply your condition to the series argument of plot(). The display argument is whether to enable or disable the plot by default and I believe it must be a constant.

And you probably want to change the style to something like plot.style_circles so your line won't be connected.

```<code>plot(from_previous_day_low ? s1 : na, linewidth=2, color=color.new(#16F6DE, 10), style=plot.style_circles)
plot(from_previous_day_low ? s2 : na, linewidth=2, color=color.new(#16F6DE, 10), style=plot.style_circles)
plot(from_previous_day_low ? s3 : na, linewidth=2, color=color.new(#16F6DE, 10), style=plot.style_circles)

plot(from_previous_day_high ? r1 : na, linewidth=2, color=color.new(#16F6DE, 10), style=plot.style_circles)
plot(from_previous_day_high ? r2 : na, linewidth=2, color=color.new(#16F6DE, 10), style=plot.style_circles)
plot(from_previous_day_high ? r3 : na, linewidth=2, color=color.new(#16F6DE, 10), style=plot.style_circles)
</code>```

Body:
I am writing a pine script code to plot some lines conditionally. I see pine script v5, plot() function has display argument, still I am getting an weird error. Any idea what it could be?

Code:

//@version=5

indicator(title="Gann Levels", shorttitle="GIL", overlay=false, timeframe="", timeframe_gaps=true)

from_previous_day_low = input.bool(title="Previous day low", defval=true)
from_previous_day_high = input.bool(title="Previous day high", defval=true)

[previous_day_high, previous_day_low] = request.security(syminfo.tickerid, "D", [high[1], low[1]])

sqrt_previous_day_low = math.round(math.sqrt(previous_day_low))
sqrt_previous_day_high = math.round(math.sqrt(previous_day_high))

display_supports() => from_previous_day_low ? display.none : display.all

display_resistances() => from_previous_day_high ? display.none : display.all

s1 = math.round(math.pow(sqrt_previous_day_high - 0.250, 2))
s2 = math.round(math.pow(sqrt_previous_day_high - 0.500, 2))
s3 = math.round(math.pow(sqrt_previous_day_high - 0.750, 2))

r1 = math.round(math.pow(sqrt_previous_day_low - 0.250, 2))
r2 = math.round(math.pow(sqrt_previous_day_low - 0.500, 2))
r3 = math.round(math.pow(sqrt_previous_day_low - 0.750, 2))

plot(series=s1, linewidth=2, color=color.new(#16F6DE, 10), display=display_supports())
plot(series=s2, linewidth=2, color=color.new(#16F6DE, 10), display=display_supports())
plot(series=s3, linewidth=2, color=color.new(#16F6DE, 10), display=display_supports())

plot(series=r1, linewidth=2, color=color.new(#16F6DE, 10), display=display_resistances())
plot(series=r2, linewidth=2, color=color.new(#16F6DE, 10), display=display_resistances())
plot(series=r3, linewidth=2, color=color.new(#16F6DE, 10), display=display_resistances())

Errors:

line 26: Invalid argument 'display' in 'plot' call. Possible values: [display.none, display.all];
line 27: Invalid argument 'display' in 'plot' call. Possible values: [display.none, display.all];
line 28: Invalid argument 'display' in 'plot' call. Possible values: [display.none, display.all];
line 31: Invalid argument 'display' in 'plot' call. Possible values: [display.none, display.all];
line 32: Invalid argument 'display' in 'plot' call. Possible values: [display.none, display.all];
line 33: Invalid argument 'display' in 'plot' call. Possible values: [display.none, display.all]

Body:
You should apply your condition to the series argument of plot(). The display argument is whether to enable or disable the plot by default and I believe it must be a constant.

And you probably want to change the style to something like plot.style_circles so your line won't be connected.

plot(from_previous_day_low ? s1 : na, linewidth=2, color=color.new(#16F6DE, 10), style=plot.style_circles)
plot(from_previous_day_low ? s2 : na, linewidth=2, color=color.new(#16F6DE, 10), style=plot.style_circles)
plot(from_previous_day_low ? s3 : na, linewidth=2, color=color.new(#16F6DE, 10), style=plot.style_circles)

plot(from_previous_day_high ? r1 : na, linewidth=2, color=color.new(#16F6DE, 10), style=plot.style_circles)
plot(from_previous_day_high ? r2 : na, linewidth=2, color=color.new(#16F6DE, 10), style=plot.style_circles)
plot(from_previous_day_high ? r3 : na, linewidth=2, color=color.new(#16F6DE, 10), style=plot.style_circles)


问:
How can I inject a build number with webpack?
I'd like to inject a build number and version information to my project as it's built with webpack. For example, so that my code can do something like:

```<code>var buildInfo = require("build-info");
</code>```

What would be the best way to generate that build-info module at build time?

答:
If you're okay with inserting the build information as a global variable directly in your index.html page, then the simplest approach may be to leverage the HtmlWebpackPlugin you're probably already using in your webpack config.

This article explains how to inject data into the index.html file at build time.  You can add arbitrary data to the plugin in your webpack.config.js file like this:

plugins: [
    ...
    new HtmlWebpackPlugin({
        template: "./src/index.html",
        filename: "index.html",
        info: {
            foo: "bar",
            time: new Date().toLocaleString()
        },
    })
]
```
<p>In the <code>index.html</code> template file, you can add an escape sequence to access that data and insert it (the <code>JSON.stringify()</code> outputs the data as an object literal that will be evaluated as part of the script):</p>
<pre class="lang-html prettyprint-override"><code><script type="text/javascript">
    window.BUILD_INFO = <%= JSON.stringify(htmlWebpackPlugin.options.info, null, 2) %>;
</script>
</code>```

You can then access that global variable from wherever you want in your code, like console.log("Built at ", BUILD_INFO.time);

For my use case, I just wanted to include a build timestamp as a comment in the HTML file.  So I added the timestamp to the plugin object and set minify: false to prevent comments from being stripped (and which also prevents the HTML from being output on a single line).

plugins: [
    ...
    new HtmlWebpackPlugin({
        ...
        minify: false,
        buildTime: new Date().toLocaleString()
    })
]
```
<p>This timestamp was then injected into an HTML comment like this:</p>
<pre class="lang-html prettyprint-override"><code><!-- Built at <%= htmlWebpackPlugin.options.buildTime %> -->
</code>```

Body:
I'd like to inject a build number and version information to my project as it's built with webpack. For example, so that my code can do something like:

var buildInfo = require("build-info");

What would be the best way to generate that build-info module at build time?

Body:
If you're okay with inserting the build information as a global variable directly in your index.html page, then the simplest approach may be to leverage the HtmlWebpackPlugin you're probably already using in your webpack config.

This article explains how to inject data into the index.html file at build time.  You can add arbitrary data to the plugin in your webpack.config.js file like this:

plugins: [
    ...
    new HtmlWebpackPlugin({
        template: "./src/index.html",
        filename: "index.html",
        info: {
            foo: "bar",
            time: new Date().toLocaleString()
        },
    })
]

In the index.html template file, you can add an escape sequence to access that data and insert it (the JSON.stringify() outputs the data as an object literal that will be evaluated as part of the script):

<script type="text/javascript">
    window.BUILD_INFO = <%= JSON.stringify(htmlWebpackPlugin.options.info, null, 2) %>;
</script>

You can then access that global variable from wherever you want in your code, like console.log("Built at ", BUILD_INFO.time);

For my use case, I just wanted to include a build timestamp as a comment in the HTML file.  So I added the timestamp to the plugin object and set minify: false to prevent comments from being stripped (and which also prevents the HTML from being output on a single line).

plugins: [
    ...
    new HtmlWebpackPlugin({
        ...
        minify: false,
        buildTime: new Date().toLocaleString()
    })
]

This timestamp was then injected into an HTML comment like this:

<!-- Built at <%= htmlWebpackPlugin.options.buildTime %> -->


问:
Google play app rejected Require that users accept the app's terms of use and/or user policy before users can create or upload UGC
My app is rejected for this reason Require that users accept the app's terms of use and/or user policy before users can create or upload UGC

I have one chatroom in the app for all users to discuss a topic and its open without registration .. What should I do to fix this?

答:
```<code>Require that users accept the app's terms of use and/or user policy before users can create or upload UGC
</code>```

As the sentence say, you should:

Write your app's terms of use and/or user policy.

Show popup or activity to show that terms of use and/or user policy.

Allow user to chat after user check agree button at the end.

Build app and submit your app again.

Check out some demo you can follow here:

Body:
Require that users accept the app's terms of use and/or user policy before users can create or upload UGC

As the sentence say, you should:

Write your app's terms of use and/or user policy.

Show popup or activity to show that terms of use and/or user policy.

Allow user to chat after user check agree button at the end.

Build app and submit your app again.

Check out some demo you can follow here:


问:
Beautiful soup returns random elements when called for a certain tag or class name
So from the following site, I need to filter the current price of the product listed which is located in the tag
 with the class name - current price, so I wrote the following code to get the result, but what I get is the price with some other bunch of stuffs, how to filter the price alone from the html code ?

https://www.tendercuts.in/chicken

here is the code i used :

```<code>   import requests
   from bs4 import BeautifulSoup

   baseurl = 'https://www.tendercuts.in/'

   r = requests.get('https://www.tendercuts.in/chicken')
   soup = BeautifulSoup(r.content, 'lxml')

   productweight = soup.find_all('p', class_='currentprice')

   print(productweight)
</code>```

答:
You need to use the correct class as follows:</p>
```<code>import requests
from bs4 import BeautifulSoup

r = requests.get('https://www.tendercuts.in/chicken')
soup = BeautifulSoup(r.content, 'lxml')

for p in soup.find_all('p', class_='current-price'):
    print(p.text)
</code>```

Body:
So from the following site, I need to filter the current price of the product listed which is located in the tag
 with the class name - current price, so I wrote the following code to get the result, but what I get is the price with some other bunch of stuffs, how to filter the price alone from the html code ?

https://www.tendercuts.in/chicken

here is the code i used :

   import requests
   from bs4 import BeautifulSoup

   baseurl = 'https://www.tendercuts.in/'

   r = requests.get('https://www.tendercuts.in/chicken')
   soup = BeautifulSoup(r.content, 'lxml')

   productweight = soup.find_all('p', class_='currentprice')

   print(productweight)

Body:
You need to use the correct class as follows:

import requests
from bs4 import BeautifulSoup

r = requests.get('https://www.tendercuts.in/chicken')
soup = BeautifulSoup(r.content, 'lxml')

for p in soup.find_all('p', class_='current-price'):
    print(p.text)


答:
Here you go...there are two changes you have to make in your code. Check the following code and comment.</p>
```<code>import requests
from bs4 import BeautifulSoup

baseurl = 'https://www.tendercuts.in/'

r = requests.get('https://www.tendercuts.in/chicken')
soup = BeautifulSoup(r.content, 'html.parser')

productweight = soup.find_all('p', class_='current-price')

print(productweight)
</code>```

Title: Beautiful soup returns random elements when called for a certain tag or class name

Body:
Here you go...there are two changes you have to make in your code. Check the following code and comment.

import requests
from bs4 import BeautifulSoup

baseurl = 'https://www.tendercuts.in/'

r = requests.get('https://www.tendercuts.in/chicken')
soup = BeautifulSoup(r.content, 'html.parser')

productweight = soup.find_all('p', class_='current-price')

print(productweight)


问:
Can I use conda to handle a virtual environment created by virtualenv
I ran a provided shell file and a requirements.txt file and that shell file created the virtual environment using virtualenv. However, I do most of my coding work using Anaconda. Is that possible to use conda to activate and manage my virtual environment? Since I haven't used a virtual environment before, I don't know how to create a new virtual environment without the provided files. Thanks for help.

This is the shell file create_venv.sh:

```<code>#!/bin/bash

# this installs the virtualenv module
python3 -m pip install virtualenv
# this creates a virtual environment named "env"
python3 -m venv env
# this activates the created virtual environment
source env/bin/activate
# updates pip
pip install -U pip
# this installs the required python packages to the virtual environment
pip install -r /Users/linghu/Desktop/CSCI\ 2470/hw1-mnist-lah-dee-dah-master/requirements.txt

echo created environment
</code>```

This is the requirements.txt file:

```<code>setuptools==41.2.0
tensorflow==2.5.0
matplotlib==3.5.1
gym==0.19.0
ghast==0.1.0
dgl==0.6.0
future==0.18.2
numpy==1.19.3
periodictable==1.5.1
tensorflow-gan==2.0.0
tensorflow-hub==0.9.0
imageio==2.9.0
tqdm==4.48.2
</code>```

答:
This is one of the great things about Anaconda. Simply the command conda create --name <env_name> --file requirements.txt should create your new virtual environment.

Here is the link on general management of anaconda environments: https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html

Body:
I ran a provided shell file and a requirements.txt file and that shell file created the virtual environment using virtualenv. However, I do most of my coding work using Anaconda. Is that possible to use conda to activate and manage my virtual environment? Since I haven't used a virtual environment before, I don't know how to create a new virtual environment without the provided files. Thanks for help.

This is the shell file create_venv.sh:

#!/bin/bash

# this installs the virtualenv module
python3 -m pip install virtualenv
# this creates a virtual environment named "env"
python3 -m venv env
# this activates the created virtual environment
source env/bin/activate
# updates pip
pip install -U pip
# this installs the required python packages to the virtual environment
pip install -r /Users/linghu/Desktop/CSCI\ 2470/hw1-mnist-lah-dee-dah-master/requirements.txt

echo created environment

This is the requirements.txt file:

setuptools==41.2.0
tensorflow==2.5.0
matplotlib==3.5.1
gym==0.19.0
ghast==0.1.0
dgl==0.6.0
future==0.18.2
numpy==1.19.3
periodictable==1.5.1
tensorflow-gan==2.0.0
tensorflow-hub==0.9.0
imageio==2.9.0
tqdm==4.48.2


问:
Regex expression to match last numerical component, but exclude file extension
I'm stumped trying to figure out a regex expression. Given a file path, I need to match the last numerical component of the path ("frame" number in an image sequence), but also ignore any numerical component in the file extension.

For example, given path:

/path/to/file/abc123/GCAM5423.xmp

The following expression will correctly match 5423.

((?P<index>(?P<padding>0*)\d+)(?!.*(0*)\d+))

However, this expression fails if for example the file extension contains a number as follows:

/path/to/file/abc123/GCAM5423.cr2

In this case the expression will match the 2 in the file extension, when I still need it to match 5423. How can I modify the above expression to ignore file extensions that have a numerical component?

Using python flavor of regex. Thanks in advance!

Edit: Thanks all for your help! To clarify, I specifically need to modify the above expression to only capture the last group. I am passing this pattern to an external library so it needs to include the named groups and to only match the last number prior to the extension.

答:
Try this pattern:
\/[^/\d\s]+(\d+)\.[^/]+$

See Regex Demo

Code:

```<code>import re

pattern = r"\/[^/\d\s]+(\d+)\.[^/]+$"

texts = ['/path/to/file/abc123/GCAM5423.xmp', '/path/to/file/abc123/GCAM5423.cr2']

print([match.group(1) for x in texts if (match := re.search(pattern, x))])
</code>```

Output:

['5423', '5423']

Body:
Try this pattern:
\/[^/\d\s]+(\d+)\.[^/]+$

See Regex Demo

Code:

import re

pattern = r"\/[^/\d\s]+(\d+)\.[^/]+$"

texts = ['/path/to/file/abc123/GCAM5423.xmp', '/path/to/file/abc123/GCAM5423.cr2']

print([match.group(1) for x in texts if (match := re.search(pattern, x))])

Output:

['5423', '5423']


问:
Microsoft SQL variant type error pops up when I run hibernate 5
Whenever I run my hibernate 5, I see this error:

```<code>ERROR: Could not fetch the SequenceInformation from the database
com.microsoft.sqlserver.jdbc.SQLServerException: The "variant" data type is not supported.
</code>```

I've never heard of a "variant" data type before. Or is it a category of data types? Not sure.

I checked the data types in all my tables, and these are the ones that are there: bigint, bit, date, datetime, int, numeric, varbinary, and varchar.

Where could this error be coming from? Is there somewhere else I should check for variant types?

EDIT:

I ran this query select distinct data_type from INFORMATION_SCHEMA.COLUMNS to get all the data types in my database, and sql variant didn't show up. That's how I'm sure there isn't one.

Is there somewhere else this could be referenced?

EDIT 2:

A little bit more information on this. The application is a maven project. I created a normal java project and ran the same codes against the same database, and I didn't get any error about sql variant types.

So this issue seems to be tied to the hibernate dependency. I don't get it, really. This is the dependency I'm using:

```<code>        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.0.Final</version>
        </dependency>
</code>```

答:
In my project
MSSQL version 2017.
springboot-parent version is 2.5.6.
hibernate-core version is 5.4.32.Final.
MSSQL Driver sqljdbc4 version 4.1
I get error when start project.
I see there's an answer said change driver version ,then i try mssql-jdbc version 6.2.2.jre8,it's dosen't work.
But version 9.4.1.jre8 it's worked solved the problem.
enter image description here</p>

Body:
Whenever I run my hibernate 5, I see this error:

ERROR: Could not fetch the SequenceInformation from the database
com.microsoft.sqlserver.jdbc.SQLServerException: The "variant" data type is not supported.

I've never heard of a "variant" data type before. Or is it a category of data types? Not sure.

I checked the data types in all my tables, and these are the ones that are there: bigint, bit, date, datetime, int, numeric, varbinary, and varchar.

Where could this error be coming from? Is there somewhere else I should check for variant types?

EDIT:

I ran this query select distinct data_type from INFORMATION_SCHEMA.COLUMNS to get all the data types in my database, and sql variant didn't show up. That's how I'm sure there isn't one.

Is there somewhere else this could be referenced?

EDIT 2:

A little bit more information on this. The application is a maven project. I created a normal java project and ran the same codes against the same database, and I didn't get any error about sql variant types.

So this issue seems to be tied to the hibernate dependency. I don't get it, really. This is the dependency I'm using:

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.0.Final</version>
        </dependency>


问:
One member of a list higher than the other
I am trying to create a navbar in my site, but every time I try to align the logo to the left the page selection is put higher, anyone have a solution?

Screenshot:

This is the html code:

```<code>  <div class="NavBar">
    <ul class="Items">
      <li class="Logo">
        <img src="images/logo1.png" alt="IM2B - Play your brand">
      </li>
      <li class="Links">
        <a class="active" href="#home">Home</a>
        <a href="#news">News</a>
        <a href="#contact">Contact</a>
        <a href="#about">About</a>
      </li>
    </ul>
  </div>
</code>```

This is the css code:

```<code>.NavBar {
  list-style-type: none;
  overflow: hidden;
  background-color: #333;
  padding: 20px;
}

.NavBar .Items {
  margin: auto;
  width: 60%;
  text-align: center;
  list-style: none;
}

.NavBar .Logo {
  float: left;
}

.NavBar .Links {
  display: inline-block;
  padding: 0px 16px;
}

.NavBar .Links a {
  color: #f2f2f2;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.NavBar .Links a:hover {
  background-color: #ddd;
  color: black;
}

.NavBar .Links a.active {
  background-color: #04AA6D;
  color: white;
}
</code>```

答:
Is this you were looking for? Look, there are 2-levels of display:flex for alignments.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.NavBar {
  list-style-type: none;
  background-color: #333;
  padding: 10px;
}

ul li {
  list-style-type: none;
}

.NavBar .Items {
  display: flex;
  justify-content: space-around;
}

.NavBar .Links {
  display: flex;
}

.NavBar .Links a {
  color: #f2f2f2;
  text-decoration: none;
  font-size: 17px;
  padding: 10px 20px;
  display: inline-block;
  height: 40px;
  align-self: center;
}

.NavBar .Links a:hover {
  background-color: #ddd;
  color: black;
}

.NavBar .Links a.active {
  background-color: #04AA6D;
  color: white;
}

img {
  height: 60px;
  width: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="NavBar">
  <ul class="Items">
    <li class="Logo">
      <img src="https://picsum.photos/200/300" alt="IM2B - Play your brand">
    </li>
    <li class="Links">
      Home
      News
      Contact
      About
    </li>
  </ul>
</div></code>```

Body:
I am trying to create a navbar in my site, but every time I try to align the logo to the left the page selection is put higher, anyone have a solution?

Screenshot:

This is the html code:

        Home
        News
        Contact
        About

This is the css code:

.NavBar {
  list-style-type: none;
  overflow: hidden;
  background-color: #333;
  padding: 20px;
}

.NavBar .Items {
  margin: auto;
  width: 60%;
  text-align: center;
  list-style: none;
}

.NavBar .Logo {
  float: left;
}

.NavBar .Links {
  display: inline-block;
  padding: 0px 16px;
}

.NavBar .Links a {
  color: #f2f2f2;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.NavBar .Links a:hover {
  background-color: #ddd;
  color: black;
}

.NavBar .Links a.active {
  background-color: #04AA6D;
  color: white;
}

Body:
Is this you were looking for? Look, there are 2-levels of display:flex for alignments.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.NavBar {
  list-style-type: none;
  background-color: #333;
  padding: 10px;
}

ul li {
  list-style-type: none;
}

.NavBar .Items {
  display: flex;
  justify-content: space-around;
}

.NavBar .Links {
  display: flex;
}

.NavBar .Links a {
  color: #f2f2f2;
  text-decoration: none;
  font-size: 17px;
  padding: 10px 20px;
  display: inline-block;
  height: 40px;
  align-self: center;
}

.NavBar .Links a:hover {
  background-color: #ddd;
  color: black;
}

.NavBar .Links a.active {
  background-color: #04AA6D;
  color: white;
}

img {
  height: 60px;
  width: 100px;
}

<div class="NavBar">
  <ul class="Items">
    <li class="Logo">
      <img src="https://picsum.photos/200/300" alt="IM2B - Play your brand">
    </li>
    <li class="Links">
      <a class="active" href="#home">Home</a>
      <a href="#news">News</a>
      <a href="#contact">Contact</a>
      <a href="#about">About</a>
    </li>
  </ul>
</div>


问:
File uploading rails 3
I have a rails 3 app that has a comment system that allows a user to make comments. What I now wish to do is extend this further by enabling the user to attach/upload files to the comment system. Fairly easy question I am about to ask. What is the best tool/plugin or gem to use so that I can achieve this? I've done some thorough research and found that alot of these plugins such as carrierwave, paperclip and a few others are used to upload photos and I am not trying to do this.

Requirements

User should be able to upload/attach files

Can upload word, powerpoint or execel docuements

答:
Both carrierwave and paperclip can be used to upload any type of files - they have extra features if you want to upload images, but they are not restricted to handling just image files.
In the end it's a matter of preference. I found both paperclip and carrierwave to be very good at what they do.</p>

Title: File uploading rails 3


问:
ES6 String interpolation from file content
I came across the String interpolation feature in ES6. It works if I define the raw string in the code. But I want to read the raw string from a file and then replace the placeholders. How to do it?

file.txt

```<code>   hello ${customer.name}
</code>```

Node JS

```<code>   var customer = {name: 'sid'};
   var data = fs.readFileSync("file.txt","utf8");
   // what should go here so that data is 'Hello sid'?
</code>```

答:
Improving on @Daniel's solution, allowing for undefined variable references to be left alone.  This allows multiple template interpolation passes with different variables matches.

// Interpolate template given parameter object.
// Can be chained, replacing only found variable paths.
// Strip whitespace from template variable reference.
// Will not work with ${"some var"."another var"}
const replace = function (templ, obj) {
    return templ.replace(/\${([^}]*)}/g, (r,k)=> {
        let ret;
        try { ret = k.replace(/ /g, '').split(".").reduce((acc,cur)=>acc[cur],obj); } catch (err) { }
        return (ret === undefined) ? r : ret;
    });
};
var obj = {a: 'one', b:{b1:"Bravo-1",b2:'Bravo-2'},c:{c1:{c2:"Charlie-2"}}};
var templMissing = '${ a}, ${b.b1 }, ${b.b2}, ${c.c1.c2}, ${bla} ${var.ble}';
console.log(replace(templMissing, obj));```

Body:
I came across the String interpolation feature in ES6. It works if I define the raw string in the code. But I want to read the raw string from a file and then replace the placeholders. How to do it?

file.txt

   hello ${customer.name}

Node JS

   var customer = {name: 'sid'};
   var data = fs.readFileSync("file.txt","utf8");
   // what should go here so that data is 'Hello sid'?


问:
Trying to return true or false from an authentification function with node
I have an async function that should return true or false. I know for sure that in this case it should return true but a console.log displays " Promise { pending }".

Here is the function :

```<code>const sql = require('mssql');
const sqlConfig = {

    user: accessDB.DB_USER,
    password: accessDB.DB_PWD,
    database: accessDB.DB_NAME,
  server: accessDB.SERVER,
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: false, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}
const authentification = async (login, password) => {

var sqls = `SELECT CLICOD FROM Clients WHERE CLICOD = '${login}' AND PasswordFtp ='${password}'`

 try {

  await sql.connect(sqlConfig)
  const result = await sql.query(sqls)

if (result.rowsAffected > 0) {
    return true;
}else {
    return false;
}

 } catch (err) {
console.log(err)
 }
}
module.exports = authentification;
</code>```

This next part of the code is supposed to receive the result (true or false) but always ends up in the "not authorized" section even though a console.log of the result.rowsAffected does return 1.

```<code>app.get('/test',(req,res)=>{

if (authentification(req.query.login, req.query.pass)===true) {

  res.send("authorized");
}else {
  res.send("not authorized");
}

})
</code>```

Can an async function return a result at all?
Thank you for your help.

答:
change your route function to async and await for authentification response like below:

```<code>app.get('/test', async (req, res) => {
  const isAuthenticated = await authentification(req.query.login, req.query.pass)
  if (isAuthenticated === true) {

    res.send("authorized");
  } else {
    res.send("not authorized");
  }

})
</code>```

Body:
I have an async function that should return true or false. I know for sure that in this case it should return true but a console.log displays " Promise { pending }".

Here is the function :

const sql = require('mssql');
const sqlConfig = {

    user: accessDB.DB_USER,
    password: accessDB.DB_PWD,
    database: accessDB.DB_NAME,
  server: accessDB.SERVER,
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: false, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}
const authentification = async (login, password) => {

var sqls = `SELECT CLICOD FROM Clients WHERE CLICOD = '${login}' AND PasswordFtp ='${password}'`

 try {

  await sql.connect(sqlConfig)
  const result = await sql.query(sqls)

if (result.rowsAffected > 0) {
    return true;
}else {
    return false;
}

 } catch (err) {
console.log(err)
 }
}
module.exports = authentification;

This next part of the code is supposed to receive the result (true or false) but always ends up in the "not authorized" section even though a console.log of the result.rowsAffected does return 1.

app.get('/test',(req,res)=>{

if (authentification(req.query.login, req.query.pass)===true) {

  res.send("authorized");
}else {
  res.send("not authorized");
}

})

Can an async function return a result at all?
Thank you for your help.

Body:
change your route function to async and await for authentification response like below:

app.get('/test', async (req, res) => {
  const isAuthenticated = await authentification(req.query.login, req.query.pass)
  if (isAuthenticated === true) {

    res.send("authorized");
  } else {
    res.send("not authorized");
  }

})


问:
I write a python program to ask my computer to guess a secret number but it does not work
Here is my code:

```<code>import random
def guessGame(x):
    low=1
    high=x
    feedback=" "

    while feedback != "c":
        if high!=low:
            guess=int(random.randint(low,high))
        else:
            guess=low

        feedback= input(f"Is it {guess} too high(H),too lowe(L) or correct(C)?").lower()
        if feedback == "h":
            high = guess-1
        elif feedback == "l":
            low=guess+1
    print(f"I guess the correct number{guess}!")

x=input("Please input a highest number in the range: ")
guessGame(x)
</code>```

I wrote a python code to ask my computer to guess a secret number. But it did not work. I did some changes but still do know where I did wrong.

答:
Python input type is a string you must convert to string to integer</p>
```<code>x=int(input("Please input a highest number in the range: "))```</code>

Body:
Here is my code:

import random
def guessGame(x):
    low=1
    high=x
    feedback=" "

    while feedback != "c":
        if high!=low:
            guess=int(random.randint(low,high))
        else:
            guess=low

        feedback= input(f"Is it {guess} too high(H),too lowe(L) or correct(C)?").lower()
        if feedback == "h":
            high = guess-1
        elif feedback == "l":
            low=guess+1
    print(f"I guess the correct number{guess}!")

x=input("Please input a highest number in the range: ")
guessGame(x)

I wrote a python code to ask my computer to guess a secret number. But it did not work. I did some changes but still do know where I did wrong.

Body:
Python input type is a string you must convert to string to integer

x=int(input("Please input a highest number in the range: "))


问:
List of available/registered twilio voice clients
I'm looking through documention but didn't find anything that can help me find registered clients to twilio voice incoming calls.

For example. I have 10 registered clients to javascript sdk, that can handle incoming calls by their identities. But on my backend I need to find out who is registered and who is not busy making another call.

Is there any endpoint or someting that can return list of users(identites, clients, devices) with their status?

Because with TwiML I can redirect incoming call up to 10 clients. But when I don't know who is ready to answer and not busy I can't redirect responsible.

Thanks for any leads.

答: I resolved it with another way. When the user connects a device to twilio, I put him in the presence group with WS. When the device starts calling, I put him in another presence group. On the backend, when recieving calls, I just check who is in the ready group and not in the calling one and connect him with this incoming call.</p>


问:
Error running Maven
I am trying to build a maven (latest version 3.1.1) project and for some reason when I run any maven command, such as maven clean, or maven compile, I get the following error:</p>

```<code>Exception in thread "main" java.lang.IllegalAccessError: tried to access method org.slf4j.LoggerFactory.reset()V from class org.slf4j.MavenSlf4jFriend
at org.slf4j.MavenSlf4jFriend.reset(MavenSlf4jFriend.java:33)
at org.apache.maven.cli.logging.impl.Slf4jSimpleConfiguration.activate(Slf4jSimpleConfiguration.java:60)
at org.apache.maven.cli.MavenCli.logging(MavenCli.java:348)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:205)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:158)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
at org.codehaus.classworlds.Launcher.main(Launcher.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
</code>```

答:
You need to remove slf4j libraries from java/path/jre/lib/ext/

Then it will work

Title: Error running Maven

Body:
I am trying to build a maven (latest version 3.1.1) project and for some reason when I run any maven command, such as maven clean, or maven compile, I get the following error:

Exception in thread "main" java.lang.IllegalAccessError: tried to access method org.slf4j.LoggerFactory.reset()V from class org.slf4j.MavenSlf4jFriend
at org.slf4j.MavenSlf4jFriend.reset(MavenSlf4jFriend.java:33)
at org.apache.maven.cli.logging.impl.Slf4jSimpleConfiguration.activate(Slf4jSimpleConfiguration.java:60)
at org.apache.maven.cli.MavenCli.logging(MavenCli.java:348)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:205)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:158)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
at org.codehaus.classworlds.Launcher.main(Launcher.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)


问:
What is the difference between BatchGetItem and TransactionGetItems in DynamoDB?
I have been searching SO for this but I didn't find an answer to this. (BatchGetItem vs Query i DID find but not what I'm looking for). I do know the basics:-

BatchGetItem you can request for items from ONE OR MORE TABLES and if the resultset exceeds 100 entities or 16MB -> It will return you an UnprocessedKeys using which you can query the next set of results

"TransactionGetItems" you can request for items from ONE OR MORE TABLES for upto 25 entities or 4MB -> Errors if size of aggregate response exceeds 4MB

What then is the use of TransactionGetItems over BatchGetItem? From trawling the docs, I could make out that TransactionGetItems will fail if there are underlying writes happening that impact the same data. Is this the primary use of TransactionGetItems over BatchGetItem, which I assume WONT fail under the same conditions?

答: TransactGetItem allows you to have an all or nothing transaction. Either all GetItem operations in the transactions succeed or none of them do. If one fails, no data is returned. In addition TransactGetItem uses serializable isolation and a plain BatchGetItem does not.</p>


问:
Typescript undefined date validation
I am using luxon for my app. I have some undefined date. I validate my date with luxon's isDateTime and function returns string. I used this function multiple places of the app. Most of the places I am passing date string and only places I am getting undefined date. I  manage to silent the Typescript error but I think it's not optimal solution.

code-sandbox

Is there any better way, I can make this function?

const {
  DateTime
} = require('luxon')

const ISO_DATE_FORMAT = "yyyy-MM-dd";

const dateToStrings = (date: string | number | Date): DateTime =>
  DateTime.fromISO(new Date(date).toISOString());

const dateToISOString = (date: Date | string | undefined): string => {
  if (DateTime.isDateTime(date)) {
    return dateToStrings(date).toFormat(ISO_DATE_FORMAT);
  }
  return date as string;
};

console.log(dateToISOString(undefined));```

答:
In this case dateToISOString(undefined), you simply tell typescript that undefined is a string, which will later cause exceptions when the caller tries to access the string-value.

Instead you should handle the undefined case explicitly and (dependent on your use-case) you may want to:

return a default text: e.g. "", "-", etc.

or throw an error: e.g. throw Error('undefined date!');

export const dateToISOString = (date: Date | string | undefined): string => {
  if (!date) {
    /**
     * handle the case when the caller passes undefined explicitly.
     * Dependent on your use-case you may want to
     * - return a default text: e.g. "", "-", etc.
     * - or throw Error('undefined date!');
     */
    return '-';
  } else if (typeof date === "string") {
    // then check if the input is a string
    return date;
  } else {
    /**
     * now typescript knows that the input is of type Date
     * because you defined the input type as:  Date | string | undefined
     * and you have already handled the undefined and string cases
     */
    return dateToStrings(date).toFormat(ISO_DATE_FORMAT);
  }
};
```

Title: Typescript undefined date validation