问:
How to calculate HashMap memory usage in Java?
I was asked in an interview to calculate the memory usage for HashMap and how much estimated memory it will consume if you have 2 million items in it.

For example:

```<code>Map <String,List<String>> mp=new HashMap <String,List<String>>();
</code>```

The mapping is like this.

```<code>key   value
----- ---------------------------
abc   ['hello','how']
abz   ['hello','how','are','you']
</code>```

How would I estimate the memory usage of this HashMap Object in Java?

答:
```<code>Summary:

memory = hashmap_array_size*bucket_size
+ n*chained_list_node_size
+ sum(key string sizes)
+ sum(list_string_size(string_list) for each hashmap List<String> value)

= 254 MB
(theoretical in-interview estimate)

Test program total-memory-used-size for 2 million sample entries: (see below)
= 640 MB
(I recommend a simple test program like this for a quick true-total-size estimate)
</code>```

A minimal estimate (actual implementation probably has a bit more overhead):

Assumed data structure:

```<code>Bucket: (Pointer to String key, Pointer to hash-chain-list first-node)

Chained List Node: (Pointer to List<String> value, Next-pointer)
(HashMap is a chained hash - each bucket has a list/tree of values)
(as of Java 8, the list switches to a tree after 8 items)

List<String> instance: (Pointer to first node)

List<String> Node: (Pointer to String value, Next-pointer)
</code>```

Assumption to simplify this estimate: zero collisions, each bucket has max 1 value (ask interviewer if this is ok - to give a rough, initial answer)

Assumption: 64-bit JVM so 64-bit pointers so pointer_size=8 bytes

Assumption: HashMap underlying array is 50% full (by default, at 75% full, the hashmap is rehashed with double the size), so hashmap_array_size = 2*n

```<code>memory = hashmap_array_size*bucket_size
+ n*chained_list_node_size
+ sum(key string sizes)
+ sum(list_string_size(string_list) for each hashmap List<String> value)

So:

memory = (n*2)*(8*2)
+ n*(8*2) + ((2 length_field + 3 string_length)*n)
+ (n*(8 + 3*(8*2)
+ 3*(2 length_field + 4 string_length))
= 2000000*(2*8*2 + 8*2 + (2+3) + (8 + 3*8*2 + 3*(2+4)))
= 254000000
= 254 MB

n = number of items in the hash map

bucket_size = pointer_size*2

chained_list_node_size = pointer_size*2

list_string_size(list) = pointer_size +
list.size()*list_string_node_size
+ sum(string value sizes in this List<String> list)

list_string_node_size = pointer_size*2

String length bytes = length_field_size + string_characters
(UTF-8 is 1 byte per ascii character)
(length_field_size = size of integer = 2)

Assume all keys are length 3.
(we have to assume something to calculate space used)
so: sum(key string sizes) = (2 length_field + 3 string_length)*n

Assume all value string-lists are length 3 and each string is of length 4. So:
sum(list_string_size(string_list) for each hashmap List<String> value)
= n*(8 + 3*(8*2) + 3*(2 length_field + 4 string_length))
</code>```

A simple test program would give a better real answer:

```<code>import java.util.*;
class TempTest {
    public static void main(String[] args) {
        HashMap<String, List<String>> map = new HashMap<>();
        System.gc();
        printMemory();
        for (int i = 0; i < 2000000; ++i) {
            map.put(String.valueOf(i), Arrays.asList(String.valueOf(i), String.valueOf(i) + "b", String.valueOf(i) + "c"));
        }
        System.gc();
        printMemory();
    }

    private static void printMemory() {
        Runtime runtime = Runtime.getRuntime();
        long totalMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();

        System.out.println("Memory: Used=" + (totalMemory - freeMemory) + " Total=" + totalMemory + " Free=" + freeMemory);
    }
}
</code>```

For me, this took 640MB (after.Used - before.Used).

Body:
I was asked in an interview to calculate the memory usage for HashMap and how much estimated memory it will consume if you have 2 million items in it.

For example:

Map <String,List<String>> mp=new HashMap <String,List<String>>();

The mapping is like this.

key   value
----- ---------------------------
abc   ['hello','how']
abz   ['hello','how','are','you']

How would I estimate the memory usage of this HashMap Object in Java?

Body:
Summary:

memory = hashmap_array_size*bucket_size
+ n*chained_list_node_size
+ sum(key string sizes)
+ sum(list_string_size(string_list) for each hashmap List<String> value)

= 254 MB
(theoretical in-interview estimate)

Test program total-memory-used-size for 2 million sample entries: (see below)
= 640 MB
(I recommend a simple test program like this for a quick true-total-size estimate)

A minimal estimate (actual implementation probably has a bit more overhead):

Assumed data structure:

Bucket: (Pointer to String key, Pointer to hash-chain-list first-node)

Chained List Node: (Pointer to List<String> value, Next-pointer)
(HashMap is a chained hash - each bucket has a list/tree of values)
(as of Java 8, the list switches to a tree after 8 items)

List<String> instance: (Pointer to first node)

List<String> Node: (Pointer to String value, Next-pointer)

Assumption to simplify this estimate: zero collisions, each bucket has max 1 value (ask interviewer if this is ok - to give a rough, initial answer)

Assumption: 64-bit JVM so 64-bit pointers so pointer_size=8 bytes

Assumption: HashMap underlying array is 50% full (by default, at 75% full, the hashmap is rehashed with double the size), so hashmap_array_size = 2*n

memory = hashmap_array_size*bucket_size
+ n*chained_list_node_size
+ sum(key string sizes)
+ sum(list_string_size(string_list) for each hashmap List<String> value)

So:

memory = (n*2)*(8*2)
+ n*(8*2) + ((2 length_field + 3 string_length)*n)
+ (n*(8 + 3*(8*2)
+ 3*(2 length_field + 4 string_length))
= 2000000*(2*8*2 + 8*2 + (2+3) + (8 + 3*8*2 + 3*(2+4)))
= 254000000
= 254 MB

n = number of items in the hash map

bucket_size = pointer_size*2

chained_list_node_size = pointer_size*2

list_string_size(list) = pointer_size +
list.size()*list_string_node_size
+ sum(string value sizes in this List<String> list)

list_string_node_size = pointer_size*2

String length bytes = length_field_size + string_characters
(UTF-8 is 1 byte per ascii character)
(length_field_size = size of integer = 2)

Assume all keys are length 3.
(we have to assume something to calculate space used)
so: sum(key string sizes) = (2 length_field + 3 string_length)*n

Assume all value string-lists are length 3 and each string is of length 4. So:
sum(list_string_size(string_list) for each hashmap List<String> value)
= n*(8 + 3*(8*2) + 3*(2 length_field + 4 string_length))

A simple test program would give a better real answer:

import java.util.*;
class TempTest {
    public static void main(String[] args) {
        HashMap<String, List<String>> map = new HashMap<>();
        System.gc();
        printMemory();
        for (int i = 0; i < 2000000; ++i) {
            map.put(String.valueOf(i), Arrays.asList(String.valueOf(i), String.valueOf(i) + "b", String.valueOf(i) + "c"));
        }
        System.gc();
        printMemory();
    }

    private static void printMemory() {
        Runtime runtime = Runtime.getRuntime();
        long totalMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();

        System.out.println("Memory: Used=" + (totalMemory - freeMemory) + " Total=" + totalMemory + " Free=" + freeMemory);
    }
}

For me, this took 640MB (after.Used - before.Used).


来源: stackexchange

问:
Filtering elements of array on the basis of dates
I have a array as follows:

data = [
    {
      "startDate": "2021-08-18T00:00:04.498059"
      "endDate": "2021-08-19T00:00:04.4962889"
    },
    {
      "startDate": "2021-08-18T00:00:04.498059"
      "endDate": "2021-08-19T00:00:04.4962889"
    }
    ]

    newArray = [];
    this.data.foreach(element => {
       if((element.startDate - element.endDate) > 7) {
           this.newArray.push(element);
       }
    })```

I want to traverse the above array and check if difference between startDate and endDate is greater than 7 days for any element, than push that element to a new array.

Because of the date format I don't know my approach is correct or not. How can I do this correctly?

答:
I think this is the one you are looking for:

let data = [
{
  startDate: "2021-08-18T00:00:04.498059",
  endDate: "2021-08-19T00:00:04.4962889",
},
{
  startDate: "2021-08-11T00:00:04.498059",
  endDate: "2021-08-19T00:00:04.4962889",
}
]

let newArray = [];
data.forEach(element => {
let start = new Date(element.startDate)
let end = new Date(element.endDate)
if((end-start)/1000/60/60/24 > 7)
      newArray.push(element);
   })
   console.log(newArray)```

ContentLicense: CC BY-SA 4.0

Body:
I have a array as follows:

data = [
    {
      "startDate": "2021-08-18T00:00:04.498059"
      "endDate": "2021-08-19T00:00:04.4962889"
    },
    {
      "startDate": "2021-08-18T00:00:04.498059"
      "endDate": "2021-08-19T00:00:04.4962889"
    }
    ]

    newArray = [];
    this.data.foreach(element => {
       if((element.startDate - element.endDate) > 7) {
           this.newArray.push(element);
       }
    })

I want to traverse the above array and check if difference between startDate and endDate is greater than 7 days for any element, than push that element to a new array.

Because of the date format I don't know my approach is correct or not. How can I do this correctly?


问:
Netbeans 6.9 / 7.0 Subversion Checkout Not Working?
When exporting a netbeans project from an svn repository. It downloads everything in the respository to the folder I've specified in the default

My Documents/NetBeansProjects

directory but it doesn't create the .svn folders for the project like it's supposed to. (It doesn't put the project under subversion control)

This has been drving me nuts because I can't seem to get any of my work under subversion control in Netbeans.

I'm running Windows 7 x64.

EDIT:

Here are the steps that I take to attempt to check-out a project from my servers repository so that I can work with it and keep it under version control in netbeans v6.9.

I go to:

Team->Subversion->Checkout...

In the Checkout dialog box that appears I enter my repository's URL and my credentials then click the next button.

Once it connects to the repository I select the checkbox "Export a clean directory tree from the repository"

In the Local Folder input I specify the path where I want my project to be. "C:\Users\Mark\Documents\NetBeansProjects\MyProjectExample"

Then I click the Finish button and get the result I stated previously. When I was running netbeans 6.8, I believe I followed the same steps without any issue and NO, I'm not going switch back to 6.8

答: Selecting 'Export a clean directory tree from the repository' when checking out the code from Subversion will check out the code without the .svn files and folders. Without those files and folders, your code will not be under source control. So try exporting but this time do not select the 'Export a clean directory tree from the repository' checkbox.</p>

ContentLicense: CC BY-SA 3.0


问:
Mac The operation couldn’t be completed. Unable to locate a Java Runtime that supports jarsigner
My purpose is to use jarsigner to sign apk.

I get the following prompt：

```<code>% jarsigner
The operation couldn’t be completed. Unable to locate a Java Runtime that supports jarsigner.
Please visit http://www.java.com for information on installing Java.
</code>```

my java version hint：

```<code>% java -version
java version "1.8.0_321"
Java(TM) SE Runtime Environment (build 1.8.0_321-b07)
Java HotSpot(TM) 64-Bit Server VM (build 25.321-b07, mixed mode)
</code>```

Mac version is 11.6.3

How can I solve this problem please?

答: I finally solved it by downloading the JDK</p>

Body:
My purpose is to use jarsigner to sign apk.

I get the following prompt：

% jarsigner
The operation couldn’t be completed. Unable to locate a Java Runtime that supports jarsigner.
Please visit http://www.java.com for information on installing Java.

my java version hint：

% java -version
java version "1.8.0_321"
Java(TM) SE Runtime Environment (build 1.8.0_321-b07)
Java HotSpot(TM) 64-Bit Server VM (build 25.321-b07, mixed mode)

Mac version is 11.6.3

How can I solve this problem please?


问:
Deep merge of complex state in React
When I have the following initial state declared:

```<code>  getInitialState: function() {
    return {
      isValid: false,
      metaData: {
        age: 12,
        content_type: 'short_url'
      }
    };
  },
</code>```

and I update state with setState like this:

```<code>...
let newMetaData = {  age: 20 };
...
this.setState({
        isValid: true,
        metaData: newMetaData
      });
...
</code>```

Resulting this.state.metadata object has only age defined. But as far as I'm aware, this.setState() merges it argument to existing state. Why it's not working here, isn't this supposed to be recurrent merging?

Is there a way to merge new object properties to state object property in React/ES6?

答:
Another way to approach this, if you only need to update one property, would be like this:</p>
```<code>this.setState({
  metaData: {
    ...this.state.metaData,
    age: 20
  }
})
</code>```

Title: Deep merge of complex state in React

Body:
When I have the following initial state declared:

  getInitialState: function() {
    return {
      isValid: false,
      metaData: {
        age: 12,
        content_type: 'short_url'
      }
    };
  },

and I update state with setState like this:

...
let newMetaData = {  age: 20 };
...
this.setState({
        isValid: true,
        metaData: newMetaData
      });
...

Resulting this.state.metadata object has only age defined. But as far as I'm aware, this.setState() merges it argument to existing state. Why it's not working here, isn't this supposed to be recurrent merging?

Is there a way to merge new object properties to state object property in React/ES6?

Body:
Another way to approach this, if you only need to update one property, would be like this:

this.setState({
  metaData: {
    ...this.state.metaData,
    age: 20
  }
})


问:
Flutter how to load api data when scroll down
here is my app fetch data from API at once and display them on listview, I want to display 10 items and when the client scroll down I want to display the rest, also 10 items till the length of the api data
please any help</p>
```<code>Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          endDrawer: NavigationDrawerWidget(),
          appBar: AppBar(
            automaticallyImplyLeading: true,
            backgroundColor: Colors.black,
            title: Text("      الصبر   "),
            centerTitle: true,
          ),
          backgroundColor: Colors.grey[900],
          body: FutureBuilder(
              future: getData(),
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                List snap = snapshot.data;

                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Center(child: CircularProgressIndicator());
                }
                if (snapshot.hasError) {
                  return Center(
                    child: Text("error"),
                  );
                }
                return ListView.separated(
                  itemCount: snap.length,
                  separatorBuilder: (context, index) {
                    final data = snap[index];
                    final dataJoke = data["joke"];
                    final dataAnswer = data["answer"];

                    return Card(
                      elevation: 6,

     margin: EdgeInsets.symmetric(vertical: 3, horizontal: 6),
                  child: Container(
                    color: Colors.grey[600],
                    child: ListTile(
                      title: Text(
                        " ${snap[index]['joke']}",
                        textDirection: TextDirection.rtl,
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
</code>```

答:
You can use a package to achieve this feature, which is called infinite_scroll_pagination:
https://pub.dev/packages/infinite_scroll_pagination

There's example code in the package README

Body:
here is my app fetch data from API at once and display them on listview, I want to display 10 items and when the client scroll down I want to display the rest, also 10 items till the length of the api data
please any help

Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          endDrawer: NavigationDrawerWidget(),
          appBar: AppBar(
            automaticallyImplyLeading: true,
            backgroundColor: Colors.black,
            title: Text("      الصبر   "),
            centerTitle: true,
          ),
          backgroundColor: Colors.grey[900],
          body: FutureBuilder(
              future: getData(),
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                List snap = snapshot.data;

                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Center(child: CircularProgressIndicator());
                }
                if (snapshot.hasError) {
                  return Center(
                    child: Text("error"),
                  );
                }
                return ListView.separated(
                  itemCount: snap.length,
                  separatorBuilder: (context, index) {
                    final data = snap[index];
                    final dataJoke = data["joke"];
                    final dataAnswer = data["answer"];

                    return Card(
                      elevation: 6,

     margin: EdgeInsets.symmetric(vertical: 3, horizontal: 6),
                  child: Container(
                    color: Colors.grey[600],
                    child: ListTile(
                      title: Text(
                        " ${snap[index]['joke']}",
                        textDirection: TextDirection.rtl,
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),


问:
How to send SMS from asp.net application

Possible Duplicate:

  sms from our site

I want to send SMS from my asp.net application. Suppose there will be 2 text boxes in my UI, one for mobile or cell phone number and another one is for message writing. When I will click the submit button then this SMS will be send to that cell number.
I want to use my cell phone number as transmission number.
Please inform me the possible ways.
I am using asp.net C#

答:
There are several services which offer this kind of SMS Gateway API.

http://www.fastsms.co.uk/solutions/developer-api/developer-api.html
http://www.esendex.co.uk/Services/SMS-API

Or just search for "SMS Gateway API" for load more


问:
Does indexing works with "WITH" in Oracle
I have query something like

```<code>WITH
str_table as (
  SELECT stringtext, stringnumberid
  FROM STRING_TABLE
  WHERE LANGID IN (23,62)
),
data as (
  select *
  from employee emp
  left outer join str_table st on emp.nameid = st.stringnumberid
)
select * from data
</code>```

I know With clause will work in this manner

Step 1 : The SQL Query within the with clause is executed at first step.

Step 2 : The output of the SQL query is stored into temporary relation of with clause.

Step 3 : The Main query is executed with temporary relation produced at the last stage.

Now I want to ask whether the indexes created on the actual STRING_TABLE are going to help in temporary str_table produce by the With clause? I want to ask whether the indexes also have impact on str_table or not?

答:
Oracle will not process CTE one by one. It will analyze the SQL as a whole. Your SQL is most likely the same as following in the eye of Oracle optimizer

```<code>select emp.*
from employee emp left outer join STRING_TABLE st
on emp.nameid = st.stringnumberid
where   st.LANGID IN (23,62);
</code>```

Oracle can use index on STRING_TABLE. Whether it will depends on the table statistics. For example, if the table has few rows (say a few hundred), Oracle will likely not use index.

Body:
I have query something like

WITH
str_table as (
  SELECT stringtext, stringnumberid
  FROM STRING_TABLE
  WHERE LANGID IN (23,62)
),
data as (
  select *
  from employee emp
  left outer join str_table st on emp.nameid = st.stringnumberid
)
select * from data

I know With clause will work in this manner

Step 1 : The SQL Query within the with clause is executed at first step.

Step 2 : The output of the SQL query is stored into temporary relation of with clause.

Step 3 : The Main query is executed with temporary relation produced at the last stage.

Now I want to ask whether the indexes created on the actual STRING_TABLE are going to help in temporary str_table produce by the With clause? I want to ask whether the indexes also have impact on str_table or not?

Body:
Oracle will not process CTE one by one. It will analyze the SQL as a whole. Your SQL is most likely the same as following in the eye of Oracle optimizer

select emp.*
from employee emp left outer join STRING_TABLE st
on emp.nameid = st.stringnumberid
where   st.LANGID IN (23,62);

Oracle can use index on STRING_TABLE. Whether it will depends on the table statistics. For example, if the table has few rows (say a few hundred), Oracle will likely not use index.


问:
How to force language in which reverse geocoding data on iOS is received?
When i call

```<code>geocoder reverseGeocodeLocation:currentLoc completionHandler:
</code>```

i get all the data (city, county, ...) in a language according to locale set on iphone.

How can i force to always get this data in English?

答:
just put Locale to specific your language</p>
```<code>let locale = Locale(identifier: "en_US")
CLGeocoder().reverseGeocodeLocation(location, preferredLocale: locale, completionHandler: {(placemarks, error) in

})
</code>```

Body:
When i call

geocoder reverseGeocodeLocation:currentLoc completionHandler:

i get all the data (city, county, ...) in a language according to locale set on iphone.

How can i force to always get this data in English?

Body:
just put Locale to specific your language

let locale = Locale(identifier: "en_US")
CLGeocoder().reverseGeocodeLocation(location, preferredLocale: locale, completionHandler: {(placemarks, error) in

})


问:
Docker run env variable does not work with single quotes?
I was running the following command:

```<code>docker run -e 'SOME_ENV_VARIABLE=somevalue' somecommand
</code>```

And this did not pass the env variable to somecommand (Note: SOME_ENV_VARIABLE and somevalue did not have un-escaped single quotes, they were capital snake case and lowercase respectively without special character.

Later, I tried:

```<code>docker run -e "SOME_ENV_VARIABLE=somevalue" somecommand
</code>```

And this somehow worked (note the double quotes).

Why is this? I have seen documentation with single quotes.

I tried this on Windows.

答:
Quotation is handled by your shell - since you are on windows, that is cmd.exe. And, from what I understand, since cmd.exe does not handle single quotes, it will pass that argument with the quotes to docker.

It would work on Linux though (which usually has the bash shell), being the the environment many people would use docker on, and as such the reason it is present in a lot of documentation.

Body:
I was running the following command:

docker run -e 'SOME_ENV_VARIABLE=somevalue' somecommand

And this did not pass the env variable to somecommand (Note: SOME_ENV_VARIABLE and somevalue did not have un-escaped single quotes, they were capital snake case and lowercase respectively without special character.

Later, I tried:

docker run -e "SOME_ENV_VARIABLE=somevalue" somecommand

And this somehow worked (note the double quotes).

Why is this? I have seen documentation with single quotes.

I tried this on Windows.


问:
Determine the common prefix of multiple strings
I have a set of strings, e.g.

```<code>my_prefix_what_ever
my_prefix_what_so_ever
my_prefix_doesnt_matter
</code>```

I simply want to find the longest common portion of these strings, here the prefix. In the above the result should be

```<code>my_prefix_
</code>```

The strings

```<code>my_prefix_what_ever
my_prefix_what_so_ever
my_doesnt_matter
</code>```

should result in the prefix

```<code>my_
</code>```

Is there a relatively painless way in Python to determine the prefix (without having to iterate over each character manually)?

PS: I'm using Python 2.6.3.

答:
Find the common prefix in all words from the given input string, if there is no common prefix print -1</p>
```<code>stringList = ['my_prefix_what_ever', 'my_prefix_what_so_ever', 'my_prefix_doesnt_matter']
len2 = len( stringList )
if len2 != 0:
    # let shortest word is prefix
    prefix = min( stringList )
    for i in range( len2 ):
        word = stringList[ i ]
        len1 = len( prefix )
        # slicing each word as lenght of prefix
        word = word[ 0:len1 ]
        for j in range( len1 ):
            # comparing each letter of word and prefix
            if word[ j ] != prefix[ j ]:
                # if letter does not match slice the prefix
                prefix = prefix[ :j ]
                break # after getting comman prefix move to next word
    if len( prefix ) != 0:
        print("common prefix: ",prefix)
    else:
        print("-1")
else:
     print("string List is empty")
</code>```

Body:
I have a set of strings, e.g.

my_prefix_what_ever
my_prefix_what_so_ever
my_prefix_doesnt_matter

I simply want to find the longest common portion of these strings, here the prefix. In the above the result should be

my_prefix_

The strings

my_prefix_what_ever
my_prefix_what_so_ever
my_doesnt_matter

should result in the prefix

my_

Is there a relatively painless way in Python to determine the prefix (without having to iterate over each character manually)?

PS: I'm using Python 2.6.3.

Body:
Find the common prefix in all words from the given input string, if there is no common prefix print -1

stringList = ['my_prefix_what_ever', 'my_prefix_what_so_ever', 'my_prefix_doesnt_matter']
len2 = len( stringList )
if len2 != 0:
    # let shortest word is prefix
    prefix = min( stringList )
    for i in range( len2 ):
        word = stringList[ i ]
        len1 = len( prefix )
        # slicing each word as lenght of prefix
        word = word[ 0:len1 ]
        for j in range( len1 ):
            # comparing each letter of word and prefix
            if word[ j ] != prefix[ j ]:
                # if letter does not match slice the prefix
                prefix = prefix[ :j ]
                break # after getting comman prefix move to next word
    if len( prefix ) != 0:
        print("common prefix: ",prefix)
    else:
        print("-1")
else:
     print("string List is empty")


问:
How to get prediction scores between 0 and 1 (or -1 and 1)?
I am training a model that adds a couple of layers to the predifined VGGish network (see github repo), so that it can predict the class of input logmel spectrograms extracted from audio files (full code at bottom).

I generate X_train, X_test, y_train, y_test sets from a previous function first and then run the main() codeblock. This predicts the classes of the X_test at line 78 and prints these:

```<code>predictions_sigm = logits.eval(feed_dict = {features_input:X_test})
print(predictions)
</code>```

Prints:

```<code>[[ -9.074987    8.840093   -8.426974 ]
 [ -9.376444    9.13514    -8.79967  ]
 [-10.03653    -7.725624    7.2162223]
 [ -9.650997    9.308293   -8.9559   ]
 [  7.789041   -7.8485446  -9.8974285]
 [  7.7869387  -7.850354   -9.899081 ]
 [-10.4985485  -8.368322    7.558868 ]
 [-10.306433   -8.043555    7.4093537]
 [  7.787068   -7.850254   -9.898217 ]
 [  7.789579   -7.851698   -9.90515  ]
 [  7.787512   -7.8483863  -9.90212  ]
 [ -9.28933     9.058059   -8.713937 ]
 [  7.7886     -7.8486743  -9.901876 ]
 [  7.7899137  -7.8464875  -9.899316 ]
 [-10.434939   -8.171508    7.459009 ]
 [-10.714449   -8.394194    7.642472 ]
 [-10.564347   -8.165948    7.6475844]
 [ -9.63355     9.158067   -8.794765 ]
 [ -9.501944    9.241178   -8.889491 ]]
</code>```

My main query is how do I get the array to instead print like this, where it returns 0's and 1's or values between -1 to 1 for each prediction, which I can then convert to 0's and 1's:

```<code>[[ 0   1   0 ]
 [ 0   1   0 ]
 [ 0   0    1]
 ...
 [ 0   1   0 ]]
</code>```

I thought this could be done using predictions_sigm = prediction.eval(...) for this line (78) instead of predictions_sigm = logits.eval(...), as it appeared to be named 'prediction' and use sigmoid some how, at line 27 tf.sigmoid(logits, name='prediction'), but using this gives a 'NameError: name 'prediction' is not defined'.

If presented as a  range of values, either -11 to 10 or -1 to 0, are their values useful for something?

Full code:

```<code>#run using:
   #python vggish_train_demo.py --num_batches 100
_NUM_CLASSES = 3
batch_size = 10

def main(X):
  with tf.Graph().as_default(), tf.Session() as sess:
    # Define VGGish.
    embeddings = vggish_slim.define_vggish_slim(training=FLAGS.train_vggish)

    # Define a shallow classification model and associated training ops on top
    # of VGGish.
    with tf.variable_scope('mymodel'):
      # Add a fully connected layer with 100 units. Add an activation function
      # to the embeddings since they are pre-activation.
      num_units = 100
      fc = slim.fully_connected(tf.nn.relu(embeddings), num_units)

      # Add a classifier layer at the end, consisting of parallel logistic
      # classifiers, one per class. This allows for multi-class tasks.
      logits = slim.fully_connected(
          fc, _NUM_CLASSES, activation_fn=None, scope='logits')
      tf.sigmoid(logits, name='prediction')

      # Add training ops.
      with tf.variable_scope('train'):
        global_step = tf.train.create_global_step()

        # Labels are assumed to be fed as a batch multi-hot vectors, with
        # a 1 in the position of each positive class label, and 0 elsewhere.
        labels_input = tf.placeholder(
            tf.float32, shape=(None, _NUM_CLASSES), name='labels')

        # Cross-entropy label loss.
        xent = tf.nn.sigmoid_cross_entropy_with_logits(
            logits=logits, labels=labels_input, name='xent')
        loss = tf.reduce_mean(xent, name='loss_op')
        tf.summary.scalar('loss', loss)

        # We use the same optimizer and hyperparameters as used to train VGGish.
        optimizer = tf.train.AdamOptimizer(
            learning_rate=vggish_params.LEARNING_RATE,
            epsilon=vggish_params.ADAM_EPSILON)
        train_op = optimizer.minimize(loss, global_step=global_step)

    # Initialize all variables in the model, and then load the pre-trained
    # VGGish checkpoint.
    sess.run(tf.global_variables_initializer())
    vggish_slim.load_vggish_slim_checkpoint(sess, FLAGS.checkpoint)

    # The training loop.
    features_input = sess.graph.get_tensor_by_name(
        vggish_params.INPUT_TENSOR_NAME)

    for epoch in range(FLAGS.num_batches):
            epoch_loss = 0
            i=0
            while i < len(X_train):
                start = i
                end = i+batch_size
                batch_x = np.array(X_train[start:end])
                batch_y = np.array(y_train[start:end])

                _, c = sess.run([train_op, loss], feed_dict={features_input: batch_x, labels_input: batch_y})
                epoch_loss += c
                i+=batch_size

            print('Epoch', epoch+1, 'completed out of',FLAGS.num_batches,', loss:',epoch_loss)

    correct = tf.equal(tf.argmax(logits, 1), tf.argmax(labels_input, 1))
    print('Accuracy:',accuracy.eval({features_input:X_test, labels_input:y_test}))

    predictions = logits.eval(feed_dict = {features_input:X_test})
    print(predictions) #shows table of predictions

    #Saves csv file of table of predictions for test data
    time = datetime.now().strftime('%H.%M.%S')
    np.savetxt("test_predictions_"+time+".csv", predictionsm, delimiter=",") #put 'r"r'C:\Users\bw339\...\test_predictions' to save in a different folder

if __name__ == '__main__':
  tf.app.run()

#think the 'An exception has occurred, use %tb to see the full traceback.' is a jupyter thing, hopefully won't happen
 #when run in conda or bash
</code>```

Edit for ahmet hamza emra

```<code>def main(X):
  with tf.Graph().as_default(), tf.Session() as sess:
    # Define VGGish.
    embeddings = vggish_slim.define_vggish_slim(training=FLAGS.train_vggish)
    #embeddings = vggish_slim.define_vggish_slim(features_tensor= X_train, training=FLAGS.train_vggish) #gives an error that arrays are not right type. no idea why as the shpae of X[0] matches what vggish_slim_define() asks for

    #prediction = vggish_slim.define_vggish_slim(X)

    # Define a shallow classification model and associated training ops on top
    # of VGGish.
    with tf.variable_scope('mymodel'):
      # Add a fully connected layer with 100 units. Add an activation function
      # to the embeddings since they are pre-activation.
      num_units = 100
      fc = slim.fully_connected(tf.nn.relu(embeddings), num_units)

      # Add a classifier layer at the end, consisting of parallel logistic
      # classifiers, one per class. This allows for multi-class tasks.
      #logits = slim.fully_connected(                                      ### logits threw me, would be easier to name this 'end model' or something
       #   fc, _NUM_CLASSES, activation_fn=None, scope='logits')
      #tf.sigmoid(logits, name='prediction')

      linear_out= slim.fully_connected(
          fc, _NUM_CLASSES, activation_fn=None, scope='linear_out')
      logits = tf.sigmoid(logits, name='logits')

      # Add training ops.
      with tf.variable_scope('train'):
        global_step = tf.train.create_global_step()

        # Labels are assumed to be fed as a batch multi-hot vectors, with
        # a 1 in the position of each positive class label, and 0 elsewhere.
        labels_input = tf.placeholder(
            tf.float32, shape=(None, _NUM_CLASSES), name='labels')

        # Cross-entropy label loss.
        xent = tf.nn.sigmoid_cross_entropy_with_logits(
            logits=logits, labels=labels_input, name='xent')    ###=labels is selecting my 'y', logits is like a precursor to predictions?
        loss = tf.reduce_mean(xent, name='loss_op')
        tf.summary.scalar('loss', loss)

        # We use the same optimizer and hyperparameters as used to train VGGish.
        optimizer = tf.train.AdamOptimizer(
            learning_rate=vggish_params.LEARNING_RATE,
            epsilon=vggish_params.ADAM_EPSILON)
        train_op = optimizer.minimize(loss, global_step=global_step)

    # Initialize all variables in the model, and then load the pre-trained
    # VGGish checkpoint.
    sess.run(tf.global_variables_initializer())         ### this starts the session appaz
    vggish_slim.load_vggish_slim_checkpoint(sess, FLAGS.checkpoint)

    # The training loop.
    features_input = sess.graph.get_tensor_by_name(
        vggish_params.INPUT_TENSOR_NAME)

    for epoch in range(FLAGS.num_batches):
            epoch_loss = 0
            i=0
            while i < len(X_train):
                start = i
                end = i+batch_size
                batch_x = np.array(X_train[start:end])
                batch_y = np.array(y_train[start:end])

                _, c = sess.run([train_op, loss], feed_dict={features_input: batch_x, labels_input: batch_y})
                epoch_loss += c
                i+=batch_size

            print('Epoch', epoch+1, 'completed out of',FLAGS.num_batches,', loss:',epoch_loss)

    #Get accuracy if executed on test data
    correct = tf.equal(tf.argmax(logits, 1), tf.argmax(labels_input, 1)) #This line returns the max value of each array, which we want o be the same (think the prediction/logits is value given to each class with the highest value being the best match)
    accuracy = tf.reduce_mean(tf.cast(correct, 'float')) #changes correct to type: float
    print('Accuracy:',accuracy.eval({features_input:X_test, labels_input:y_test})) #TF is smart so just knows to feed it through the model without us seeming to tell it to. .eval() uses the current session which I guess is my model?

    #Save predictions for test data
    predictions_sigm = logits.eval(feed_dict = {features_input:X_test}) #not really _sigm, change back later
    #print(predictions_sigm) #shows table of predictions
    test_preds = pd.DataFrame(predictions_sigm, columns = col_names)  #converts predictions to df
    true_class = np.argmax(y_test, axis = 1)     #This saves the true class
    test_preds['True class'] = true_class        #This adds true class to the df
    print(test_preds)

    #Saves csv file of table of predictions for test data. NB. header will not save when using np.text for some reason
    time = datetime.now().strftime('%H.%M.%S')
    #np.savetxt("test_predictions_"+time+".csv", test_preds.values, delimiter=",") #put 'r"r'C:\Users\bw339\...\test_predictions' to save in a different folder

    ##Save model
    #saver = tf.train.Saver()
    #saver.save(sess, 'my-test-model')

if __name__ == '__main__':
  tf.app.run()

#think the 'An exception has occurred, use %tb to see the full traceback.' is a jupyter thing, hopefully won't happen
 #when run in conda or bash
</code>```

答:
You are outputing the linear-layer before the sigmoid. Change the code as following:

```<code>    # Add a classifier layer at the end, consisting of parallel logistic
    # classifiers, one per class. This allows for multi-class tasks.
    linear_out= slim.fully_connected(
          fc, _NUM_CLASSES, activation_fn=None, scope='linear_out')
    logits = tf.sigmoid(linear_out, name='logits')

</code>```

This will ensure you output the values between 0 and 1.

Note: Your evaluation is not considering multi-class classification, argmax will return the index of the largest value which in your case will be single output.

Body:
I am training a model that adds a couple of layers to the predifined VGGish network (see github repo), so that it can predict the class of input logmel spectrograms extracted from audio files (full code at bottom).

I generate X_train, X_test, y_train, y_test sets from a previous function first and then run the main() codeblock. This predicts the classes of the X_test at line 78 and prints these:

predictions_sigm = logits.eval(feed_dict = {features_input:X_test})
print(predictions)

Prints:

[[ -9.074987    8.840093   -8.426974 ]
 [ -9.376444    9.13514    -8.79967  ]
 [-10.03653    -7.725624    7.2162223]
 [ -9.650997    9.308293   -8.9559   ]
 [  7.789041   -7.8485446  -9.8974285]
 [  7.7869387  -7.850354   -9.899081 ]
 [-10.4985485  -8.368322    7.558868 ]
 [-10.306433   -8.043555    7.4093537]
 [  7.787068   -7.850254   -9.898217 ]
 [  7.789579   -7.851698   -9.90515  ]
 [  7.787512   -7.8483863  -9.90212  ]
 [ -9.28933     9.058059   -8.713937 ]
 [  7.7886     -7.8486743  -9.901876 ]
 [  7.7899137  -7.8464875  -9.899316 ]
 [-10.434939   -8.171508    7.459009 ]
 [-10.714449   -8.394194    7.642472 ]
 [-10.564347   -8.165948    7.6475844]
 [ -9.63355     9.158067   -8.794765 ]
 [ -9.501944    9.241178   -8.889491 ]]

My main query is how do I get the array to instead print like this, where it returns 0's and 1's or values between -1 to 1 for each prediction, which I can then convert to 0's and 1's:

[[ 0   1   0 ]
 [ 0   1   0 ]
 [ 0   0    1]
 ...
 [ 0   1   0 ]]

I thought this could be done using predictions_sigm = prediction.eval(...) for this line (78) instead of predictions_sigm = logits.eval(...), as it appeared to be named 'prediction' and use sigmoid some how, at line 27 tf.sigmoid(logits, name='prediction'), but using this gives a 'NameError: name 'prediction' is not defined'.

If presented as a  range of values, either -11 to 10 or -1 to 0, are their values useful for something?

Full code:

#run using:
   #python vggish_train_demo.py --num_batches 100
_NUM_CLASSES = 3
batch_size = 10

def main(X):
  with tf.Graph().as_default(), tf.Session() as sess:
    # Define VGGish.
    embeddings = vggish_slim.define_vggish_slim(training=FLAGS.train_vggish)

    # Define a shallow classification model and associated training ops on top
    # of VGGish.
    with tf.variable_scope('mymodel'):
      # Add a fully connected layer with 100 units. Add an activation function
      # to the embeddings since they are pre-activation.
      num_units = 100
      fc = slim.fully_connected(tf.nn.relu(embeddings), num_units)

      # Add a classifier layer at the end, consisting of parallel logistic
      # classifiers, one per class. This allows for multi-class tasks.
      logits = slim.fully_connected(
          fc, _NUM_CLASSES, activation_fn=None, scope='logits')
      tf.sigmoid(logits, name='prediction')

      # Add training ops.
      with tf.variable_scope('train'):
        global_step = tf.train.create_global_step()

        # Labels are assumed to be fed as a batch multi-hot vectors, with
        # a 1 in the position of each positive class label, and 0 elsewhere.
        labels_input = tf.placeholder(
            tf.float32, shape=(None, _NUM_CLASSES), name='labels')

        # Cross-entropy label loss.
        xent = tf.nn.sigmoid_cross_entropy_with_logits(
            logits=logits, labels=labels_input, name='xent')
        loss = tf.reduce_mean(xent, name='loss_op')
        tf.summary.scalar('loss', loss)

        # We use the same optimizer and hyperparameters as used to train VGGish.
        optimizer = tf.train.AdamOptimizer(
            learning_rate=vggish_params.LEARNING_RATE,
            epsilon=vggish_params.ADAM_EPSILON)
        train_op = optimizer.minimize(loss, global_step=global_step)

    # Initialize all variables in the model, and then load the pre-trained
    # VGGish checkpoint.
    sess.run(tf.global_variables_initializer())
    vggish_slim.load_vggish_slim_checkpoint(sess, FLAGS.checkpoint)

    # The training loop.
    features_input = sess.graph.get_tensor_by_name(
        vggish_params.INPUT_TENSOR_NAME)

    for epoch in range(FLAGS.num_batches):
            epoch_loss = 0
            i=0
            while i < len(X_train):
                start = i
                end = i+batch_size
                batch_x = np.array(X_train[start:end])
                batch_y = np.array(y_train[start:end])

                _, c = sess.run([train_op, loss], feed_dict={features_input: batch_x, labels_input: batch_y})
                epoch_loss += c
                i+=batch_size

            print('Epoch', epoch+1, 'completed out of',FLAGS.num_batches,', loss:',epoch_loss)

    correct = tf.equal(tf.argmax(logits, 1), tf.argmax(labels_input, 1))
    print('Accuracy:',accuracy.eval({features_input:X_test, labels_input:y_test}))

    predictions = logits.eval(feed_dict = {features_input:X_test})
    print(predictions) #shows table of predictions

    #Saves csv file of table of predictions for test data
    time = datetime.now().strftime('%H.%M.%S')
    np.savetxt("test_predictions_"+time+".csv", predictionsm, delimiter=",") #put 'r"r'C:\Users\bw339\...\test_predictions' to save in a different folder

if __name__ == '__main__':
  tf.app.run()

#think the 'An exception has occurred, use %tb to see the full traceback.' is a jupyter thing, hopefully won't happen
 #when run in conda or bash

Edit for ahmet hamza emra

def main(X):
  with tf.Graph().as_default(), tf.Session() as sess:
    # Define VGGish.
    embeddings = vggish_slim.define_vggish_slim(training=FLAGS.train_vggish)
    #embeddings = vggish_slim.define_vggish_slim(features_tensor= X_train, training=FLAGS.train_vggish) #gives an error that arrays are not right type. no idea why as the shpae of X[0] matches what vggish_slim_define() asks for

    #prediction = vggish_slim.define_vggish_slim(X)

    # Define a shallow classification model and associated training ops on top
    # of VGGish.
    with tf.variable_scope('mymodel'):
      # Add a fully connected layer with 100 units. Add an activation function
      # to the embeddings since they are pre-activation.
      num_units = 100
      fc = slim.fully_connected(tf.nn.relu(embeddings), num_units)

      # Add a classifier layer at the end, consisting of parallel logistic
      # classifiers, one per class. This allows for multi-class tasks.
      #logits = slim.fully_connected(                                      ### logits threw me, would be easier to name this 'end model' or something
       #   fc, _NUM_CLASSES, activation_fn=None, scope='logits')
      #tf.sigmoid(logits, name='prediction')

      linear_out= slim.fully_connected(
          fc, _NUM_CLASSES, activation_fn=None, scope='linear_out')
      logits = tf.sigmoid(logits, name='logits')

      # Add training ops.
      with tf.variable_scope('train'):
        global_step = tf.train.create_global_step()

        # Labels are assumed to be fed as a batch multi-hot vectors, with
        # a 1 in the position of each positive class label, and 0 elsewhere.
        labels_input = tf.placeholder(
            tf.float32, shape=(None, _NUM_CLASSES), name='labels')

        # Cross-entropy label loss.
        xent = tf.nn.sigmoid_cross_entropy_with_logits(
            logits=logits, labels=labels_input, name='xent')    ###=labels is selecting my 'y', logits is like a precursor to predictions?
        loss = tf.reduce_mean(xent, name='loss_op')
        tf.summary.scalar('loss', loss)

        # We use the same optimizer and hyperparameters as used to train VGGish.
        optimizer = tf.train.AdamOptimizer(
            learning_rate=vggish_params.LEARNING_RATE,
            epsilon=vggish_params.ADAM_EPSILON)
        train_op = optimizer.minimize(loss, global_step=global_step)

    # Initialize all variables in the model, and then load the pre-trained
    # VGGish checkpoint.
    sess.run(tf.global_variables_initializer())         ### this starts the session appaz
    vggish_slim.load_vggish_slim_checkpoint(sess, FLAGS.checkpoint)

    # The training loop.
    features_input = sess.graph.get_tensor_by_name(
        vggish_params.INPUT_TENSOR_NAME)

    for epoch in range(FLAGS.num_batches):
            epoch_loss = 0
            i=0
            while i < len(X_train):
                start = i
                end = i+batch_size
                batch_x = np.array(X_train[start:end])
                batch_y = np.array(y_train[start:end])

                _, c = sess.run([train_op, loss], feed_dict={features_input: batch_x, labels_input: batch_y})
                epoch_loss += c
                i+=batch_size

            print('Epoch', epoch+1, 'completed out of',FLAGS.num_batches,', loss:',epoch_loss)

    #Get accuracy if executed on test data
    correct = tf.equal(tf.argmax(logits, 1), tf.argmax(labels_input, 1)) #This line returns the max value of each array, which we want o be the same (think the prediction/logits is value given to each class with the highest value being the best match)
    accuracy = tf.reduce_mean(tf.cast(correct, 'float')) #changes correct to type: float
    print('Accuracy:',accuracy.eval({features_input:X_test, labels_input:y_test})) #TF is smart so just knows to feed it through the model without us seeming to tell it to. .eval() uses the current session which I guess is my model?

    #Save predictions for test data
    predictions_sigm = logits.eval(feed_dict = {features_input:X_test}) #not really _sigm, change back later
    #print(predictions_sigm) #shows table of predictions
    test_preds = pd.DataFrame(predictions_sigm, columns = col_names)  #converts predictions to df
    true_class = np.argmax(y_test, axis = 1)     #This saves the true class
    test_preds['True class'] = true_class        #This adds true class to the df
    print(test_preds)

    #Saves csv file of table of predictions for test data. NB. header will not save when using np.text for some reason
    time = datetime.now().strftime('%H.%M.%S')
    #np.savetxt("test_predictions_"+time+".csv", test_preds.values, delimiter=",") #put 'r"r'C:\Users\bw339\...\test_predictions' to save in a different folder

    ##Save model
    #saver = tf.train.Saver()
    #saver.save(sess, 'my-test-model')

if __name__ == '__main__':
  tf.app.run()

#think the 'An exception has occurred, use %tb to see the full traceback.' is a jupyter thing, hopefully won't happen
 #when run in conda or bash

Body:
You are outputing the linear-layer before the sigmoid. Change the code as following:

    # Add a classifier layer at the end, consisting of parallel logistic
    # classifiers, one per class. This allows for multi-class tasks.
    linear_out= slim.fully_connected(
          fc, _NUM_CLASSES, activation_fn=None, scope='linear_out')
    logits = tf.sigmoid(linear_out, name='logits')

This will ensure you output the values between 0 and 1.

Note: Your evaluation is not considering multi-class classification, argmax will return the index of the largest value which in your case will be single output.


问:
Firebase signinwithemail&password is not a function
I recently have been making a app for my IOS app and am introducing firebase email/password auth to my project.  The registration part works good but when i do the handleSignin function it doesnt quite work as expected.  Any ideas why

my code:

```<code>import React from 'react';
import { Button,StyleSheet,View,Text, Image,SafeAreaView, TextInput, KeyboardAvoidingView, TouchableOpacity} from 'react-native';
import {auth} from "../firebase"
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword} from "firebase/auth";
import { FirebaseError } from 'firebase/app';

export const Login = () => {
    const [email, setEmail] = React.useState("")
   const [password, setPassword] = React.useState("")
  const handleSignUp = (e) => {
    createUserWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      // Signed in
      const user = userCredential.user;
      // ...
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
      // ..
    });
  }
  const handleLogin  =  () => {
    auth
    .signInWithEmailAndPassword(email, password)
    .then(userCredentials => {
      const user = userCredentials.user;
      console.log('Logged in with:', user.email);
    })
    .catch(error => alert(error.message))
  }

  return (
    <KeyboardAvoidingView
    style={styles.container}
    behavior="padding"
  >
    <Text style={styles.heading}>Unlock the power of time managment</Text>
    <View style={styles.inputContainer}>
      <TextInput
      value={email}
        placeholder="Email"
        style={styles.input}
        onChangeText={text => setEmail(text)}
      />
      <TextInput
        placeholder="Password"
        style={styles.input}
        onChangeText={text => setPassword(text)}
        value={password}
        secureTextEntry
      />
    </View>

    <View style={styles.buttonContainer}>
      <TouchableOpacity
        style={styles.button}
        onPress={handleLogin}
      >
        <Text style={styles.buttonText}>Login</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={[styles.button, styles.buttonOutline]}
        onPress={handleSignUp}
      >
        <Text style={styles.buttonOutlineText} >Register</Text>
      </TouchableOpacity>
    </View>
  </KeyboardAvoidingView>
  )
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  inputContainer: {
    width: '80%'
  },
  input: {
    backgroundColor: 'white',
    paddingHorizontal: 15,
    paddingVertical: 10,
    borderRadius: 10,
    marginTop: 5,
  },
  heading: {
    fontSize: 30,
    fontWeight: "700"
  },
  buttonContainer: {
    width: '60%',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 40,
  },
  button: {
    backgroundColor: '#0782F9',
    width: '100%',
    padding: 15,
    borderRadius: 10,
    alignItems: 'center',
  },
  buttonOutline: {
    backgroundColor: 'white',
    marginTop: 5,
    borderColor: '#0782F9',
    borderWidth: 2,
  },
  buttonText: {
    color: 'white',
    fontWeight: '700',
    fontSize: 16,
  },
  buttonOutlineText: {
    color: '#0782F9',
    fontWeight: '700',
    fontSize: 16,
  },
});
</code>```

expo go error:
firebase.auth.signinwithemailandpassword not a function
firebase.auth.signinwithemailandpassword returned undefined

答:
You're using the new, modular SDK syntax, where most functionality is exposed as a top-level function, instead of as a method on an object. When you call createUserWithEmailAndPassword as a top-level function you pass in the auth object, and you need to do the same for signing in:

```<code>const handleLogin  =  () => {
  signInWithEmailAndPassword(auth, email, password)
  ...
</code>```

I recommend keeping the Firebase documentation handy when troubleshooting problems like this, as the above is almost exactly the code shown in the Web version 9 (modular) tab in the section signing in a user with an email address and password

Body:
I recently have been making a app for my IOS app and am introducing firebase email/password auth to my project.  The registration part works good but when i do the handleSignin function it doesnt quite work as expected.  Any ideas why

my code:

import React from 'react';
import { Button,StyleSheet,View,Text, Image,SafeAreaView, TextInput, KeyboardAvoidingView, TouchableOpacity} from 'react-native';
import {auth} from "../firebase"
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword} from "firebase/auth";
import { FirebaseError } from 'firebase/app';

export const Login = () => {
    const [email, setEmail] = React.useState("")
   const [password, setPassword] = React.useState("")
  const handleSignUp = (e) => {
    createUserWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      // Signed in
      const user = userCredential.user;
      // ...
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
      // ..
    });
  }
  const handleLogin  =  () => {
    auth
    .signInWithEmailAndPassword(email, password)
    .then(userCredentials => {
      const user = userCredentials.user;
      console.log('Logged in with:', user.email);
    })
    .catch(error => alert(error.message))
  }

  return (
    <KeyboardAvoidingView
    style={styles.container}
    behavior="padding"
  >
    <Text style={styles.heading}>Unlock the power of time managment</Text>
    <View style={styles.inputContainer}>
      <TextInput
      value={email}
        placeholder="Email"
        style={styles.input}
        onChangeText={text => setEmail(text)}
      />
      <TextInput
        placeholder="Password"
        style={styles.input}
        onChangeText={text => setPassword(text)}
        value={password}
        secureTextEntry
      />
    </View>

    <View style={styles.buttonContainer}>
      <TouchableOpacity
        style={styles.button}
        onPress={handleLogin}
      >
        <Text style={styles.buttonText}>Login</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={[styles.button, styles.buttonOutline]}
        onPress={handleSignUp}
      >
        <Text style={styles.buttonOutlineText} >Register</Text>
      </TouchableOpacity>
    </View>
  </KeyboardAvoidingView>
  )
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  inputContainer: {
    width: '80%'
  },
  input: {
    backgroundColor: 'white',
    paddingHorizontal: 15,
    paddingVertical: 10,
    borderRadius: 10,
    marginTop: 5,
  },
  heading: {
    fontSize: 30,
    fontWeight: "700"
  },
  buttonContainer: {
    width: '60%',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 40,
  },
  button: {
    backgroundColor: '#0782F9',
    width: '100%',
    padding: 15,
    borderRadius: 10,
    alignItems: 'center',
  },
  buttonOutline: {
    backgroundColor: 'white',
    marginTop: 5,
    borderColor: '#0782F9',
    borderWidth: 2,
  },
  buttonText: {
    color: 'white',
    fontWeight: '700',
    fontSize: 16,
  },
  buttonOutlineText: {
    color: '#0782F9',
    fontWeight: '700',
    fontSize: 16,
  },
});

expo go error:
firebase.auth.signinwithemailandpassword not a function
firebase.auth.signinwithemailandpassword returned undefined

Body:
You're using the new, modular SDK syntax, where most functionality is exposed as a top-level function, instead of as a method on an object. When you call createUserWithEmailAndPassword as a top-level function you pass in the auth object, and you need to do the same for signing in:

const handleLogin  =  () => {
  signInWithEmailAndPassword(auth, email, password)
  ...

I recommend keeping the Firebase documentation handy when troubleshooting problems like this, as the above is almost exactly the code shown in the Web version 9 (modular) tab in the section signing in a user with an email address and password


答:
```<code>const data = [
{
  "startDate": "2021-08-18T00:00:04.498059",
  "endDate": "2021-08-19T00:00:04.4962889"
},
{
  "startDate": "2021-08-18T00:00:04.498059",
  "endDate": "2021-08-19T00:00:04.4962889"
}
]
const newData = [];
data.forEach(element => {
  const startDate = new Date(element.startDate);
  const endDate = new Date(element.endDate);
  const difference = endDate.getTime() - startDate.getTime();
  if (difference > 604800000) {
    newData.push(element);
  }
}
);
console.log(newData);
</code>```

Title: Filtering elements of array on the basis of dates


问:
Python convert string holding nested json to dict
I have the following list (notice "keyE" has a dictionary as a string):

[
  {
    "keyA": "Example",
    "keyB": "{\"keyC\":2,\"keyD\":{\"keyE\":\"{\"name\":\"foo\"}\"},\"keyF\":0}"
  },
  {
    "keyA": "Example2",
    "keyB": "{\"keyC\":6,\"keyD\":{\"keyE\":\"{\"name\":\"bar\"}\"},\"keyF\":5}"
  }
]
```
<p>And I want to convert it to this (it can have any number of nested dictionaries and lists):</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "keyA": "Example",
    "keyB": {
      "keyC": 2,
      "keyD": {
        "keyE": {
          "name": "foo"
        }
      },
      "keyF": 0
    }
  },
  {
    "keyA": "Example2",
    "keyB": {
      "keyC": 6,
      "keyD": {
        "keyE": {
          "name": "bar"
        }
      },
      "keyF": 5
    }
  }
]
</code>```

So far, I have the following but I don't know what to do after the json.loads. I know I have to recursively call the function but not sure how.

import json

def convert(data_list: list) -> list:
  for i in range(len(data_list)):
    obj = data_list[i]

    for key, value in obj.items():
      if isinstance(value, str) and any(char in "{[]}" for char in value):
        try:
          data = json.loads(value)
          # What do I do here?
        except:
          continue
```

答:
Your nested key seems like a JSON string that can be loaded into a dictionary using json.loads method.
Though the nested JSON won't get converted to the dictionary that's why I've added the recursive function to address the nested dictionary present in the JSON.

```<code>import json
from json import JSONDecodeError

def recurse(d):
    try:
        if isinstance(d, dict):
            loaded_d = d
        else:
            loaded_d = json.loads(d)
        for k, v in loaded_d.items():
            loaded_d[k] = recurse(v)
    except (JSONDecodeError, TypeError):
        return d
    return loaded_d

for d in data_list:
    for key, val in d.items():
        d[key] = recurse(val)
</code>```

Output:

```<code>[
    {
        "keyA": "Example",
        "keyB": {"keyC": 2, "keyD": {"keyE": {"name": "foo"}}, "keyF": 0},
    },
    {
        "keyA": "Example2",
        "keyB": {"keyC": 6, "keyD": {"keyE": {"name": "bar"}}, "keyF": 5},
    },
]
</code>```

Body:
I have the following list (notice "keyE" has a dictionary as a string):

[
  {
    "keyA": "Example",
    "keyB": "{\"keyC\":2,\"keyD\":{\"keyE\":\"{\"name\":\"foo\"}\"},\"keyF\":0}"
  },
  {
    "keyA": "Example2",
    "keyB": "{\"keyC\":6,\"keyD\":{\"keyE\":\"{\"name\":\"bar\"}\"},\"keyF\":5}"
  }
]

And I want to convert it to this (it can have any number of nested dictionaries and lists):

[
  {
    "keyA": "Example",
    "keyB": {
      "keyC": 2,
      "keyD": {
        "keyE": {
          "name": "foo"
        }
      },
      "keyF": 0
    }
  },
  {
    "keyA": "Example2",
    "keyB": {
      "keyC": 6,
      "keyD": {
        "keyE": {
          "name": "bar"
        }
      },
      "keyF": 5
    }
  }
]

So far, I have the following but I don't know what to do after the json.loads. I know I have to recursively call the function but not sure how.

import json

def convert(data_list: list) -> list:
  for i in range(len(data_list)):
    obj = data_list[i]

    for key, value in obj.items():
      if isinstance(value, str) and any(char in "{[]}" for char in value):
        try:
          data = json.loads(value)
          # What do I do here?
        except:
          continue

Body:
Your nested key seems like a JSON string that can be loaded into a dictionary using json.loads method.
Though the nested JSON won't get converted to the dictionary that's why I've added the recursive function to address the nested dictionary present in the JSON.

import json
from json import JSONDecodeError

def recurse(d):
    try:
        if isinstance(d, dict):
            loaded_d = d
        else:
            loaded_d = json.loads(d)
        for k, v in loaded_d.items():
            loaded_d[k] = recurse(v)
    except (JSONDecodeError, TypeError):
        return d
    return loaded_d

for d in data_list:
    for key, val in d.items():
        d[key] = recurse(val)

Output:

[
    {
        "keyA": "Example",
        "keyB": {"keyC": 2, "keyD": {"keyE": {"name": "foo"}}, "keyF": 0},
    },
    {
        "keyA": "Example2",
        "keyB": {"keyC": 6, "keyD": {"keyE": {"name": "bar"}}, "keyF": 5},
    },
]


问:
Why if i created a mock i am still getting error?
i am doing testing, i made a test in that test i create a mock for a fake function

```<code>jest.mock('@/services/myService', ()=>({getAvailables: jest.fn().mockReturnValue()}))
</code>```

that function is running in my component

```<code> onMounted(async () => {
        const answer = await getAvailables1()
        const answer = await getAvailables2()
        const answer = await getAvailables3()
</code>```

but still i am getting this error

(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables1) is not a function
(node:81921) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag

if i put like this first getAvailables2

```<code> onMounted(async () => {
            const answer = await getAvailables2()
            const answer = await getAvailables1()
</code>```

i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables2) is not a function

if i put like this first getAvailables3

```<code> onMounted(async () => {
            const answer = await getAvailables3()
            const answer = await getAvailables2()
</code>```

i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables3) is not a function

also i try with mockResolvedValue, does not worked

```<code>export const getAvailables = async () => {
  let response
  let error
  try {
    response = await getData()
  } catch (err) {
    error = err
    throw err
  }
  return { response, error }
}
</code>```

答:
getAvailables() is async function that always returns a promise.

So, in order to mock that function you need to return the mock promise with success or rejected value.

Following is the example of mocking that function which returns success promise.

```<code>jest.mock('@/services/myService', () => ({
   getAvailables: jest.fn().mockResolvedValue(true)
}))
</code>```

Body:
i am doing testing, i made a test in that test i create a mock for a fake function

jest.mock('@/services/myService', ()=>({getAvailables: jest.fn().mockReturnValue()}))

that function is running in my component

 onMounted(async () => {
        const answer = await getAvailables1()
        const answer = await getAvailables2()
        const answer = await getAvailables3()

but still i am getting this error

(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables1) is not a function
(node:81921) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag

if i put like this first getAvailables2

 onMounted(async () => {
            const answer = await getAvailables2()
            const answer = await getAvailables1()

i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables2) is not a function

if i put like this first getAvailables3

 onMounted(async () => {
            const answer = await getAvailables3()
            const answer = await getAvailables2()

i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables3) is not a function

also i try with mockResolvedValue, does not worked

export const getAvailables = async () => {
  let response
  let error
  try {
    response = await getData()
  } catch (err) {
    error = err
    throw err
  }
  return { response, error }
}

Body:
getAvailables() is async function that always returns a promise.

So, in order to mock that function you need to return the mock promise with success or rejected value.

Following is the example of mocking that function which returns success promise.

jest.mock('@/services/myService', () => ({
   getAvailables: jest.fn().mockResolvedValue(true)
}))


问:
S3 Objects created using UNLOAD command from the Redshift cluster are not accessible to the bucket owner user of the AWS account
I have one AWS S# and Redshift question:

A company uses two AWS accounts for accessing various AWS services. The analytics team has just configured an Amazon S3 bucket in AWS account A for writing data from the Amazon Redshift cluster provisioned in AWS account B. The team has noticed that the files created in the S3 bucket using UNLOAD command from the Redshift cluster are not accessible to the bucket owner user of the AWS account A that created the S3 bucket.

What could be the reason for this denial of permission for resources belonging to the same AWS account?

I tried to reproduce the scenario for the question, but I can't.

I don't get the S3 Object Ownership and Bucket Ownership.

答:
You are not the only person confused by Amazon S3 object ownership. When writing files from one AWS Account to a bucket owned by a different AWS Account, is possible for the 'ownership' of objects to remain with the 'sending' account. This causes all types of problems.

Fortunately, AWS has introduced a new feature into S3 called Edit Object Ownership that overrides all these issues:

By setting "ACLs disabled" for an S3 Bucket, objects will always be owned by the AWS Account that owns the bucket.

So, you should configure this option for the S3 bucket in your AWS account B and it should all work nicely.


问:
int issue in g++/mysql/redhat
I haven't written C in quite some time and am writing an app using the MySQL C API, compiling in g++ on redhat.

So i start outputting some fields with printfs... using the oracle api, with PRO*C, which i used to use (on suse, years ago), i could select an int and output it as:

```
int some_int;
printf("%i",some_int);
```

I tried to do that with mysql ints and i got 8 random numbers displayed... i thought this was  a mysql api issue and some config issue with my server, and i wasted a few hours trying to fix it, but couldn't, and found that i could do:

```
int some_int;
printf("%s",some_int);
```

and it would print out the integer properly. Because i'm not doing computations on the values i am extracting, i thought this an okay solution.

UNTIL I TRIED TO COUNT SOME THINGS....

I did a simple:

```
int rowcount;
for([stmt]){
rowcount++;
}
printf("%i",rowcount);
```

i am getting an 8 digit random number again... i couldn't figure out what the deal is with ints on this machine.

then i realized that if i initialize the int to zero, then i get a proper number.

can someone please explain to me under what conditions you need to initialize int variables to zero? i don't recall doing this every time in my old codebase, and i didn't see it in the example that i was modeling my mysql_stmt code from...

is there something i'm missing? also, it's entirely possible i've forgotten this is required each time

thanks...

答:
Uninitialized variable.</p>

```<code>int some_int = 0;
</code>```

OwnerDisplayName: hcmk

LastEditorDisplayName: FreeMemory

ContentLicense: CC BY-SA 2.5

Title: int issue in g++/mysql/redhat

Body:
I haven't written C in quite some time and am writing an app using the MySQL C API, compiling in g++ on redhat.

So i start outputting some fields with printfs... using the oracle api, with PRO*C, which i used to use (on suse, years ago), i could select an int and output it as:

int some_int;
printf("%i",some_int);

I tried to do that with mysql ints and i got 8 random numbers displayed... i thought this was  a mysql api issue and some config issue with my server, and i wasted a few hours trying to fix it, but couldn't, and found that i could do:

int some_int;
printf("%s",some_int);

and it would print out the integer properly. Because i'm not doing computations on the values i am extracting, i thought this an okay solution.

UNTIL I TRIED TO COUNT SOME THINGS....

I did a simple:

int rowcount;
for([stmt]){
rowcount++;
}
printf("%i",rowcount);

i am getting an 8 digit random number again... i couldn't figure out what the deal is with ints on this machine.

then i realized that if i initialize the int to zero, then i get a proper number.

can someone please explain to me under what conditions you need to initialize int variables to zero? i don't recall doing this every time in my old codebase, and i didn't see it in the example that i was modeling my mysql_stmt code from...

is there something i'm missing? also, it's entirely possible i've forgotten this is required each time

thanks...

Body:
Uninitialized variable.

int some_int = 0;

OwnerDisplayName: Sanjaya R


问:
Python - os.remove() - str object has no attribute 'remove'
I've written a script that takes a .csv file, converts it to an .xlsx using openpyxl, and formats the file.

Throughout the script's process, it creates several .csv files, which can be deleted.  I've tried using os.remove("File.csv"), but always get the error:

```<code>      os.remove("File.csv")
AttributeError: 'str' object has no attribute 'remove'
</code>```

I've tried running this on 3 different computers, and I've even written a test script with just 2 lines of code to test the functionality and have had no luck (same error):

```<code>import os
os.remove("File.csv")
</code>```

Does anybody know the cause/reason for this?

OR

Is there another way to delete (move to trash) a file/multiple files?

答:
Try finding the file using os.path.exists
Example:

```<code>import os
if os.path.exists("File.csv"):
   os.remove("File.csv")
else:
   print("That file does not exist!")
</code>```

Body:
I've written a script that takes a .csv file, converts it to an .xlsx using openpyxl, and formats the file.

Throughout the script's process, it creates several .csv files, which can be deleted.  I've tried using os.remove("File.csv"), but always get the error:

      os.remove("File.csv")
AttributeError: 'str' object has no attribute 'remove'

I've tried running this on 3 different computers, and I've even written a test script with just 2 lines of code to test the functionality and have had no luck (same error):

import os
os.remove("File.csv")

Does anybody know the cause/reason for this?

OR

Is there another way to delete (move to trash) a file/multiple files?

Body:
Try finding the file using os.path.exists
Example:

import os
if os.path.exists("File.csv"):
   os.remove("File.csv")
else:
   print("That file does not exist!")


问:
Count occurrences of list of values in column using PySpark DataFrame
I have a PySpark DataFrame with a string column text and a separate list word_list and I need to count how many of the word_list values appear in each text row (can be counted more than once).

```<code>df = spark.createDataFrame(
  [(1,'Hello my name is John'),
   (2,'Yo go Bengals'),
   (3,'this is a text')
  ]
  , ['id','text']
)

word_list = ['is', 'm', 'o', 'my']
</code>```

The result would be:

| text                  | list_count   |
| Hello my name is John |       6      |
| Yo go Bengals         |       2      |
| this is a text        |       2      |
```

For text's first value, "is" occurs once, "m" occurs twice, "o" occurs twice, and "my" occurs once. In the second row, the only value from word_list that appears is "o" and it appears twice. In the third value for text, the only value from word_list that appears is "is" and it appears twice.

The result doesn't necessarily have to be PySpark-based either, it could be in Pandas if that's easier.

答:
You can do this with a UDF as below

UDF

```<code>df = sql.createDataFrame(
  [(1,'Hello my name is John'),
   (2,'Yo go Bengals'),
   (3,'this is a text')
  ]
  , ['id','text']
)

word_list = ['is', 'm', 'o', 'my']

def count_values(inp,map_list=None):

    count = 0

    for pattern in map_list:
        if re.findall(pattern,inp):
            count += 1

    return count

count_values_udf = F.udf(partial(count_values,map_list=word_list),IntegerType())

df.select(
            count_values_udf(F.col('text')).alias('count_values')
         ).show()

+------------+
|count_values|
+------------+
|           4|
|           1|
|           1|
+------------+
</code>```

Body:
I have a PySpark DataFrame with a string column text and a separate list word_list and I need to count how many of the word_list values appear in each text row (can be counted more than once).

df = spark.createDataFrame(
  [(1,'Hello my name is John'),
   (2,'Yo go Bengals'),
   (3,'this is a text')
  ]
  , ['id','text']
)

word_list = ['is', 'm', 'o', 'my']

The result would be:

| text                  | list_count   |
| Hello my name is John |       6      |
| Yo go Bengals         |       2      |
| this is a text        |       2      |

For text's first value, "is" occurs once, "m" occurs twice, "o" occurs twice, and "my" occurs once. In the second row, the only value from word_list that appears is "o" and it appears twice. In the third value for text, the only value from word_list that appears is "is" and it appears twice.

The result doesn't necessarily have to be PySpark-based either, it could be in Pandas if that's easier.

Body:
You can do this with a UDF as below

UDF

df = sql.createDataFrame(
  [(1,'Hello my name is John'),
   (2,'Yo go Bengals'),
   (3,'this is a text')
  ]
  , ['id','text']
)

word_list = ['is', 'm', 'o', 'my']

def count_values(inp,map_list=None):

    count = 0

    for pattern in map_list:
        if re.findall(pattern,inp):
            count += 1

    return count

count_values_udf = F.udf(partial(count_values,map_list=word_list),IntegerType())

df.select(
            count_values_udf(F.col('text')).alias('count_values')
         ).show()

+------------+
|count_values|
+------------+
|           4|
|           1|
|           1|
+------------+


问:
How to exclude holidays like saturday, sunday from date using Javascript?
I've found this code online to return the next working day and exclude weekends.

```<code>function nextWorkDay() {
    const date = new Date();
  do {
    date.setDate(date.getDate() + 1);
  } while (!(date.getDay() % 6));
  return date;
}
</code>```

However, the % 6 part in my understanding excludes Saturdays and Sundays.
How can I modify it to only exclude Saturdays?

答:
getDay returns a value between 0 and 6, inclusive. 0 is Sunday.

So, date.getDay() % 6 will result in 0 if getDay returns either 0 or 6.

Don't use modulo - use === to exclude exactly one day, not both zero and another day.

```<code>} while (date.getDay() === 6);
</code>```

You also don't need a loop anymore - a single condition will be clearer.

```<code>function nextWorkDay() {
    const date = new Date();
    date.setDate(date.getDate() + 1);
    if (date.getDay() === 6) date.setDate(date.getDate() + 1);
    return date;
}
</code>```

Body:
I've found this code online to return the next working day and exclude weekends.

function nextWorkDay() {
    const date = new Date();
  do {
    date.setDate(date.getDate() + 1);
  } while (!(date.getDay() % 6));
  return date;
}

However, the % 6 part in my understanding excludes Saturdays and Sundays.
How can I modify it to only exclude Saturdays?

Body:
getDay returns a value between 0 and 6, inclusive. 0 is Sunday.

So, date.getDay() % 6 will result in 0 if getDay returns either 0 or 6.

Don't use modulo - use === to exclude exactly one day, not both zero and another day.

} while (date.getDay() === 6);

You also don't need a loop anymore - a single condition will be clearer.

function nextWorkDay() {
    const date = new Date();
    date.setDate(date.getDate() + 1);
    if (date.getDay() === 6) date.setDate(date.getDate() + 1);
    return date;
}


问:
Locally, Auth works. on Deployment, logs in, but the Auth gets returned False
Locally this

```<code>module.exports.isAuth = (req, res, next) => {
  if (req.isAuthenticated()) {
    next();
    // res.status(200).json({ user: req.user, auth: true });
  } else {
    return res.status(401).json({ auth: false, msg: "Here" });
  }
};
</code>```

Works perfectly, I get logged in.

But when I try to do it with the backend on Heroku and not locally, I get the "Else" returned to the front end.

The problem is I know where the issue is, most likely, I just feel like I'm in an empty room looking for it.

I get the Json object returned on the front end, even though my passport middleware logs "logged in" on the server. heres the passport middleware

```<code>const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const connection = require("./database");
const mongoose = require("mongoose");
const User = mongoose.models.User;
const validPassword = require("../lib/passwordUtils").validPassword;
const cors = require("cors");
passport.use(
  cors({
    origin: [
      "http://2607:fb90:b6e0:a363:f89f:be4b:a976:9ed0:3001",
      "https://frontendfullstack.netlify.app",
      "http://localhost:3001",
      "localhost:3001",
    ],
    credentials: true,
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
  })
);

const customFields = {
  usernameField: "username",
  passwordField: "password",
};

passport.use(
  new LocalStrategy(customFields, (username, password, done) => {
    User.findOne({ username: username })
      .then((user) => {
        if (!user) {
          console.log("No user");
          return done(null, false);
        } else {
          const isValid = validPassword(password, user.hash, user.salt);
          if (isValid) {
            console.log("Logged in");

            return done(null, user);
          } else {
            console.log("Wrong Password");
            return done(null, true);
          }
        }
      })
      .catch((err) => {
        done(err);
      });
  })
);

passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  User.findById(id, (err, user) => {
    done(err, user);
  }).catch((err) => done(err));
});
</code>```

And just to reiterate, when the server is local, it works, I get logged in and redirected, the site works perfectly.

答:
The problem is that the Passport Local Strategy uses cookies for authentication, and Heroku only allows cookies to be set for its own domain.

As your frontend is hosted in Netlify, if you check the developer tools you will notice no cookie being set. So, the next request you make after logging in, fails.

Not much you can do except hosting the backend together with the frontend in Heroku, that way your app will work.

I answered a similar question a few days ago and left some tips at the end:

Not able to set/receive cookies cross-domain using Netlify and Heroku

EDIT:

Ok, let's see if we can make this work. I haven't worked with React, but the process for building the production app is somewhat similar to Angular from what I read.

First of all, you will want to revert to a prior commit where your app was working. Then create a new branch (i.e. backup) just to be sure if anything goes wrong, you can revert to it. Now, checkout to your main again. This is because Heroku will ignore commits pushed from branches that are not the main one.

Execute npm run build on your React app project folder and you will obtain the compiled files in a build folder. In there you will find the index.html file, and inside the build/static folder you'll find all the .js and .css files with hashed names that contain your app code.

Depending on what location this build folder was generated, you may need to manually copy it so it ends up as a folder inside your Express project folder tree.

Make sure the new folder isn't ignored (check the .gitignore file) so that it will be included in the next commit you'll make.

In the file that sets up your Express server (app.js, server.js or whatever you named it), in the part where the routes are setted, you need to add this line:

app.use(express.static(path.join(__dirname, 'build')));
```

This line will ensure that when you try to access the / path, Express will send the index.html file to the client. So, it will be just like is hosted in Netlify for example.

Now, you can git add . -> git commit -m 'Deploy test message' -> git push heroku main.

If everything went well, you can now visit the URL that Heroku assigned to your app and you'll see your frontend served in there.

Depending on your folders or environment variables you may run into some other problems, but this should work.

Let me know.

Body:
Locally this

module.exports.isAuth = (req, res, next) => {
  if (req.isAuthenticated()) {
    next();
    // res.status(200).json({ user: req.user, auth: true });
  } else {
    return res.status(401).json({ auth: false, msg: "Here" });
  }
};

Works perfectly, I get logged in.

But when I try to do it with the backend on Heroku and not locally, I get the "Else" returned to the front end.

The problem is I know where the issue is, most likely, I just feel like I'm in an empty room looking for it.

I get the Json object returned on the front end, even though my passport middleware logs "logged in" on the server. heres the passport middleware

const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const connection = require("./database");
const mongoose = require("mongoose");
const User = mongoose.models.User;
const validPassword = require("../lib/passwordUtils").validPassword;
const cors = require("cors");
passport.use(
  cors({
    origin: [
      "http://2607:fb90:b6e0:a363:f89f:be4b:a976:9ed0:3001",
      "https://frontendfullstack.netlify.app",
      "http://localhost:3001",
      "localhost:3001",
    ],
    credentials: true,
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
  })
);

const customFields = {
  usernameField: "username",
  passwordField: "password",
};

passport.use(
  new LocalStrategy(customFields, (username, password, done) => {
    User.findOne({ username: username })
      .then((user) => {
        if (!user) {
          console.log("No user");
          return done(null, false);
        } else {
          const isValid = validPassword(password, user.hash, user.salt);
          if (isValid) {
            console.log("Logged in");

            return done(null, user);
          } else {
            console.log("Wrong Password");
            return done(null, true);
          }
        }
      })
      .catch((err) => {
        done(err);
      });
  })
);

passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  User.findById(id, (err, user) => {
    done(err, user);
  }).catch((err) => done(err));
});

And just to reiterate, when the server is local, it works, I get logged in and redirected, the site works perfectly.

Body:
The problem is that the Passport Local Strategy uses cookies for authentication, and Heroku only allows cookies to be set for its own domain.

As your frontend is hosted in Netlify, if you check the developer tools you will notice no cookie being set. So, the next request you make after logging in, fails.

Not much you can do except hosting the backend together with the frontend in Heroku, that way your app will work.

I answered a similar question a few days ago and left some tips at the end:

Not able to set/receive cookies cross-domain using Netlify and Heroku

EDIT:

Ok, let's see if we can make this work. I haven't worked with React, but the process for building the production app is somewhat similar to Angular from what I read.

First of all, you will want to revert to a prior commit where your app was working. Then create a new branch (i.e. backup) just to be sure if anything goes wrong, you can revert to it. Now, checkout to your main again. This is because Heroku will ignore commits pushed from branches that are not the main one.

Execute npm run build on your React app project folder and you will obtain the compiled files in a build folder. In there you will find the index.html file, and inside the build/static folder you'll find all the .js and .css files with hashed names that contain your app code.

Depending on what location this build folder was generated, you may need to manually copy it so it ends up as a folder inside your Express project folder tree.

Make sure the new folder isn't ignored (check the .gitignore file) so that it will be included in the next commit you'll make.

In the file that sets up your Express server (app.js, server.js or whatever you named it), in the part where the routes are setted, you need to add this line:

app.use(express.static(path.join(__dirname, 'build')));

This line will ensure that when you try to access the / path, Express will send the index.html file to the client. So, it will be just like is hosted in Netlify for example.

Now, you can git add . -> git commit -m 'Deploy test message' -> git push heroku main.

If everything went well, you can now visit the URL that Heroku assigned to your app and you'll see your frontend served in there.

Depending on your folders or environment variables you may run into some other problems, but this should work.

Let me know.


问:
Why do the `man bash` pages state the `declare` and `local` `-n` attribute "cannot be applied to array variables", and yet it can?
Why does local -n work on array variables when the manual explicitly says it does not? Is the manual wrong? Is this relying on some sort of bash "undefined behavior?" Is the manual out-of-date? Am I missing something?

Here is the information I'm looking at from the bash manual:

Run man bash and search for local [ using the regular expression search pattern local \[. It says (emphasis added):

local [option] [name[=value] ... | - ]

For each argument, a local variable named name is created, and assigned  value.  The
option  can  be  any of the options accepted by declare.

(See also help local).

So, the options that can be passed to the bash local built-in command are the same as those of declare. Let's find what options can be passed to declare:

Run man bash and search for declare [ using the regular expression search pattern declare \[. Under the -n entry there for declare [-aAfFgilnrtux] [-p] [name[=value] ...] you'll see (emphasis added):

-n     Give each name the nameref attribute, making it a name  reference  to  another
variable.   That  other  variable is defined by the value of name.  All references, assignments, and attribute modifications to name, except those using or
changing  the -n attribute itself, are performed on the variable referenced by
name's value.  The nameref attribute cannot be applied to array variables.

(See also help declare).

So, despite it saying "The nameref attribute cannot be applied to array variables,", it does work just fine on array variables!

To prove that, here is a demo of it working fine for regular bash arrays:

function foo {
    # declare a local **reference variable** (hence `-n`) named `data_ref`
    # which is a reference to the value stored in the first parameter
    # passed in
    local -n data_ref="$1"
    echo "${data_ref[0]}"
    echo "${data_ref[1]}"
}

# declare a regular bash "indexed" array
declare -a data
data+=("Fred Flintstone")
data+=("Barney Rubble")
foo "data"
```
<p>Sample output:</p>
<blockquote>
```Fred Flintstone
Barney Rubble
```
</blockquote>
<p>...and here is it working just fine on <strong>associative bash arrays</strong> (ie: bash hash tables, "dictionaries", or "unordered maps"):</p>
<pre class="lang-sh prettyprint-override"><code>function foo {
    # declare a local **reference variable** (hence `-n`) named `data_ref`
    # which is a reference to the value stored in the first parameter
    # passed in
    local -n data_ref="$1"
    echo "${data_ref["a"]}"
    echo "${data_ref["b"]}"
}

# declare a bash associative array
declare -A data
data["a"]="Fred Flintstone"
data["b"]="Barney Rubble"
foo "data"
</code>```

Sample output:

```<code>Fred Flintstone
Barney Rubble
</code>```

My bash --version is 4.4.20(1)-release, on Linux Ubuntu 18.04:

```<code>GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
</code>```

References:

I modified the above code samples from @Todd Lehman's answer here: How to pass an associative array as argument to a function in Bash?

Note: in case anyone is searching for it, this question itself also answers the questions: "How do I pass a bash array as a parameter to a function?" and "How do I pass a bash associative array as a parameter to a function?"

答:
You are applying -n to a scalar variable, and then have that nameref point to an array. This is fine.

What you can't do is apply -n to an array variable to create an array of namerefs:

```<code># Declare two variables
declare foo=42 bar=1337

# Make an array of namerefs
declare -n array=(foo bar)    # ERROR

# ${array[0]} is foo so this should print $foo, i.e. 42?
echo "${array[0]}"
</code>```

If you try, Bash stops you:

```<code>bash: declare: array: reference variable cannot be an array
</code>```

Body:
Why does local -n work on array variables when the manual explicitly says it does not? Is the manual wrong? Is this relying on some sort of bash "undefined behavior?" Is the manual out-of-date? Am I missing something?

Here is the information I'm looking at from the bash manual:

Run man bash and search for local [ using the regular expression search pattern local \[. It says (emphasis added):

local [option] [name[=value] ... | - ]

For each argument, a local variable named name is created, and assigned  value.  The
option  can  be  any of the options accepted by declare.

(See also help local).

So, the options that can be passed to the bash local built-in command are the same as those of declare. Let's find what options can be passed to declare:

Run man bash and search for declare [ using the regular expression search pattern declare \[. Under the -n entry there for declare [-aAfFgilnrtux] [-p] [name[=value] ...] you'll see (emphasis added):

-n     Give each name the nameref attribute, making it a name  reference  to  another
variable.   That  other  variable is defined by the value of name.  All references, assignments, and attribute modifications to name, except those using or
changing  the -n attribute itself, are performed on the variable referenced by
name's value.  The nameref attribute cannot be applied to array variables.

(See also help declare).

So, despite it saying "The nameref attribute cannot be applied to array variables,", it does work just fine on array variables!

To prove that, here is a demo of it working fine for regular bash arrays:

function foo {
    # declare a local **reference variable** (hence `-n`) named `data_ref`
    # which is a reference to the value stored in the first parameter
    # passed in
    local -n data_ref="$1"
    echo "${data_ref[0]}"
    echo "${data_ref[1]}"
}

# declare a regular bash "indexed" array
declare -a data
data+=("Fred Flintstone")
data+=("Barney Rubble")
foo "data"

Sample output:

Fred Flintstone
Barney Rubble

...and here is it working just fine on associative bash arrays (ie: bash hash tables, "dictionaries", or "unordered maps"):

function foo {
    # declare a local **reference variable** (hence `-n`) named `data_ref`
    # which is a reference to the value stored in the first parameter
    # passed in
    local -n data_ref="$1"
    echo "${data_ref["a"]}"
    echo "${data_ref["b"]}"
}

# declare a bash associative array
declare -A data
data["a"]="Fred Flintstone"
data["b"]="Barney Rubble"
foo "data"

Sample output:

Fred Flintstone
Barney Rubble

My bash --version is 4.4.20(1)-release, on Linux Ubuntu 18.04:

GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

References:

I modified the above code samples from @Todd Lehman's answer here: How to pass an associative array as argument to a function in Bash?

Note: in case anyone is searching for it, this question itself also answers the questions: "How do I pass a bash array as a parameter to a function?" and "How do I pass a bash associative array as a parameter to a function?"

Body:
You are applying -n to a scalar variable, and then have that nameref point to an array. This is fine.

What you can't do is apply -n to an array variable to create an array of namerefs:

# Declare two variables
declare foo=42 bar=1337

# Make an array of namerefs
declare -n array=(foo bar)    # ERROR

# ${array[0]} is foo so this should print $foo, i.e. 42?
echo "${array[0]}"

If you try, Bash stops you:

bash: declare: array: reference variable cannot be an array


问:
Jenkins on Kubernetes service yaml parsing error
I'm following this Link to setup Jenkins on Kubernetes cluster. When I tried to apply jenkins-svc.yaml it fails with an error.

jenkins-svc.yaml file content as follows,

apiVersion: v1
kind: Service
metadata:
  name: jenkins-ui-service
  namespace: jenkins
spec:
    type: ClusterIP # NodePort, LoadBalancer
  ports:
    - protocol: TCP
      port: 8080
      targetPort: 8080
      # nodePort: 30100
      name: ui
  selector:
    app: jenkins
---
apiVersion: v1
kind: Service
metadata:
  name: jenkins-jnlp-service
  namespace: jenkins
spec:
    type: ClusterIP # NodePort, LoadBalancer
  ports:
    - port: 50000
      targetPort: 50000
  selector:
    app: jenkins
```
<p>The error I get when I tried to apply <code>jenkins-svc.yaml</code>.</p>
```# kubectl  apply -f jenkins-svc.yaml -n jenkins
error: error parsing jenkins-svc.yaml: error converting YAML to JSON: yaml: line 7: did not find expected key
```

Please let me know how do I solve this issue?

答: please check indentation of line 7 & 23. remove 2 extra spaces before "type" in spec section for both svc.</p>

Body:
I'm following this Link to setup Jenkins on Kubernetes cluster. When I tried to apply jenkins-svc.yaml it fails with an error.

jenkins-svc.yaml file content as follows,

apiVersion: v1
kind: Service
metadata:
  name: jenkins-ui-service
  namespace: jenkins
spec:
    type: ClusterIP # NodePort, LoadBalancer
  ports:
    - protocol: TCP
      port: 8080
      targetPort: 8080
      # nodePort: 30100
      name: ui
  selector:
    app: jenkins
---
apiVersion: v1
kind: Service
metadata:
  name: jenkins-jnlp-service
  namespace: jenkins
spec:
    type: ClusterIP # NodePort, LoadBalancer
  ports:
    - port: 50000
      targetPort: 50000
  selector:
    app: jenkins

The error I get when I tried to apply jenkins-svc.yaml.

# kubectl  apply -f jenkins-svc.yaml -n jenkins
error: error parsing jenkins-svc.yaml: error converting YAML to JSON: yaml: line 7: did not find expected key

Please let me know how do I solve this issue?


问:
The content copied from a richtextbox is not getting saved in my database
Am trying to copy the content of a Richtextbox to another Richtextbox using the below code.

```<code>FlowDocument doc = RTB1.Document;
RTB1.Document = new FlowDocument();
RTB2.Document = doc;
</code>```

But the copied line disappears if i try to save the screen where the RichTextBox(RTB2) is there.

Any help on this will be greatful.

答:
In your code RTB1.Document = new FlowDocument(); will asign a new FlowDocument value to the RTB1.that's why the copied line disappears.

Try this

 first you need to include the namespace and add the code below

```<code>        using System.IO;
        using System.Windows.Markup;

       MemoryStream ms = new MemoryStream();

       XamlWriter.Save(RTB1.Document, ms);

       ms.Seek(0, SeekOrigin.Begin);

       RTB2.Document = XamlReader.Load(ms) as FlowDocument;
</code>```

Body:
Am trying to copy the content of a Richtextbox to another Richtextbox using the below code.

FlowDocument doc = RTB1.Document;
RTB1.Document = new FlowDocument();
RTB2.Document = doc;

But the copied line disappears if i try to save the screen where the RichTextBox(RTB2) is there.

Any help on this will be greatful.

Body:
In your code RTB1.Document = new FlowDocument(); will asign a new FlowDocument value to the RTB1.that's why the copied line disappears.

Try this

 first you need to include the namespace and add the code below

        using System.IO;
        using System.Windows.Markup;

       MemoryStream ms = new MemoryStream();

       XamlWriter.Save(RTB1.Document, ms);

       ms.Seek(0, SeekOrigin.Begin);

       RTB2.Document = XamlReader.Load(ms) as FlowDocument;