问:
Tensorflow evaluate network with different batch size
I have a trained network with input:

```<code>input = tf.placeholder(dtype=tf.float32, shape=(None, width, height, channels), name='input')
</code>```

In practice, I want to be able to make predictions with variable batch_size (with maximum batch size batch_max, say 100), i.e.,

```<code>imgs = get_batch(batch_size=1)
session.run([output], feed_dict={'input:0': imgs})
imgs = get_batch(batch_size=100)
session.run([output], feed_dict={'input:0': imgs})
</code>```

Now I observed the following behaviour:

```<code>imgs_batch1 = get_batch(batch_size=1)
imgs_batch100 = get_batch(batch_size=100)
session.run([output], feed_dict={'input:0': imgs_batch1})
session.run([output], feed_dict={'input:0': imgs_batch100}) # takes 1.5s
session.run([output], feed_dict={'input:0': imgs_batch100}) # takes 1.0s
session.run([output], feed_dict={'input:0': imgs_batch1})
session.run([output], feed_dict={'input:0': imgs_batch100}) # takes 1.5s
session.run([output], feed_dict={'input:0': imgs_batch100}) # takes 1.0s
</code>```

Otherwise said, changing the batch size slows down the evaluation. The first evaluation of a batch size is significantly slower than direct following evaluations of same batch size.

That sounds reasonable I can find logical reasons why that would be the case. But given that I know the maximum batch size that will ever be sent as input, is there not a smarter way to achieve this without the slowing down as soon as there is a batch of size 1 being sent?

Thanks

答: You can try to pad your batches, i.e creating an example full of 0 and put it multiple time inside your batch if your batch is less than your max_size. When you have the results just discard those coming from the dummy example.</p>

Body:
I have a trained network with input:

input = tf.placeholder(dtype=tf.float32, shape=(None, width, height, channels), name='input')

In practice, I want to be able to make predictions with variable batch_size (with maximum batch size batch_max, say 100), i.e.,

imgs = get_batch(batch_size=1)
session.run([output], feed_dict={'input:0': imgs})
imgs = get_batch(batch_size=100)
session.run([output], feed_dict={'input:0': imgs})

Now I observed the following behaviour:

imgs_batch1 = get_batch(batch_size=1)
imgs_batch100 = get_batch(batch_size=100)
session.run([output], feed_dict={'input:0': imgs_batch1})
session.run([output], feed_dict={'input:0': imgs_batch100}) # takes 1.5s
session.run([output], feed_dict={'input:0': imgs_batch100}) # takes 1.0s
session.run([output], feed_dict={'input:0': imgs_batch1})
session.run([output], feed_dict={'input:0': imgs_batch100}) # takes 1.5s
session.run([output], feed_dict={'input:0': imgs_batch100}) # takes 1.0s

Otherwise said, changing the batch size slows down the evaluation. The first evaluation of a batch size is significantly slower than direct following evaluations of same batch size.

That sounds reasonable I can find logical reasons why that would be the case. But given that I know the maximum batch size that will ever be sent as input, is there not a smarter way to achieve this without the slowing down as soon as there is a batch of size 1 being sent?

Thanks


来源: stackexchange

问:
Alter Odoo XmlRPC context to use a specific language
I need to get the translated data from odoo with a specific language using XMLRPC
by default odoo sends data in the default language which is English

```<code>api.execute_kw(db, uid, pwd, 'res.country', 'search_read', [[]], {'fields': ['name']})
</code>```

how to add context to this request to use a specific translation language.

答:
Here I have listed some example syntax for xmlrpc(Odoo Web Service API) common ORM methods to add context as a param.

Create

```<code>api.execute_kw(db, uid, password, 'res.partner', 'create', [{'name: Atul'}], {'context' :{'tag': 1}})
</code>```

Search

```<code>api.execute_kw(db, uid, pwd, 'res.partner', 'search_read', [[('name', '=', "Atul")]], {'context' :{'tag': 1}})
</code>```

Search Read

```<code>api.execute_kw(db, uid, pwd, 'res.partner', 'search_read', [[('name', '=', "Atul")]], {'fields': ['id', 'name'], 'context' :{'tag': 1}})
</code>```

Read

```<code>api.execute_kw(db, uid, password, 'res.partner', 'read', [ids], {'context' :{'tag': 1}})
</code>```

Write

```<code>api.execute_kw(db, uid, password, 'res.partner', 'write', [[id], {'name': "Atul Arvind"}], {'context' :{'tag': 1}})
</code>```

Unlink

```<code>api.execute_kw(db, uid, password, 'res.partner', 'unlink', [[id]], {'context' :{'tag': 1})
</code>```

Hope this helps!

ContentLicense: CC BY-SA 3.0

Body:
I need to get the translated data from odoo with a specific language using XMLRPC
by default odoo sends data in the default language which is English

api.execute_kw(db, uid, pwd, 'res.country', 'search_read', [[]], {'fields': ['name']})

how to add context to this request to use a specific translation language.

Body:
Here I have listed some example syntax for xmlrpc(Odoo Web Service API) common ORM methods to add context as a param.

Create

api.execute_kw(db, uid, password, 'res.partner', 'create', [{'name: Atul'}], {'context' :{'tag': 1}})

Search

api.execute_kw(db, uid, pwd, 'res.partner', 'search_read', [[('name', '=', "Atul")]], {'context' :{'tag': 1}})

Search Read

api.execute_kw(db, uid, pwd, 'res.partner', 'search_read', [[('name', '=', "Atul")]], {'fields': ['id', 'name'], 'context' :{'tag': 1}})

Read

api.execute_kw(db, uid, password, 'res.partner', 'read', [ids], {'context' :{'tag': 1}})

Write

api.execute_kw(db, uid, password, 'res.partner', 'write', [[id], {'name': "Atul Arvind"}], {'context' :{'tag': 1}})

Unlink

api.execute_kw(db, uid, password, 'res.partner', 'unlink', [[id]], {'context' :{'tag': 1})

Hope this helps!


问:
VBA Range Issues - Set and Dynamic
Update: Just need to learn how to make fullrng dynamic

Big Picture:
I am trying to automatically create named ranges based on the data in a column.

The subprocedure I have posted takes an element of an array as an argument. All of this logic works fine.. I can create the named ranges for each element of the array.

I figured out the logic of how to get the values that I want in my range.

the for rownum = 2 to finalrow
next row

contains this logic.

The problem is that I am having trouble with the ranges.

If I dont use Set my ranges = Range(cells) then i get an object error.. this makes sense, the object has been declared but not set to anything.

I just dont know how to get these ranges initialized, and then change them to the group of cells that I want to

fullrng also needs to be dynamic is will be 2 cells tall, then 3 , then 4, etc.

```<code>Sub Createranges(ByVal TableName As String)

 If TableName <> "" Then

    Debug.Print TableName
    Dim fullrng As Range
    Dim temprng As Range
    Dim thiscell As Range
    Dim nextcell As Range

    Set fullrng = Range("H1")

    fullrng.Name = TableName

        For rownum = 2 To finalrow

            'Checking to see if cell should be in named range
            If Cells(rownum, ColumnVar).Value = TableName Then

                'Modify Ranges for union
                Set thiscell = Range(ColumnVar & Cells.Row, ColumnVar & Cells.Column)
                Set nextcell = Range(ColumnVar & Cells.Row + 1, ColumnVar & Cells.Column)

                'union the range to include all past matching values
                If thiscell.Value2 = nextcell.Value2(2, 1) Then
                    Set temprng = Range(thiscell, nextcell)
                    'Figure out dynamic ranges here
                    Set fullrng = Range(
                    fullrng = Union(fullrng, temprng)
                End If

            End If

        Next rownum
    End If

End Sub
</code>```

答:
Turns out there were alot of problems!

I guess thats what you get when you don't create your own objects, you have to explore and figure out the object model.

Besides some things being blatantly wrong --- using Cells.Column instead of my ColumnVar & rownum variables, here is what I changed:

I was originally Setting my range to a random cell so that I could name my range. fullrng.Name = TableName I just moved this line to right after I set the fullrng.

```<code>Sub Createranges(ByVal TableName As String)

If TableName <> "" Then

Debug.Print TableName
Dim fullrng As Range
Dim temprng As Range
Dim thiscell As Range
Dim nextcell As Range

    For rownum = 2 To finalrow

        'Checking to see if cell should be in named range
        If Cells(rownum, ColumnVar).Value = TableName Then

            'Modify Ranges for union
            Set thiscell = Range(ColumnVar & rownum, ColumnVar & rownum)
            Set nextcell = Range(ColumnVar & rownum + 1, ColumnVar & rownum + 1)

            'union the range to include all past matching values
            If thiscell.Text = nextcell.Text Then
                Set temprng = Application.Union(thiscell, nextcell)
                If Not fullrng Is Nothing Then
                    Set fullrng = Application.Union(fullrng, temprng)
                    fullrng.Name = TableName
                Else
                    Set fullrng = temprng
                End If

            End If

        End If

    Next rownum
End If

End Sub
</code>```

Title: VBA Range Issues - Set and Dynamic

Body:
Update: Just need to learn how to make fullrng dynamic

Big Picture:
I am trying to automatically create named ranges based on the data in a column.

The subprocedure I have posted takes an element of an array as an argument. All of this logic works fine.. I can create the named ranges for each element of the array.

I figured out the logic of how to get the values that I want in my range.

the for rownum = 2 to finalrow
next row

contains this logic.

The problem is that I am having trouble with the ranges.

If I dont use Set my ranges = Range(cells) then i get an object error.. this makes sense, the object has been declared but not set to anything.

I just dont know how to get these ranges initialized, and then change them to the group of cells that I want to

fullrng also needs to be dynamic is will be 2 cells tall, then 3 , then 4, etc.

Sub Createranges(ByVal TableName As String)

 If TableName <> "" Then

    Debug.Print TableName
    Dim fullrng As Range
    Dim temprng As Range
    Dim thiscell As Range
    Dim nextcell As Range

    Set fullrng = Range("H1")

    fullrng.Name = TableName

        For rownum = 2 To finalrow

            'Checking to see if cell should be in named range
            If Cells(rownum, ColumnVar).Value = TableName Then

                'Modify Ranges for union
                Set thiscell = Range(ColumnVar & Cells.Row, ColumnVar & Cells.Column)
                Set nextcell = Range(ColumnVar & Cells.Row + 1, ColumnVar & Cells.Column)

                'union the range to include all past matching values
                If thiscell.Value2 = nextcell.Value2(2, 1) Then
                    Set temprng = Range(thiscell, nextcell)
                    'Figure out dynamic ranges here
                    Set fullrng = Range(
                    fullrng = Union(fullrng, temprng)
                End If

            End If

        Next rownum
    End If

End Sub

Body:
Turns out there were alot of problems!

I guess thats what you get when you don't create your own objects, you have to explore and figure out the object model.

Besides some things being blatantly wrong --- using Cells.Column instead of my ColumnVar & rownum variables, here is what I changed:

I was originally Setting my range to a random cell so that I could name my range. fullrng.Name = TableName I just moved this line to right after I set the fullrng.

Sub Createranges(ByVal TableName As String)

If TableName <> "" Then

Debug.Print TableName
Dim fullrng As Range
Dim temprng As Range
Dim thiscell As Range
Dim nextcell As Range

    For rownum = 2 To finalrow

        'Checking to see if cell should be in named range
        If Cells(rownum, ColumnVar).Value = TableName Then

            'Modify Ranges for union
            Set thiscell = Range(ColumnVar & rownum, ColumnVar & rownum)
            Set nextcell = Range(ColumnVar & rownum + 1, ColumnVar & rownum + 1)

            'union the range to include all past matching values
            If thiscell.Text = nextcell.Text Then
                Set temprng = Application.Union(thiscell, nextcell)
                If Not fullrng Is Nothing Then
                    Set fullrng = Application.Union(fullrng, temprng)
                    fullrng.Name = TableName
                Else
                    Set fullrng = temprng
                End If

            End If

        End If

    Next rownum
End If

End Sub


问:
Pandas : Replace values multiple times until the end
I have a pandas df like this:

```<code>import pandas as pd
df = pd.DataFrame({'sales':[114,114,114,113,12,10,8500,8666]})
</code>```

It is cumulative data from sales.
There is a bug in the data : Some observations are wrong.
(No value can be greater than the previous one : i.e., 8500 and 8666 are not correct)
I want to replace these values with the previous one.

I tried this

```<code>df['above'] = df.sales.shift(1)
df.loc[df.above < df.sales, 'sales'] = df.above
</code>```

But this code works only one time, how to extend this code to replace all values until the end of the series (with the previous one) ?

The desired result should looks like :

答:
You can replace values to NaNs by condition and then use ffill - fillna with method='ffill':

```<code>df.loc[df.above < df.sales, 'sales'] = np.nan
df['sales'] = df['sales'].ffill()
print (df)
   sales   above
0  114.0     NaN
1  114.0   114.0
2  114.0   114.0
3  113.0   114.0
4   12.0   113.0
5   10.0    12.0
6   10.0    10.0
7   10.0  8500.0
</code>```

What is same as using mask, which by default replace to NaNs, last cast to int if always integer values:

```<code>df = pd.DataFrame({'sales':[114,114,114,113,12,10,8500,8666]})

df['sales'] = df['sales'].mask(df.sales.shift(1) < df.sales).ffill().astype(int)
print (df)
   sales
0    114
1    114
2    114
3    113
4     12
5     10
6     10
7     10
</code>```

EDIT:

```<code>df = pd.DataFrame({'sales':[114,114,114,113,12,10,8500,8400]})

df['sales'] = df['sales'].mask((df.sales.shift(1) < df.sales).cumsum() > 0).ffill().astype(int)
print (df)
   sales
0    114
1    114
2    114
3    113
4     12
5     10
6     10
7     10
</code>```

Detail:

```<code>print ((df.sales.shift(1) < df.sales).cumsum())
0    0
1    0
2    0
3    0
4    0
5    0
6    1
7    1
Name: sales, dtype: int32

print ((df.sales.shift(1) < df.sales).cumsum() > 0)
0    False
1    False
2    False
3    False
4    False
5    False
6     True
7     True
Name: sales, dtype: bool
</code>```

Body:
I have a pandas df like this:

import pandas as pd
df = pd.DataFrame({'sales':[114,114,114,113,12,10,8500,8666]})

It is cumulative data from sales.
There is a bug in the data : Some observations are wrong.
(No value can be greater than the previous one : i.e., 8500 and 8666 are not correct)
I want to replace these values with the previous one.

I tried this

df['above'] = df.sales.shift(1)
df.loc[df.above < df.sales, 'sales'] = df.above

But this code works only one time, how to extend this code to replace all values until the end of the series (with the previous one) ?

The desired result should looks like :

Body:
You can replace values to NaNs by condition and then use ffill - fillna with method='ffill':

df.loc[df.above < df.sales, 'sales'] = np.nan
df['sales'] = df['sales'].ffill()
print (df)
   sales   above
0  114.0     NaN
1  114.0   114.0
2  114.0   114.0
3  113.0   114.0
4   12.0   113.0
5   10.0    12.0
6   10.0    10.0
7   10.0  8500.0

What is same as using mask, which by default replace to NaNs, last cast to int if always integer values:

df = pd.DataFrame({'sales':[114,114,114,113,12,10,8500,8666]})

df['sales'] = df['sales'].mask(df.sales.shift(1) < df.sales).ffill().astype(int)
print (df)
   sales
0    114
1    114
2    114
3    113
4     12
5     10
6     10
7     10

EDIT:

df = pd.DataFrame({'sales':[114,114,114,113,12,10,8500,8400]})

df['sales'] = df['sales'].mask((df.sales.shift(1) < df.sales).cumsum() > 0).ffill().astype(int)
print (df)
   sales
0    114
1    114
2    114
3    113
4     12
5     10
6     10
7     10

Detail:

print ((df.sales.shift(1) < df.sales).cumsum())
0    0
1    0
2    0
3    0
4    0
5    0
6    1
7    1
Name: sales, dtype: int32

print ((df.sales.shift(1) < df.sales).cumsum() > 0)
0    False
1    False
2    False
3    False
4    False
5    False
6     True
7     True
Name: sales, dtype: bool


问:
Postgresql. CREATE CAST 'character varying' to 'integer'
I want to CREATE CAST a suitable function to convert 'character varying' to 'integer'. Can anyone suggest a function? Everything I try fails.</p>

答:
Use this:

```<code>CREATE CAST (varchar AS integer) WITH INOUT [AS IMPLICIT];
</code>```

It uses the input/output functions of the data types involved.

ContentLicense: CC BY-SA 2.5

Body:
Use this:

CREATE CAST (varchar AS integer) WITH INOUT [AS IMPLICIT];

It uses the input/output functions of the data types involved.


问:
Find Whole Months from date range java
I have two dates:

```<code>Start Date: 2017-01-15
End Date: 2017-05-27
</code>```

Now I want to find the whole month between these two dates. So the result should be:

```<code>Feb-2017
Mar-2017
Apr-2017
</code>```

January is not included in the result because start date starts from the middle of the month and May is not included because end date does not cover whole May month.

How can I achieve this with Java?

I have tried doing something like:

```<code>String date1 = "2015-01-15";
String date2 = "2015-05-27";

DateFormat formater1 = new SimpleDateFormat("MMM-yyyy");
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");

Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();

try {
    startCalendar.setTime(formater.parse(date1));
    endCalendar.setTime(formater.parse(date2));
} catch (ParseException e) {
    e.printStackTrace();
}

System.out.println("startDate:" + startCalendar.getTime());
System.out.println("endCalendar:" + endCalendar.getTime());

while (startCalendar.before(endCalendar)) {
    // add one month to date per loop
    String date = formater1.format(startCalendar.getTime()).toUpperCase();
    System.out.println(date);
    startCalendar.add(Calendar.MONTH, 1);
}
</code>```

But I don't know how to exclude Jan and May from the result. Currently, I am getting this result:

```<code>JAN-2015
FEB-2015
MAR-2015
APR-2015
MAY-2015
</code>```

答:
With the release of Java 8, Oracle dramatically overhauled their date-time libraries to make it much simpler to implement calendar logic. Check out the java.time documentation for more details. Among the supported functions are withDayOfMonth and lastDayOfMonth, which allow you to find specific dates within a given month.

Have a look at this implementation, using the java.time APIs for formatting and date manipulation:

```<code>import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;

public class Main {

    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM-yyyy");

        LocalDate start = LocalDate.of(2017, 1, 15);
        LocalDate end = LocalDate.of(2017, 5, 27);
        List<String> months = new ArrayList<>();

        LocalDate date = start;
        if (date.getDayOfMonth() == 1) {
            date = date.minusDays(1);
        }

        while (date.isBefore(end)) {
            if (date.plusMonths(1).with(lastDayOfMonth()).isAfter(end)) {
                break;
            }

            date = date.plusMonths(1).withDayOfMonth(1);
            months.add(date.format(formatter).toUpperCase());
        }

        System.out.println(months);
    }

}
</code>```

Output:

```<code>> [FEB-2017, MAR-2017, APR-2017]
</code>```

Title: Find Whole Months from date range java

Body:
I have two dates:

Start Date: 2017-01-15
End Date: 2017-05-27

Now I want to find the whole month between these two dates. So the result should be:

Feb-2017
Mar-2017
Apr-2017

January is not included in the result because start date starts from the middle of the month and May is not included because end date does not cover whole May month.

How can I achieve this with Java?

I have tried doing something like:

String date1 = "2015-01-15";
String date2 = "2015-05-27";

DateFormat formater1 = new SimpleDateFormat("MMM-yyyy");
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");

Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();

try {
    startCalendar.setTime(formater.parse(date1));
    endCalendar.setTime(formater.parse(date2));
} catch (ParseException e) {
    e.printStackTrace();
}

System.out.println("startDate:" + startCalendar.getTime());
System.out.println("endCalendar:" + endCalendar.getTime());

while (startCalendar.before(endCalendar)) {
    // add one month to date per loop
    String date = formater1.format(startCalendar.getTime()).toUpperCase();
    System.out.println(date);
    startCalendar.add(Calendar.MONTH, 1);
}

But I don't know how to exclude Jan and May from the result. Currently, I am getting this result:

JAN-2015
FEB-2015
MAR-2015
APR-2015
MAY-2015

Body:
With the release of Java 8, Oracle dramatically overhauled their date-time libraries to make it much simpler to implement calendar logic. Check out the java.time documentation for more details. Among the supported functions are withDayOfMonth and lastDayOfMonth, which allow you to find specific dates within a given month.

Have a look at this implementation, using the java.time APIs for formatting and date manipulation:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;

public class Main {

    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM-yyyy");

        LocalDate start = LocalDate.of(2017, 1, 15);
        LocalDate end = LocalDate.of(2017, 5, 27);
        List<String> months = new ArrayList<>();

        LocalDate date = start;
        if (date.getDayOfMonth() == 1) {
            date = date.minusDays(1);
        }

        while (date.isBefore(end)) {
            if (date.plusMonths(1).with(lastDayOfMonth()).isAfter(end)) {
                break;
            }

            date = date.plusMonths(1).withDayOfMonth(1);
            months.add(date.format(formatter).toUpperCase());
        }

        System.out.println(months);
    }

}

Output:

> [FEB-2017, MAR-2017, APR-2017]


问:
Searching through a 2D array in python 2.7 if a char is in that position
Hi im trying to search through my array if a particular char is in that position and then printing it to the console.

this is my code so far.

```<code>students = [['Gary','Y'],['Steve','N'],['Tom','Y']]

for i in range (len(students)):
        if students[i,1] == 'Y':
            print (students(i,0))
</code>```

答:
Adding to other answers, you could try using filter() also:

```<code>>>> students = [['Gary','Y'],['Steve','N'],['Tom','Y']]
>>> filtered = list(filter(lambda x: x[1] == 'Y', students))
>>> print(filtered)
[['Gary', 'Y'], ['Tom', 'Y']]
>>> print([x[0] for x in filtered])
['Gary', 'Tom']
</code>```

Body:
Hi im trying to search through my array if a particular char is in that position and then printing it to the console.

this is my code so far.

students = [['Gary','Y'],['Steve','N'],['Tom','Y']]

for i in range (len(students)):
        if students[i,1] == 'Y':
            print (students(i,0))

Body:
Adding to other answers, you could try using filter() also:

>>> students = [['Gary','Y'],['Steve','N'],['Tom','Y']]
>>> filtered = list(filter(lambda x: x[1] == 'Y', students))
>>> print(filtered)
[['Gary', 'Y'], ['Tom', 'Y']]
>>> print([x[0] for x in filtered])
['Gary', 'Tom']


问:
Why does the regex (aba?)+ not match with abab?
Given (aba?)+ as the Regex and abab is the string.

Why does it only matches aba?

Since the last a in the regex is optional, isn't abab a match as well?

tested on https://regex101.com/

答:
The correct regex for this is:

```<code>^(aba??)+$
</code>```

and not (aba??)+ as discussed with @WiktorStribizew and YSelf.

Body:
The correct regex for this is:

^(aba??)+$

and not (aba??)+ as discussed with @WiktorStribizew and YSelf.


问:
Get img currentSrc using Vue
Basically, I have an img element that looks like this:

```<code><img
     ref="primaryImg"
     id="primary-img"
     class="profile-img"
     sizes="(max-width: 1920px) 80vw,
     (max-width: 1440px) 70vw,
     (max-width: 1280px) 60vw,
     (max-width: 1020px) 50vw,
     (max-width: 900px) 40vw,
     (max-width: 800px) 30vw,
     (max-width: 600px) 20vw,
     (max-width: 400px) 10vw,
     80vw"
     :srcset="profile.photos.primary._srcset"
     alt="">
</code>```

srcset contains different urls to be used depending on the user's device viewport.

In order to access the element's properties, I used Vue's this.$refs.

On mounted(), I tried to console.dir(this.$refs.primaryImg).

```<code>mounted() {
    console.dir(this.$refs.primaryImg);
},
</code>```

It did show the currentSrc on the browser's console

However, when I tried to do this

console.dir(this.$refs.primaryImg.currentSrc);

It returns an empty string. I assume this has to be a lifecycle issue, the img src might not be initialized at this point of time. How do I get the currentSrc?

答:
The img element object is not completely loaded yet when you are trying to log the currentSrc property.

So use the onload event which is triggered after the img element finishes loading:

```<code>var myImg = this.$refs.primaryImg;
myImg.onload = function(){
    console.dir(myImg.currentSrc);
}
</code>```

Title: Get img currentSrc using Vue

Body:
Basically, I have an img element that looks like this:

srcset contains different urls to be used depending on the user's device viewport.

In order to access the element's properties, I used Vue's this.$refs.

On mounted(), I tried to console.dir(this.$refs.primaryImg).

mounted() {
    console.dir(this.$refs.primaryImg);
},

It did show the currentSrc on the browser's console

However, when I tried to do this

console.dir(this.$refs.primaryImg.currentSrc);

It returns an empty string. I assume this has to be a lifecycle issue, the img src might not be initialized at this point of time. How do I get the currentSrc?

Body:
The img element object is not completely loaded yet when you are trying to log the currentSrc property.

So use the onload event which is triggered after the img element finishes loading:

var myImg = this.$refs.primaryImg;
myImg.onload = function(){
    console.dir(myImg.currentSrc);
}


问:
When to use VARCHAR and DATE/DATETIME
We had this programming discussion on Freenode and this question came up when I was trying to use a VARCHAR(255) to store a Date Variable in this format: D/MM/YYYY. So the question is why is it so bad to use a VARCHAR to store a date. Here are the advantages:

Its faster to code. Previously I used DATE, but date formatting was a real pain.

Its more power hungry to use string than Date? Who cares, we live in the Ghz era.

Its not ethically correct (lolwut?) This is what the other user told me...

So what would you prefer to use to store a date? SQL VARCHAR or SQL DATE?

答:
I'd vote for using the date/datetime types, just for the sake of simplicity/consistency.

If you do store it as a character string, store it in ISO 8601 format:

http://www.iso.org/iso/date_and_time_format

http://xml.coverpages.org/ISO-FDIS-8601.pdf

http://www.cl.cam.ac.uk/~mgk25/iso-time.html

Among other things, ISO 8601 date/time string (A) collate properly, (B) are human readable, (C) are locale-indepedent, and (D) are readily convertable to other formats. To crib from the ISO blurb, ISO 8601 strings offer

representations for the following:

Date

Time of the day

Coordinated universal time (UTC)

Local time with offset to UTC

Date and time

Time intervals

Recurring time intervals

Representations can be in one of two formats: a basic format
  that has a minimal number of characters and an extended format
  that adds characters to enhance human readability. For example,
  the third of January 2003 can be represented as either 20030103
  or 2003-01-03.

[and]

offer the following advantages over many of the locally used
  representations:

Easily readable and writeable by systems

Easily comparable and sortable

Language independent

Larger units are written in front of smaller units

For most representations the notation is short and of constant length

One last thing: If all you need to do is store a date, then storing it in the ISO 8601 short form YYYYMMDD in a char(8) column takes no more storage than a datetime value (and you don't need to worry about the 3 millisecond gap between the last tick of the one day and the first tick of the next. But that's a matter for another discussion. If you break it up into 3 columns — YYYY char(4), MM char(2), DD char(2) you'll use up the same amount of storage, and get more options for indexing. Even better, store the fields as a short for yyyy (4 bytes), and a tinyint for each of MM and DD — now you're down to 6 bytes for the date. The drawback, of course, to decomposing the date components into their constituent parts is that conversion to proper date/time data types is complicated.

ContentLicense: CC BY-SA 4.0

Title: When to use VARCHAR and DATE/DATETIME


问:
Position of `@` label in Kotlin when denoting receiver with `this`
I am a newbie in Kotlin. I am curious about the difference of labeled this in Kotlin with prefix @ or postfix @.

I have just seen a code which writes SignInActivity@this, which seems to work exactly same as this@SignInActivity.

Are these two exactly the same thing? If not, what is the difference between the two?

I was trying to do some research on *@this form, but I couldn't find any reference on it. All I could find was this official doc which demonstrates this@*. It will be nice if anybody could share me with the correct reference I should go to.

答:
SignInActivity@this means SignInActivity.this (Java)
this@SignInActivity means - using the  SignInActivity context instead a local context (usually is in closures).</p>


问:
Informatica workflow fails on failure of command task with UNCHECKED fail parent if task fails property
I have a command task to call a batch file which returns 1 if File.Ok does not exists and 0 if File.Ok exists in a particular location. Following this command task I have 2 links:

link 1: $commandtask.status = succeeded

link 2: $commandtask.status = failed

After each of these links there are several session and other tasks.

PROBLEM: Whenever File.OK is not found, Link 2 is executed followed by tasks/sessions of this branch (as desired and expected) but after executing all remaining items the workflow gets failed.

note: I have not checked 'Fail Parent if task fails' property anywhere.

答: You might have checked the "Fail parent if task does not run" in some task. If the task with this property checked does not run then it fails the workflow.</p>


问:
Calculate difference in hours PHP

I am trying to write a PHP code to count publishing time-lapse. I have a date and time in this format: Sun, 03 Dec 2017 12:45:09 GMT ($pub_time).

My code:

```<code>$timestamp=  strtotime($pub_time) ;
$minutes = floor((strtotime('now') - $timestamp)/ 60);
if  ($minutes < 60) {
    return $time_string = $minutes . ' minutes ago';
} else {
    return $time_string = floor(($minutes) / 60) . ' hours ago';
}
</code>```

As a result I need to get smth like this : "4 hours ago".

Using my code I get this result - 420104.58333333 hours ago, whatever input date there is. Any thoughts?

答:
You can use the DateTime class build in php and do it like that:

```<code>$time = 'Sun, 03 Dec 2017 12:25:09 GMT';
$oldTime = new DateTime($time);
$now = new DateTime(date("Y-m-d H:i:s"));
$difference = $oldTime->diff($now);

$hours = $difference->h;
$minutes = $difference->i;
$days = $difference->d;
</code>```

from here you build your logic to display as you wish.

Title: Calculate difference in hours PHP

Body:
I am trying to write a PHP code to count publishing time-lapse. I have a date and time in this format: Sun, 03 Dec 2017 12:45:09 GMT ($pub_time).

My code:

$timestamp=  strtotime($pub_time) ;
$minutes = floor((strtotime('now') - $timestamp)/ 60);
if  ($minutes < 60) {
    return $time_string = $minutes . ' minutes ago';
} else {
    return $time_string = floor(($minutes) / 60) . ' hours ago';
}

As a result I need to get smth like this : "4 hours ago".

Using my code I get this result - 420104.58333333 hours ago, whatever input date there is. Any thoughts?

Body:
You can use the DateTime class build in php and do it like that:

$time = 'Sun, 03 Dec 2017 12:25:09 GMT';
$oldTime = new DateTime($time);
$now = new DateTime(date("Y-m-d H:i:s"));
$difference = $oldTime->diff($now);

$hours = $difference->h;
$minutes = $difference->i;
$days = $difference->d;

from here you build your logic to display as you wish.


问:
How to get all(!) closest directives/components in Angular?
Looking at :

```<code><div class="widget-content">
  <div class="widget-content">
    <div>
        <widget-item></widget-item>
    </div>
  </div>
</div>
</code>```

I'm able to get the first(!) closest widget-content within the <widget-item></widget-item> component.

It's pretty easy to do it by creating a directive  :

```<code>@Directive({
  selector: '.widget-content'
})
export class WidgetContentDirective {
}
</code>```

And by Injecting  to the constructor of widget-item :

```<code>constructor(private widgetContentQuery: WidgetContentDirective) { }

  ngOnInit() {
    console.log(this.widgetContentQuery);
  }
</code>```

Result :

Question:

There are two  widget-content wrappers.

How can I get an array of them both  within the widget-item constructor ?

full disclosure:

for learning purpose. There is no real scenario. ( I'm not after jQuery solutions)

Stackblitz

答:
Well, that's an unusual request, but I believe there is a way to do this. It's not easy, but it uses an InjectionToken on the WidgetContentDirective:

stackblitz

Basically you've got this InjectionToken:

```<code>export const WidgetContents: InjectionToken<WidgetContentDirective[]> =
  new InjectionToken('WIDGET_CONTENTS');
</code>```

And using @Optional() and @SkipSelf() inject this in the providers array of your WidgetContentDirective, together with the current WidgetContentDirective:

```<code>@Directive({
  selector: '.widget-content',
  providers: [{
        provide: WidgetContents,
        useFactory: (
          widgetContent: WidgetContentDirective,
          parents?: WidgetContentDirective[]
        ) => {
          // filter because of optional
          return [widgetContent, ...parents].filter(widget => widget);
        },
        deps: [
          forwardRef(() => WidgetContentDirective),
          [new Optional(), new SkipSelf(), new Inject(WidgetContents)]
        ]
    }
  ]
})
</code>```

You can then use this InjectionToken inside your WidgetItemComponent:

```<code>export class WidgetItemComponent implements OnInit {

  constructor(
    @Inject(WidgetContents)
    private widgetContentQuery: WidgetContentDirective[]
  ) {}

  ngOnInit() {
    console.log(this.widgetContentQuery);
  }

}
</code>```

Body:
Looking at :

        <widget-item></widget-item>

I'm able to get the first(!) closest widget-content within the <widget-item></widget-item> component.

It's pretty easy to do it by creating a directive  :

@Directive({
  selector: '.widget-content'
})
export class WidgetContentDirective {
}

And by Injecting  to the constructor of widget-item :

constructor(private widgetContentQuery: WidgetContentDirective) { }

  ngOnInit() {
    console.log(this.widgetContentQuery);
  }

Result :

Question:

There are two  widget-content wrappers.

How can I get an array of them both  within the widget-item constructor ?

full disclosure:

for learning purpose. There is no real scenario. ( I'm not after jQuery solutions)

Stackblitz

Body:
Well, that's an unusual request, but I believe there is a way to do this. It's not easy, but it uses an InjectionToken on the WidgetContentDirective:

stackblitz

Basically you've got this InjectionToken:

export const WidgetContents: InjectionToken<WidgetContentDirective[]> =
  new InjectionToken('WIDGET_CONTENTS');

And using @Optional() and @SkipSelf() inject this in the providers array of your WidgetContentDirective, together with the current WidgetContentDirective:

@Directive({
  selector: '.widget-content',
  providers: [{
        provide: WidgetContents,
        useFactory: (
          widgetContent: WidgetContentDirective,
          parents?: WidgetContentDirective[]
        ) => {
          // filter because of optional
          return [widgetContent, ...parents].filter(widget => widget);
        },
        deps: [
          forwardRef(() => WidgetContentDirective),
          [new Optional(), new SkipSelf(), new Inject(WidgetContents)]
        ]
    }
  ]
})

You can then use this InjectionToken inside your WidgetItemComponent:

export class WidgetItemComponent implements OnInit {

  constructor(
    @Inject(WidgetContents)
    private widgetContentQuery: WidgetContentDirective[]
  ) {}

  ngOnInit() {
    console.log(this.widgetContentQuery);
  }

}


问:
Comparison : interface methods vs virtual methods vs abstract methods
What are the advantages and disadvantages of each of these?

interface methods

virtual methods

abstract methods

When one should choose what? What are the points one should keep in mind when making this decision?

答:
Virtual and abstract are almost the same. A virtual method has an implementation in the base class that can optionally be overridden, while an abstract method hasn't and must be overridden in a child class. Otherwise they are the same. Choosing between them depends on the situation. If you got a base implementation, you use virtual. If you don't, and you need every descendant to implement it for itself, you choose abstract.

Interface methods are implementations of a method that is declared in an interface that the class implements. This is quite unrelated to the other two. I think a method can be both virtual and interface. The advantage of interfaces is that you declare one interface (duh) that can be implemented by two totally different classes. That way, you can run the same code on two different classes, as long as the methods you'd like to call are declared in an interface they share.


问:
Error in twitter4j classes while feeding data from twitter using flume
I am using the sources provided by cloudera flume-sources-1.0-SNAPSHOT uploaded on github.

I am getting error below. the method does not exist in the configuration.class the jar provided by cloudera in twitter4j.

How to solve this issue?

```<code> {

    14/06/12 03:04:56 INFO node.PollingPropertiesFileConfigurationProvider:                                             Configuration provider starting
    14/06/12 03:04:56 INFO node.PollingPropertiesFileConfigurationProvider: Reloading configuration file:conf/tagent
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Processing:HDFS
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Processing:HDFS
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Processing:HDFS
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Added sinks: HDFS Agent: TwitterAgent
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Processing:HDFS
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Processing:HDFS
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Processing:HDFS
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Processing:HDFS
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Processing:HDFS
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Post-validation flume configuration contains configuration for agents: [TwitterAgent]
    14/06/12 03:04:56 INFO node.AbstractConfigurationProvider: Creating channels
    14/06/12 03:04:56 INFO channel.DefaultChannelFactory: Creating instance of channel MemChannel type memory
    14/06/12 03:04:57 INFO node.AbstractConfigurationProvider: Created channel MemChannel
    14/06/12 03:04:57 INFO source.DefaultSourceFactory: Creating instance of source Twitter, type com.cloudera.flume.source.TwitterSource
    14/06/12 03:04:57 ERROR node.PollingPropertiesFileConfigurationProvider: Unhandled error
    java.lang.NoSuchMethodError:         twitter4j.conf.Configuration.getRequestHeaders()Ljava/util/Map;
at         twitter4j.StreamingReadTimeoutConfiguration.getRequestHeaders(TwitterStreamImpl.java:664)
at twitter4j.internal.http.HttpClientWrapper.<init>(HttpClientWrapper.java:47)
at twitter4j.TwitterStreamImpl.<init>(TwitterStreamImpl.java:54)
at twitter4j.TwitterStreamFactory.<clinit>(TwitterStreamFactory.java:40)
at com.cloudera.flume.source.TwitterSource.<init>(TwitterSource.java:64)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:355)
at java.lang.Class.newInstance(Class.java:308)
at org.apache.flume.source.DefaultSourceFactory.create(DefaultSourceFactory.java:42)
at org.apache.flume.node.AbstractConfigurationProvider.loadSources(AbstractConfigurationProvider.java:327)
at org.apache.flume.node.AbstractConfigurationProvider.getConfiguration(AbstractConfigurationProvider.java:102)
at org.apache.flume.node.PollingPropertiesFileConfigurationProvider$FileWatcherRunnable.run(PollingPropertiesFileConfigurationProvider.java:140)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:317)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:150)
at  java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(ScheduledThreadPoolExecutor.java:98)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:204)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)

   }
</code>```

答:
You have to replace all the  twitter4j-3.0.3 libraries placed in flume/lib folder by the twitter4j-2.x.x version. The reason is that same class name is conflicting in twitter4j-3.0.3 and flume-sources-1.0-SNAPSHOT.jar

To avoid this you have to make changes in the twitter4j properties by putting the following property in twitter4j.properties as class path:

```<code>streamBaseURL=https://stream.twitter.com/1.1/ `
</code>```

Or you can download the new flume-source-1.0-snapshot.jar from here.

This issue has been resolved by the Twitter community, for a full explanation you can check this discussion.

Body:
I am using the sources provided by cloudera flume-sources-1.0-SNAPSHOT uploaded on github.

I am getting error below. the method does not exist in the configuration.class the jar provided by cloudera in twitter4j.

How to solve this issue?

 {

    14/06/12 03:04:56 INFO node.PollingPropertiesFileConfigurationProvider:                                             Configuration provider starting
    14/06/12 03:04:56 INFO node.PollingPropertiesFileConfigurationProvider: Reloading configuration file:conf/tagent
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Processing:HDFS
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Processing:HDFS
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Processing:HDFS
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Added sinks: HDFS Agent: TwitterAgent
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Processing:HDFS
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Processing:HDFS
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Processing:HDFS
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Processing:HDFS
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Processing:HDFS
    14/06/12 03:04:56 INFO conf.FlumeConfiguration: Post-validation flume configuration contains configuration for agents: [TwitterAgent]
    14/06/12 03:04:56 INFO node.AbstractConfigurationProvider: Creating channels
    14/06/12 03:04:56 INFO channel.DefaultChannelFactory: Creating instance of channel MemChannel type memory
    14/06/12 03:04:57 INFO node.AbstractConfigurationProvider: Created channel MemChannel
    14/06/12 03:04:57 INFO source.DefaultSourceFactory: Creating instance of source Twitter, type com.cloudera.flume.source.TwitterSource
    14/06/12 03:04:57 ERROR node.PollingPropertiesFileConfigurationProvider: Unhandled error
    java.lang.NoSuchMethodError:         twitter4j.conf.Configuration.getRequestHeaders()Ljava/util/Map;
at         twitter4j.StreamingReadTimeoutConfiguration.getRequestHeaders(TwitterStreamImpl.java:664)
at twitter4j.internal.http.HttpClientWrapper.<init>(HttpClientWrapper.java:47)
at twitter4j.TwitterStreamImpl.<init>(TwitterStreamImpl.java:54)
at twitter4j.TwitterStreamFactory.<clinit>(TwitterStreamFactory.java:40)
at com.cloudera.flume.source.TwitterSource.<init>(TwitterSource.java:64)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:355)
at java.lang.Class.newInstance(Class.java:308)
at org.apache.flume.source.DefaultSourceFactory.create(DefaultSourceFactory.java:42)
at org.apache.flume.node.AbstractConfigurationProvider.loadSources(AbstractConfigurationProvider.java:327)
at org.apache.flume.node.AbstractConfigurationProvider.getConfiguration(AbstractConfigurationProvider.java:102)
at org.apache.flume.node.PollingPropertiesFileConfigurationProvider$FileWatcherRunnable.run(PollingPropertiesFileConfigurationProvider.java:140)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:317)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:150)
at  java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(ScheduledThreadPoolExecutor.java:98)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:204)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)

   }

Body:
You have to replace all the  twitter4j-3.0.3 libraries placed in flume/lib folder by the twitter4j-2.x.x version. The reason is that same class name is conflicting in twitter4j-3.0.3 and flume-sources-1.0-SNAPSHOT.jar

To avoid this you have to make changes in the twitter4j properties by putting the following property in twitter4j.properties as class path:

streamBaseURL=https://stream.twitter.com/1.1/ `

Or you can download the new flume-source-1.0-snapshot.jar from here.

This issue has been resolved by the Twitter community, for a full explanation you can check this discussion.


问:
ionic 3 firebase Error: ./node_modules/firebase/auth/index.js
I have ionic 3 app, and for some reason, it's not running ionic cordova run android

I have tried to downgrade firebase and @firebase along with android between 6.4.0 and 6.3.2, along with tweaking the version of so many libraries and dependencies!

This has been going on with sandbox project as well! and I searched the internet for it, but it seems to be a new error!

When you will read the error log down you will notice that it's compalining about Error: Can't resolve '@firebase/auth' in node_modules/firebase/auth thus here is the content of this file:

```<code>require('@firebase/auth'); // only one line, and when I click on it it's pointing to `node_modules/firebase/node_modules/@firebase/auth/dist/auth.js`
</code>```

ionic info output:

```<code>cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-utils  : 1.19.0
    ionic (Ionic CLI) : 3.19.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 3.1.2
    Cordova Platforms  : android 6.3.0
    Ionic Framework    : ionic-angular 3.9.2

System:

    Android SDK Tools : 25.2.5
    ios-deploy        : 1.9.2
    ios-sim           : 6.1.2
    Node              : v8.9.1
    npm               : 5.2.0
    OS                : macOS High Sierra
    Xcode             : Xcode 9.1 Build version 9B55

Environment Variables:
</code>```

the exact error is as follows:

```<code>[21:34:40]  copy finished in 6.73 s
Error: ./node_modules/firebase/auth/index.js
Module not found: Error: Can't resolve '@firebase/auth' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/auth'
resolve '@firebase/auth' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/auth'
  Parsed request is a module
  using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./auth)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./auth)
    resolve as module
      looking for modules in /Users/Mike/Code/ionic/foo-bar/node_modules
        using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
        after using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules/@firebase/auth)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth.json doesn't exist
            as directory
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth doesn't exist
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth.ts]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth.js]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth.json]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth]
 @ ./node_modules/firebase/auth/index.js 17:0-25
 @ ./node_modules/angularfire2/auth/auth.module.js
 @ ./node_modules/angularfire2/auth/public_api.js
 @ ./node_modules/angularfire2/auth/index.js
 @ ./src/app/app.module.ts
 @ ./src/app/main.ts,./node_modules/firebase/database/index.js
Module not found: Error: Can't resolve '@firebase/database' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/database'
resolve '@firebase/database' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/database'
  Parsed request is a module
  using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./database)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./database)
    resolve as module
      looking for modules in /Users/Mike/Code/ionic/foo-bar/node_modules
        using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
        after using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules/@firebase/database)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database.json doesn't exist
            as directory
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database doesn't exist
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database.ts]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database.js]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database.json]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database]
 @ ./node_modules/firebase/database/index.js 17:17-46
 @ ./node_modules/firebase/index.js
 @ ./src/providers/imgHandler.ts
 @ ./src/app/app.module.ts
 @ ./src/app/main.ts,./node_modules/firebase/firestore/index.js
Module not found: Error: Can't resolve '@firebase/firestore' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/firestore'
resolve '@firebase/firestore' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/firestore'
  Parsed request is a module
  using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./firestore)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./firestore)
    resolve as module
      looking for modules in /Users/Mike/Code/ionic/foo-bar/node_modules
        using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
        after using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules/@firebase/firestore)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore.json doesn't exist
            as directory
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore doesn't exist
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore.ts]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore.js]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore.json]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore]
 @ ./node_modules/firebase/firestore/index.js 17:0-30
 @ ./node_modules/angularfire2/firestore/firestore.js
 @ ./node_modules/angularfire2/firestore/public_api.js
 @ ./node_modules/angularfire2/firestore/index.js
 @ ./src/app/app.module.ts
 @ ./src/app/main.ts,./node_modules/firebase/messaging/index.js
Module not found: Error: Can't resolve '@firebase/messaging' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/messaging'
resolve '@firebase/messaging' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/messaging'
  Parsed request is a module
  using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./messaging)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./messaging)
    resolve as module
      looking for modules in /Users/Mike/Code/ionic/foo-bar/node_modules
        using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
        after using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules/@firebase/messaging)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging.json doesn't exist
            as directory
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging doesn't exist
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging.ts]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging.js]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging.json]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging]
 @ ./node_modules/firebase/messaging/index.js 17:0-30
 @ ./node_modules/firebase/index.js
 @ ./src/providers/imgHandler.ts
 @ ./src/app/app.module.ts
 @ ./src/app/main.ts,./node_modules/firebase/storage/index.js
Module not found: Error: Can't resolve '@firebase/storage' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/storage'
resolve '@firebase/storage' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/storage'
  Parsed request is a module
  using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./storage)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./storage)
    resolve as module
      looking for modules in /Users/Mike/Code/ionic/foo-bar/node_modules
        using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
        after using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules/@firebase/storage)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage.json doesn't exist
            as directory
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage doesn't exist
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage.ts]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage.js]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage.json]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage]
 @ ./node_modules/firebase/storage/index.js 17:0-28
 @ ./node_modules/firebase/index.js
 @ ./src/providers/imgHandler.ts
 @ ./src/app/app.module.ts
 @ ./src/app/main.ts
    at new BuildError (/Users/Mike/Code/ionic/foo-bar/node_modules/@ionic/app-scripts/dist/util/errors.js:16:28)
    at callback (/Users/Mike/Code/ionic/foo-bar/node_modules/@ionic/app-scripts/dist/webpack.js:121:28)
    at emitRecords.err (/Users/Mike/Code/ionic/foo-bar/node_modules/webpack/lib/Compiler.js:269:13)
    at Compiler.emitRecords (/Users/Mike/Code/ionic/foo-bar/node_modules/webpack/lib/Compiler.js:375:38)
    at emitAssets.err (/Users/Mike/Code/ionic/foo-bar/node_modules/webpack/lib/Compiler.js:262:10)
    at applyPluginsAsyncSeries1.err (/Users/Mike/Code/ionic/foo-bar/node_modules/webpack/lib/Compiler.js:368:12)
    at next (/Users/Mike/Code/ionic/foo-bar/node_modules/tapable/lib/Tapable.js:218:11)
    at Compiler.compiler.plugin (/Users/Mike/Code/ionic/foo-bar/node_modules/webpack/lib/performance/SizeLimitsPlugin.js:99:4)
    at Compiler.applyPluginsAsyncSeries1 (/Users/Mike/Code/ionic/foo-bar/node_modules/tapable/lib/Tapable.js:222:13)
    at Compiler.afterEmit (/Users/Mike/Code/ionic/foo-bar/node_modules/webpack/lib/Compiler.js:365:9)
</code>```

package.json:

```<code>{
  "name": "foo-bar",
  "version": "2.0.1",
  "author": "Optimatec",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.4.4",
    "@angular/compiler": "4.4.4",
    "@angular/compiler-cli": "4.4.4",
    "@angular/core": "4.4.4",
    "@angular/forms": "4.4.4",
    "@angular/http": "4.4.4",
    "@angular/platform-browser": "4.4.4",
    "@angular/platform-browser-dynamic": "4.4.4",
    "@ionic-native/app-version": "^4.4.2",
    "@ionic-native/call-number": "4.3.0",
    "@ionic-native/camera": "4.3.0",
    "@ionic-native/clipboard": "^4.4.2",
    "@ionic-native/core": "4.3.0",
    "@ionic-native/diagnostic": "4.3.0",
    "@ionic-native/facebook": "4.3.0",
    "@ionic-native/file": "4.3.0",
    "@ionic-native/file-chooser": "4.3.0",
    "@ionic-native/file-path": "4.3.0",
    "@ionic-native/file-transfer": "^4.4.2",
    "@ionic-native/firebase": "4.3.0",
    "@ionic-native/geolocation": "4.3.0",
    "@ionic-native/google-maps": "4.3.0",
    "@ionic-native/google-plus": "4.3.0",
    "@ionic-native/in-app-browser": "4.3.0",
    "@ionic-native/launch-navigator": "4.3.0",
    "@ionic-native/onesignal": "4.3.0",
    "@ionic-native/social-sharing": "4.3.0",
    "@ionic-native/splash-screen": "4.3.0",
    "@ionic-native/status-bar": "4.3.0",
    "@ionic-native/vibration": "4.3.0",
    "@ionic/storage": "2.1.3",
    "@ngx-translate/core": "8.0.0",
    "@ngx-translate/http-loader": "2.0.0",
    "angular2-moment": "^1.7.0",
    "angularfire2": "^5.0.0-rc.0",
    "branch-cordova-sdk": "^2.6.18",
    "call-number": "^1.0.1",
    "com.googlemaps.ios": "https://github.com/mapsplugin/cordova-plugin-googlemaps-sdk",
    "cordova-android": "^6.3.0",
    "cordova-clipboard": "^1.1.1",
    "cordova-plugin-actionsheet": "^2.3.3",
    "cordova-plugin-app-version": "^0.1.9",
    "cordova-plugin-camera": "^2.4.1",
    "cordova-plugin-compat": "^1.2.0",
    "cordova-plugin-device": "^1.1.7",
    "cordova-plugin-dialogs": "^1.3.4",
    "cordova-plugin-facebook4": "^1.9.1",
    "cordova-plugin-file": "^5.0.0",
    "cordova-plugin-file-transfer": "^1.7.0",
    "cordova-plugin-filechooser": "^1.0.1",
    "cordova-plugin-filepath": "^1.1.0",
    "cordova-plugin-firebase": "^0.1.24",
    "cordova-plugin-geolocation": "^2.4.3",
    "cordova-plugin-googlemaps": "^2.1.1",
    "cordova-plugin-googlemaps-sdk": "git+https://github.com/mapsplugin/cordova-plugin-googlemaps-sdk.git",
    "cordova-plugin-googleplus": "^5.1.1",
    "cordova-plugin-inappbrowser": "^1.7.2",
    "cordova-plugin-splashscreen": "^4.1.0",
    "cordova-plugin-statusbar": "^2.3.0",
    "cordova-plugin-vibration": "^2.1.6",
    "cordova-plugin-whitelist": "^1.3.3",
    "cordova-plugin-x-socialsharing": "^5.2.1",
    "cordova.plugins.diagnostic": "^3.7.2",
    "es6-promise-plugin": "^4.1.0",
    "firebase": "^4.5.0",
    "ionic-angular": "^3.7.1",
    "ionic-img-viewer": "2.7.0",
    "ionic-plugin-keyboard": "^2.2.1",
    "ionic2-rating": "^1.2.2",
    "ionicons": "3.0.0",
    "moment": "^2.19.2",
    "onesignal-cordova-plugin": "^2.2.4",
    "promise-polyfill": "6.1.0",
    "rxjs": "5.4.3",
    "sw-toolbox": "3.6.0",
    "uk.co.workingedge.phonegap.plugin.launchnavigator": "^4.1.0",
    "zone.js": "0.8.18"
  },
  "devDependencies": {
    "@ionic/app-scripts": "3.1.2",
    "typescript": "2.4.0"
  },
  "description": "An Ionic project",
  "cordova": {
    "plugins": {
      "cordova-plugin-x-socialsharing": {},
      "cordova-plugin-device": {},
      "cordova-plugin-splashscreen": {},
      "cordova-plugin-statusbar": {},
      "cordova-plugin-whitelist": {},
      "ionic-plugin-keyboard": {},
      "cordova-plugin-firebase": {},
      "call-number": {},
      "mx.ferreyra.callnumber": {},
      "cordova-plugin-vibration": {},
      "cordova-plugin-facebook4": {
        "APP_ID": "15196419",
        "APP_NAME": "FooBar"
      },
      "cordova-plugin-camera": {},
      "onesignal-cordova-plugin": {},
      "cordova-plugin-inappbrowser": {},
      "cordova-plugin-googleplus": {
        "REVERSED_CLIENT_ID": "com.googleusercontent.app"
      },
      "cordova.plugins.diagnostic": {},
      "cordova-plugin-filechooser": {},
      "cordova-plugin-filepath": {},
      "branch-cordova-sdk": {},
      "uk.co.workingedge.phonegap.plugin.launchnavigator": {},
      "cordova-clipboard": {},
      "cordova-plugin-app-version": {},
      "cordova-plugin-file-transfer": {},
      "cordova-plugin-googlemaps": {
        "API_KEY_FOR_ANDROID": "AIzaSyBYJVEVRyo7Az",
        "API_KEY_FOR_IOS": "AIzaSyCqe2DU",
        "LOCATION_WHEN_IN_USE_DESCRIPTION": "Show your location on the map",
        "LOCATION_ALWAYS_USAGE_DESCRIPTION": "Trace your location on the map"
      },
      "cordova-plugin-geolocation": {
        "GEOLOCATION_USAGE_DESCRIPTION": "To display to you the most close places based on your location"
      },
      "com.googlemaps.ios": {},
      "cordova-plugin-file": {}
    },
    "platforms": [
      "android"
    ]
  }
}
</code>```

答:
It was all about firebase version it should not be 4.7.0 so I downgraded it.

The spell is:

npm install firebase@4.6.2 --save

Body:
I have ionic 3 app, and for some reason, it's not running ionic cordova run android

I have tried to downgrade firebase and @firebase along with android between 6.4.0 and 6.3.2, along with tweaking the version of so many libraries and dependencies!

This has been going on with sandbox project as well! and I searched the internet for it, but it seems to be a new error!

When you will read the error log down you will notice that it's compalining about Error: Can't resolve '@firebase/auth' in node_modules/firebase/auth thus here is the content of this file:

require('@firebase/auth'); // only one line, and when I click on it it's pointing to `node_modules/firebase/node_modules/@firebase/auth/dist/auth.js`

ionic info output:

cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-utils  : 1.19.0
    ionic (Ionic CLI) : 3.19.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 3.1.2
    Cordova Platforms  : android 6.3.0
    Ionic Framework    : ionic-angular 3.9.2

System:

    Android SDK Tools : 25.2.5
    ios-deploy        : 1.9.2
    ios-sim           : 6.1.2
    Node              : v8.9.1
    npm               : 5.2.0
    OS                : macOS High Sierra
    Xcode             : Xcode 9.1 Build version 9B55

Environment Variables:

the exact error is as follows:

[21:34:40]  copy finished in 6.73 s
Error: ./node_modules/firebase/auth/index.js
Module not found: Error: Can't resolve '@firebase/auth' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/auth'
resolve '@firebase/auth' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/auth'
  Parsed request is a module
  using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./auth)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./auth)
    resolve as module
      looking for modules in /Users/Mike/Code/ionic/foo-bar/node_modules
        using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
        after using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules/@firebase/auth)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth.json doesn't exist
            as directory
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth doesn't exist
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth.ts]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth.js]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth.json]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/auth]
 @ ./node_modules/firebase/auth/index.js 17:0-25
 @ ./node_modules/angularfire2/auth/auth.module.js
 @ ./node_modules/angularfire2/auth/public_api.js
 @ ./node_modules/angularfire2/auth/index.js
 @ ./src/app/app.module.ts
 @ ./src/app/main.ts,./node_modules/firebase/database/index.js
Module not found: Error: Can't resolve '@firebase/database' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/database'
resolve '@firebase/database' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/database'
  Parsed request is a module
  using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./database)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./database)
    resolve as module
      looking for modules in /Users/Mike/Code/ionic/foo-bar/node_modules
        using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
        after using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules/@firebase/database)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database.json doesn't exist
            as directory
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database doesn't exist
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database.ts]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database.js]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database.json]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/database]
 @ ./node_modules/firebase/database/index.js 17:17-46
 @ ./node_modules/firebase/index.js
 @ ./src/providers/imgHandler.ts
 @ ./src/app/app.module.ts
 @ ./src/app/main.ts,./node_modules/firebase/firestore/index.js
Module not found: Error: Can't resolve '@firebase/firestore' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/firestore'
resolve '@firebase/firestore' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/firestore'
  Parsed request is a module
  using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./firestore)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./firestore)
    resolve as module
      looking for modules in /Users/Mike/Code/ionic/foo-bar/node_modules
        using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
        after using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules/@firebase/firestore)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore.json doesn't exist
            as directory
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore doesn't exist
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore.ts]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore.js]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore.json]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/firestore]
 @ ./node_modules/firebase/firestore/index.js 17:0-30
 @ ./node_modules/angularfire2/firestore/firestore.js
 @ ./node_modules/angularfire2/firestore/public_api.js
 @ ./node_modules/angularfire2/firestore/index.js
 @ ./src/app/app.module.ts
 @ ./src/app/main.ts,./node_modules/firebase/messaging/index.js
Module not found: Error: Can't resolve '@firebase/messaging' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/messaging'
resolve '@firebase/messaging' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/messaging'
  Parsed request is a module
  using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./messaging)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./messaging)
    resolve as module
      looking for modules in /Users/Mike/Code/ionic/foo-bar/node_modules
        using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
        after using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules/@firebase/messaging)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging.json doesn't exist
            as directory
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging doesn't exist
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging.ts]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging.js]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging.json]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/messaging]
 @ ./node_modules/firebase/messaging/index.js 17:0-30
 @ ./node_modules/firebase/index.js
 @ ./src/providers/imgHandler.ts
 @ ./src/app/app.module.ts
 @ ./src/app/main.ts,./node_modules/firebase/storage/index.js
Module not found: Error: Can't resolve '@firebase/storage' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/storage'
resolve '@firebase/storage' in '/Users/Mike/Code/ionic/foo-bar/node_modules/firebase/storage'
  Parsed request is a module
  using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./storage)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/Mike/Code/ionic/foo-bar/node_modules/firebase/package.json (relative path: ./storage)
    resolve as module
      looking for modules in /Users/Mike/Code/ionic/foo-bar/node_modules
        using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
        after using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules)
          using description file: /Users/Mike/Code/ionic/foo-bar/package.json (relative path: ./node_modules/@firebase/storage)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage.json doesn't exist
            as directory
              /Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage doesn't exist
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage.ts]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage.js]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage.json]
[/Users/Mike/Code/ionic/foo-bar/node_modules/@firebase/storage]
 @ ./node_modules/firebase/storage/index.js 17:0-28
 @ ./node_modules/firebase/index.js
 @ ./src/providers/imgHandler.ts
 @ ./src/app/app.module.ts
 @ ./src/app/main.ts
    at new BuildError (/Users/Mike/Code/ionic/foo-bar/node_modules/@ionic/app-scripts/dist/util/errors.js:16:28)
    at callback (/Users/Mike/Code/ionic/foo-bar/node_modules/@ionic/app-scripts/dist/webpack.js:121:28)
    at emitRecords.err (/Users/Mike/Code/ionic/foo-bar/node_modules/webpack/lib/Compiler.js:269:13)
    at Compiler.emitRecords (/Users/Mike/Code/ionic/foo-bar/node_modules/webpack/lib/Compiler.js:375:38)
    at emitAssets.err (/Users/Mike/Code/ionic/foo-bar/node_modules/webpack/lib/Compiler.js:262:10)
    at applyPluginsAsyncSeries1.err (/Users/Mike/Code/ionic/foo-bar/node_modules/webpack/lib/Compiler.js:368:12)
    at next (/Users/Mike/Code/ionic/foo-bar/node_modules/tapable/lib/Tapable.js:218:11)
    at Compiler.compiler.plugin (/Users/Mike/Code/ionic/foo-bar/node_modules/webpack/lib/performance/SizeLimitsPlugin.js:99:4)
    at Compiler.applyPluginsAsyncSeries1 (/Users/Mike/Code/ionic/foo-bar/node_modules/tapable/lib/Tapable.js:222:13)
    at Compiler.afterEmit (/Users/Mike/Code/ionic/foo-bar/node_modules/webpack/lib/Compiler.js:365:9)

package.json:

{
  "name": "foo-bar",
  "version": "2.0.1",
  "author": "Optimatec",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.4.4",
    "@angular/compiler": "4.4.4",
    "@angular/compiler-cli": "4.4.4",
    "@angular/core": "4.4.4",
    "@angular/forms": "4.4.4",
    "@angular/http": "4.4.4",
    "@angular/platform-browser": "4.4.4",
    "@angular/platform-browser-dynamic": "4.4.4",
    "@ionic-native/app-version": "^4.4.2",
    "@ionic-native/call-number": "4.3.0",
    "@ionic-native/camera": "4.3.0",
    "@ionic-native/clipboard": "^4.4.2",
    "@ionic-native/core": "4.3.0",
    "@ionic-native/diagnostic": "4.3.0",
    "@ionic-native/facebook": "4.3.0",
    "@ionic-native/file": "4.3.0",
    "@ionic-native/file-chooser": "4.3.0",
    "@ionic-native/file-path": "4.3.0",
    "@ionic-native/file-transfer": "^4.4.2",
    "@ionic-native/firebase": "4.3.0",
    "@ionic-native/geolocation": "4.3.0",
    "@ionic-native/google-maps": "4.3.0",
    "@ionic-native/google-plus": "4.3.0",
    "@ionic-native/in-app-browser": "4.3.0",
    "@ionic-native/launch-navigator": "4.3.0",
    "@ionic-native/onesignal": "4.3.0",
    "@ionic-native/social-sharing": "4.3.0",
    "@ionic-native/splash-screen": "4.3.0",
    "@ionic-native/status-bar": "4.3.0",
    "@ionic-native/vibration": "4.3.0",
    "@ionic/storage": "2.1.3",
    "@ngx-translate/core": "8.0.0",
    "@ngx-translate/http-loader": "2.0.0",
    "angular2-moment": "^1.7.0",
    "angularfire2": "^5.0.0-rc.0",
    "branch-cordova-sdk": "^2.6.18",
    "call-number": "^1.0.1",
    "com.googlemaps.ios": "https://github.com/mapsplugin/cordova-plugin-googlemaps-sdk",
    "cordova-android": "^6.3.0",
    "cordova-clipboard": "^1.1.1",
    "cordova-plugin-actionsheet": "^2.3.3",
    "cordova-plugin-app-version": "^0.1.9",
    "cordova-plugin-camera": "^2.4.1",
    "cordova-plugin-compat": "^1.2.0",
    "cordova-plugin-device": "^1.1.7",
    "cordova-plugin-dialogs": "^1.3.4",
    "cordova-plugin-facebook4": "^1.9.1",
    "cordova-plugin-file": "^5.0.0",
    "cordova-plugin-file-transfer": "^1.7.0",
    "cordova-plugin-filechooser": "^1.0.1",
    "cordova-plugin-filepath": "^1.1.0",
    "cordova-plugin-firebase": "^0.1.24",
    "cordova-plugin-geolocation": "^2.4.3",
    "cordova-plugin-googlemaps": "^2.1.1",
    "cordova-plugin-googlemaps-sdk": "git+https://github.com/mapsplugin/cordova-plugin-googlemaps-sdk.git",
    "cordova-plugin-googleplus": "^5.1.1",
    "cordova-plugin-inappbrowser": "^1.7.2",
    "cordova-plugin-splashscreen": "^4.1.0",
    "cordova-plugin-statusbar": "^2.3.0",
    "cordova-plugin-vibration": "^2.1.6",
    "cordova-plugin-whitelist": "^1.3.3",
    "cordova-plugin-x-socialsharing": "^5.2.1",
    "cordova.plugins.diagnostic": "^3.7.2",
    "es6-promise-plugin": "^4.1.0",
    "firebase": "^4.5.0",
    "ionic-angular": "^3.7.1",
    "ionic-img-viewer": "2.7.0",
    "ionic-plugin-keyboard": "^2.2.1",
    "ionic2-rating": "^1.2.2",
    "ionicons": "3.0.0",
    "moment": "^2.19.2",
    "onesignal-cordova-plugin": "^2.2.4",
    "promise-polyfill": "6.1.0",
    "rxjs": "5.4.3",
    "sw-toolbox": "3.6.0",
    "uk.co.workingedge.phonegap.plugin.launchnavigator": "^4.1.0",
    "zone.js": "0.8.18"
  },
  "devDependencies": {
    "@ionic/app-scripts": "3.1.2",
    "typescript": "2.4.0"
  },
  "description": "An Ionic project",
  "cordova": {
    "plugins": {
      "cordova-plugin-x-socialsharing": {},
      "cordova-plugin-device": {},
      "cordova-plugin-splashscreen": {},
      "cordova-plugin-statusbar": {},
      "cordova-plugin-whitelist": {},
      "ionic-plugin-keyboard": {},
      "cordova-plugin-firebase": {},
      "call-number": {},
      "mx.ferreyra.callnumber": {},
      "cordova-plugin-vibration": {},
      "cordova-plugin-facebook4": {
        "APP_ID": "15196419",
        "APP_NAME": "FooBar"
      },
      "cordova-plugin-camera": {},
      "onesignal-cordova-plugin": {},
      "cordova-plugin-inappbrowser": {},
      "cordova-plugin-googleplus": {
        "REVERSED_CLIENT_ID": "com.googleusercontent.app"
      },
      "cordova.plugins.diagnostic": {},
      "cordova-plugin-filechooser": {},
      "cordova-plugin-filepath": {},
      "branch-cordova-sdk": {},
      "uk.co.workingedge.phonegap.plugin.launchnavigator": {},
      "cordova-clipboard": {},
      "cordova-plugin-app-version": {},
      "cordova-plugin-file-transfer": {},
      "cordova-plugin-googlemaps": {
        "API_KEY_FOR_ANDROID": "AIzaSyBYJVEVRyo7Az",
        "API_KEY_FOR_IOS": "AIzaSyCqe2DU",
        "LOCATION_WHEN_IN_USE_DESCRIPTION": "Show your location on the map",
        "LOCATION_ALWAYS_USAGE_DESCRIPTION": "Trace your location on the map"
      },
      "cordova-plugin-geolocation": {
        "GEOLOCATION_USAGE_DESCRIPTION": "To display to you the most close places based on your location"
      },
      "com.googlemaps.ios": {},
      "cordova-plugin-file": {}
    },
    "platforms": [
      "android"
    ]
  }
}


问:
ASP.Net Core register Controller at runtime
I am asking myself if it is possible to load a DLL with Controllers in it at runtime and use it.

The only solution I've found is to add an assembly via ApplicationPart on the StartUp:

```<code>var builder = services.AddMvc();
builder.AddApplicationPart(
    AssemblyLoadContext.Default.LoadFromAssemblyPath(
        @"PATH\ExternalControllers.dll"
));
</code>```

Do anyone know if it is possible to register Controller at any time, because the issue with that solution is, that you have to restart the WebService when you want to add another DLL with Controllers in it. It would be nice when you just can add them at any time and register them at any time in the application.

答:
This is possible now on .net core 2.0+

Please see code ActionDescriptorCollectionProvider.cs:

```<code>    public ActionDescriptorCollectionProvider(
        IEnumerable<IActionDescriptorProvider> actionDescriptorProviders,
        IEnumerable<IActionDescriptorChangeProvider> actionDescriptorChangeProviders)
    {
        _actionDescriptorProviders = actionDescriptorProviders
            .OrderBy(p => p.Order)
            .ToArray();

        _actionDescriptorChangeProviders = actionDescriptorChangeProviders.ToArray();

        ChangeToken.OnChange(
            GetCompositeChangeToken,
            UpdateCollection);
    }
</code>```

Step 1:Implement IActionDescriptorChangeProvider class:

```<code>public class MyActionDescriptorChangeProvider : IActionDescriptorChangeProvider
{
    public static MyActionDescriptorChangeProvider Instance { get; } = new MyActionDescriptorChangeProvider();

    public CancellationTokenSource TokenSource { get; private set; }

    public bool HasChanged { get; set; }

    public IChangeToken GetChangeToken()
    {
        TokenSource = new CancellationTokenSource();
        return new CancellationChangeToken(TokenSource.Token);
    }
}
</code>```

Step 2:AddSingleton on Startup.ConfigureServices():

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddSingleton<IActionDescriptorChangeProvider>(MyActionDescriptorChangeProvider.Instance);
    services.AddSingleton(MyActionDescriptorChangeProvider.Instance);
}
</code>```

Step 3: Register controller at runtime:

```<code>public class TestController : Controller
{
    private readonly ApplicationPartManager _partManager;
    private readonly IHostingEnvironment _hostingEnvironment;
    public TestController(
        ApplicationPartManager partManager,
        IHostingEnvironment env)
    {
        _partManager = partManager;
        _hostingEnvironment = env;
    }
    public IActionResult RegisterControllerAtRuntime()
    {
        string assemblyPath = @"PATH\ExternalControllers.dll";
        var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);
        if (assembly != null)
        {
            _partManager.ApplicationParts.Add(new AssemblyPart(assembly));
            // Notify change
            MyActionDescriptorChangeProvider.Instance.HasChanged = true;
            MyActionDescriptorChangeProvider.Instance.TokenSource.Cancel();
            return Content("1");
        }
        return Content("0");
    }
}
</code>```

Body:
I am asking myself if it is possible to load a DLL with Controllers in it at runtime and use it.

The only solution I've found is to add an assembly via ApplicationPart on the StartUp:

var builder = services.AddMvc();
builder.AddApplicationPart(
    AssemblyLoadContext.Default.LoadFromAssemblyPath(
        @"PATH\ExternalControllers.dll"
));

Do anyone know if it is possible to register Controller at any time, because the issue with that solution is, that you have to restart the WebService when you want to add another DLL with Controllers in it. It would be nice when you just can add them at any time and register them at any time in the application.

Body:
This is possible now on .net core 2.0+

Please see code ActionDescriptorCollectionProvider.cs:

    public ActionDescriptorCollectionProvider(
        IEnumerable<IActionDescriptorProvider> actionDescriptorProviders,
        IEnumerable<IActionDescriptorChangeProvider> actionDescriptorChangeProviders)
    {
        _actionDescriptorProviders = actionDescriptorProviders
            .OrderBy(p => p.Order)
            .ToArray();

        _actionDescriptorChangeProviders = actionDescriptorChangeProviders.ToArray();

        ChangeToken.OnChange(
            GetCompositeChangeToken,
            UpdateCollection);
    }

Step 1:Implement IActionDescriptorChangeProvider class:

public class MyActionDescriptorChangeProvider : IActionDescriptorChangeProvider
{
    public static MyActionDescriptorChangeProvider Instance { get; } = new MyActionDescriptorChangeProvider();

    public CancellationTokenSource TokenSource { get; private set; }

    public bool HasChanged { get; set; }

    public IChangeToken GetChangeToken()
    {
        TokenSource = new CancellationTokenSource();
        return new CancellationChangeToken(TokenSource.Token);
    }
}

Step 2:AddSingleton on Startup.ConfigureServices():

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddSingleton<IActionDescriptorChangeProvider>(MyActionDescriptorChangeProvider.Instance);
    services.AddSingleton(MyActionDescriptorChangeProvider.Instance);
}

Step 3: Register controller at runtime:

public class TestController : Controller
{
    private readonly ApplicationPartManager _partManager;
    private readonly IHostingEnvironment _hostingEnvironment;
    public TestController(
        ApplicationPartManager partManager,
        IHostingEnvironment env)
    {
        _partManager = partManager;
        _hostingEnvironment = env;
    }
    public IActionResult RegisterControllerAtRuntime()
    {
        string assemblyPath = @"PATH\ExternalControllers.dll";
        var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);
        if (assembly != null)
        {
            _partManager.ApplicationParts.Add(new AssemblyPart(assembly));
            // Notify change
            MyActionDescriptorChangeProvider.Instance.HasChanged = true;
            MyActionDescriptorChangeProvider.Instance.TokenSource.Cancel();
            return Content("1");
        }
        return Content("0");
    }
}


问:
instanceof function parameter returns false in Typescript/Angular
I'm trying to find out how to get the type of an Object if it was passed as a parameter in my function.

For example you have following code

```<code>getTypeOfAnimal(animal){
   console.log(animal instanceof Cat)
   console.log(animal instanceof Bear)
}
</code>```

animal could be either an instanceof a Cat or a Bear. The animal passed in from my form always returns false (also if the Object's structure seems to match one of a Cat or a Bear).

Is there a way to get the type properly?

答:
If you are dealing with classes in a hierarchy, you can use instanceof:

```<code>class Animal {
    name: string;
}

class Cat extends Animal {
    purrs: boolean;
}

class Bear extends Animal {
    growls: boolean;
}

const animal = new Cat();
console.log(animal instanceof Cat); // true
console.log(animal instanceof Bear); // false
</code>```

When dealing with structural types that you want to narrow, you can use a custom type guard:

```<code>const structuralBear = {
    name: 'Paddington',
    growls: false
};

console.log(structuralBear instanceof Cat); // false
console.log(structuralBear instanceof Bear); // false

function isBeary(obj: any): obj is Bear {
    console.log(typeof obj.growls);
    return (typeof obj.name === 'string' && typeof obj.growls === 'boolean');
}

console.log(isBeary(structuralBear));
</code>```

This works out if something is "beary" enough for your needs...

On the whole, though, beware of needing to know too much about types in this way. The main use case is to narrow a union type.

Body:
I'm trying to find out how to get the type of an Object if it was passed as a parameter in my function.

For example you have following code

getTypeOfAnimal(animal){
   console.log(animal instanceof Cat)
   console.log(animal instanceof Bear)
}

animal could be either an instanceof a Cat or a Bear. The animal passed in from my form always returns false (also if the Object's structure seems to match one of a Cat or a Bear).

Is there a way to get the type properly?

Body:
If you are dealing with classes in a hierarchy, you can use instanceof:

class Animal {
    name: string;
}

class Cat extends Animal {
    purrs: boolean;
}

class Bear extends Animal {
    growls: boolean;
}

const animal = new Cat();
console.log(animal instanceof Cat); // true
console.log(animal instanceof Bear); // false

When dealing with structural types that you want to narrow, you can use a custom type guard:

const structuralBear = {
    name: 'Paddington',
    growls: false
};

console.log(structuralBear instanceof Cat); // false
console.log(structuralBear instanceof Bear); // false

function isBeary(obj: any): obj is Bear {
    console.log(typeof obj.growls);
    return (typeof obj.name === 'string' && typeof obj.growls === 'boolean');
}

console.log(isBeary(structuralBear));

This works out if something is "beary" enough for your needs...

On the whole, though, beware of needing to know too much about types in this way. The main use case is to narrow a union type.