问:
Python 3.8.1: ModuleNotFoundError: No module named '_pywrap_tensorflow_internal' - Is tensorflow only supported up to 3.7?
I am using Python 3.8.1 on Windows 10 and am trying to install TensorFlow.

I have tried many methods to install it, but I keep getting the following error upon importing TensorFlow. This time, I installed it using

```<code>conda install -c conda-forge tensorflow
</code>```

Here is the stack trace:

```<code>Using TensorFlow backend.
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
    fp, pathname, description = imp.find_module('_pywrap_tensorflow_internal', [dirname(__file__)])
  File "C:\Program Files (x86)\Python38-32\lib\imp.py", line 296, in find_module
    raise ImportError(_ERR_MSG.format(name), name=name)
ImportError: No module named '_pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
    import _pywrap_tensorflow_internal
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "deep_versions.py", line 6, in <module>
    import keras
  File "C:\Users\rapto\AppData\Roaming\Python\Python38\site-packages\keras\__init__.py", line 3, in <module>
    from . import utils
  File "C:\Users\rapto\AppData\Roaming\Python\Python38\site-packages\keras\utils\__init__.py", line 6, in <module>
    from . import conv_utils
  File "C:\Users\rapto\AppData\Roaming\Python\Python38\site-packages\keras\utils\conv_utils.py", line 9, in <module>
    from .. import backend as K
  File "C:\Users\rapto\AppData\Roaming\Python\Python38\site-packages\keras\backend\__init__.py", line 1, in <module>
    from .load_backend import epsilon
  File "C:\Users\rapto\AppData\Roaming\Python\Python38\site-packages\keras\backend\load_backend.py", line 90, in <module>
    from .tensorflow_backend import *
  File "C:\Users\rapto\AppData\Roaming\Python\Python38\site-packages\keras\backend\tensorflow_backend.py", line 5, in <module>
    import tensorflow as tf
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
    fp, pathname, description = imp.find_module('_pywrap_tensorflow_internal', [dirname(__file__)])
  File "C:\Program Files (x86)\Python38-32\lib\imp.py", line 296, in find_module
    raise ImportError(_ERR_MSG.format(name), name=name)
ImportError: No module named '_pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
    import _pywrap_tensorflow_internal
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
</code>```

What I have done to try to fix it: I have looked at other similar questions on here but they have been for older versions of Python. I have also looked at this GitHub post but could not resolve the issue.

I checked the TensorFlow site for Python version compatability but the latest update that I could find was a few months ago, saying that TensorFlow only supports up to Python 3.7 (https://github.com/tensorflow/tensorflow/issues/33374) Is this still the case and do I need to downgrade Python in order to use TensorFlow?

Please let me know if there is any more information I should provide (I'm still learning how to correctly ask questions here). Thank you.

Edit: I created a conda environment with Python 3.7 and I did not get the same error and importing TF seems to be working fine now. It seems that Python 3.8 is still not yet supported, so this may have been the problem.

答: Per the installation documents, only Python 3.5-3.7 are supported. https://www.tensorflow.org/install</p>

Body:
I am using Python 3.8.1 on Windows 10 and am trying to install TensorFlow.

I have tried many methods to install it, but I keep getting the following error upon importing TensorFlow. This time, I installed it using

conda install -c conda-forge tensorflow

Here is the stack trace:

Using TensorFlow backend.
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
    fp, pathname, description = imp.find_module('_pywrap_tensorflow_internal', [dirname(__file__)])
  File "C:\Program Files (x86)\Python38-32\lib\imp.py", line 296, in find_module
    raise ImportError(_ERR_MSG.format(name), name=name)
ImportError: No module named '_pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
    import _pywrap_tensorflow_internal
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "deep_versions.py", line 6, in <module>
    import keras
  File "C:\Users\rapto\AppData\Roaming\Python\Python38\site-packages\keras\__init__.py", line 3, in <module>
    from . import utils
  File "C:\Users\rapto\AppData\Roaming\Python\Python38\site-packages\keras\utils\__init__.py", line 6, in <module>
    from . import conv_utils
  File "C:\Users\rapto\AppData\Roaming\Python\Python38\site-packages\keras\utils\conv_utils.py", line 9, in <module>
    from .. import backend as K
  File "C:\Users\rapto\AppData\Roaming\Python\Python38\site-packages\keras\backend\__init__.py", line 1, in <module>
    from .load_backend import epsilon
  File "C:\Users\rapto\AppData\Roaming\Python\Python38\site-packages\keras\backend\load_backend.py", line 90, in <module>
    from .tensorflow_backend import *
  File "C:\Users\rapto\AppData\Roaming\Python\Python38\site-packages\keras\backend\tensorflow_backend.py", line 5, in <module>
    import tensorflow as tf
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
    fp, pathname, description = imp.find_module('_pywrap_tensorflow_internal', [dirname(__file__)])
  File "C:\Program Files (x86)\Python38-32\lib\imp.py", line 296, in find_module
    raise ImportError(_ERR_MSG.format(name), name=name)
ImportError: No module named '_pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
    import _pywrap_tensorflow_internal
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

What I have done to try to fix it: I have looked at other similar questions on here but they have been for older versions of Python. I have also looked at this GitHub post but could not resolve the issue.

I checked the TensorFlow site for Python version compatability but the latest update that I could find was a few months ago, saying that TensorFlow only supports up to Python 3.7 (https://github.com/tensorflow/tensorflow/issues/33374) Is this still the case and do I need to downgrade Python in order to use TensorFlow?

Please let me know if there is any more information I should provide (I'm still learning how to correctly ask questions here). Thank you.

Edit: I created a conda environment with Python 3.7 and I did not get the same error and importing TF seems to be working fine now. It seems that Python 3.8 is still not yet supported, so this may have been the problem.


来源: stackexchange

问:
ORM SQLAlchemy: how to build a select/where query from a list/dict with hundreds of elements
I have two tables: "user" which is a list of users of the website and "post" which is a list of all the users' posts.
Any user follows different users, like Twitter.
Any 'user' object holds a 'following' dict attribute containing a list of id.
Any 'post' object holds a 'user_id' label containing a id user.

I want to obtain a query that, from the table 'Post', collect all the posts with 'user_id'  matching the id's contained in the dict.

But such a query, translated straight,  would result in a SELECT  with  hundreds of  WHERE id= 1 AND id=2 etc in a row.  Is there a better way?

答:
It is not clear how your following dict attribute is persisted. If it were stored in a separate N-1 table Follows, assuming your db schema looks like:

```<code>User(UserID, ...)
Post(PostID, UserID, ...)
Follows(UserID, FollowsUserID, ...)
</code>```

the SQL query to retrieve the data you want would be:

```<code>SELECT  u.UserID,
        p.*
FROM    User u
JOIN    Follows f
    ON  u.UserID = f.UserID
JOIN    Post p
    ON  f.FollowsUserID = p.UserID
</code>```

Assuming the objects and relations are configured, the SA query to do the same job would like similar to:

```<code>u = ... # get desired User object
qry = (session.query(Post).
        join(User). # User will join to Post properly
        join(Follows, Follows.FollowsUserID == User.UserID). # specify the join condition
        filter(Follows.User == u)
      )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It is not clear how your following dict attribute is persisted. If it were stored in a separate N-1 table Follows, assuming your db schema looks like:

User(UserID, ...)
Post(PostID, UserID, ...)
Follows(UserID, FollowsUserID, ...)

the SQL query to retrieve the data you want would be:

SELECT  u.UserID,
        p.*
FROM    User u
JOIN    Follows f
    ON  u.UserID = f.UserID
JOIN    Post p
    ON  f.FollowsUserID = p.UserID

Assuming the objects and relations are configured, the SA query to do the same job would like similar to:

u = ... # get desired User object
qry = (session.query(Post).
        join(User). # User will join to Post properly
        join(Follows, Follows.FollowsUserID == User.UserID). # specify the join condition
        filter(Follows.User == u)
      )


问:
I want to group list of list
The structure of class along with sample data here.

```<code>class Student
{
    public Int32 Id { get; set; }

    public string Name { get; set; }

    public Int32 Age { get; set; }

    public List<string> subjects { get; set; }

}

class Program
{
    static void Main( string[] )
    {
        List<Student> students = new List<Student>()
        {
           new Student(){ Id=1 ,Name="Pratik", Age=24, subjects=new List<string>(){"s1", "s2"}},
           new Student(){ Id=2, Name="Ashish", Age=28, subjects=new List<string>{"s1", "s4"}},
           new Student(){ Id=3, Name="Umesh", Age=24, subjects=new List<string>(){"s1" }},
           new Student(){ Id=4, Name="Ajay", Age=28, subjects=new List<string>(){"s5", "s1"}},
           new Student(){ Id=5, Name="Vijay", Age=24, subjects=new List<string>(){"s1"}},
           new Student(){ Id=6, Name="Shital", Age=24, subjects=new List<string>(){"s2", "s3"}}
        };

        ...
    }
</code>```

I want to group subjects on Names for ex.

```<code>s2 Pratik, Shital
</code>```

答:
Demo on dotnet fiddle

Using SelectMany to get list of list item with format like { Name, Subject }

Using GroupBy to group Subject and Using Join to get list of Names seperated by comma.

```<code>var data = students.SelectMany(p => p.subjects.Select(s => new { p.Name, Subject = s  }));
var result = data.GroupBy(p => p.Subject)
                .Select(g => new
                {
                    g.Key,
                    Names = string.Join(",", g.Select(n => n.Name))
                });
</code>```

Output

```<code>s1 Pratik,Ashish,Umesh,Ajay,Vijay
s2 Pratik,Shital
s4 Ashish
s5 Ajay
s3 Shital
</code>```

ContentLicense: CC BY-SA 4.0

Title: I want to group list of list

Body:
The structure of class along with sample data here.

class Student
{
    public Int32 Id { get; set; }

    public string Name { get; set; }

    public Int32 Age { get; set; }

    public List<string> subjects { get; set; }

}

class Program
{
    static void Main( string[] )
    {
        List<Student> students = new List<Student>()
        {
           new Student(){ Id=1 ,Name="Pratik", Age=24, subjects=new List<string>(){"s1", "s2"}},
           new Student(){ Id=2, Name="Ashish", Age=28, subjects=new List<string>{"s1", "s4"}},
           new Student(){ Id=3, Name="Umesh", Age=24, subjects=new List<string>(){"s1" }},
           new Student(){ Id=4, Name="Ajay", Age=28, subjects=new List<string>(){"s5", "s1"}},
           new Student(){ Id=5, Name="Vijay", Age=24, subjects=new List<string>(){"s1"}},
           new Student(){ Id=6, Name="Shital", Age=24, subjects=new List<string>(){"s2", "s3"}}
        };

        ...
    }

I want to group subjects on Names for ex.

s2 Pratik, Shital

Body:
Demo on dotnet fiddle

Using SelectMany to get list of list item with format like { Name, Subject }

Using GroupBy to group Subject and Using Join to get list of Names seperated by comma.

var data = students.SelectMany(p => p.subjects.Select(s => new { p.Name, Subject = s  }));
var result = data.GroupBy(p => p.Subject)
                .Select(g => new
                {
                    g.Key,
                    Names = string.Join(",", g.Select(n => n.Name))
                });

Output

s1 Pratik,Ashish,Umesh,Ajay,Vijay
s2 Pratik,Shital
s4 Ashish
s5 Ajay
s3 Shital


问:
Excel VBA AutoFilter Error 1004
When I record the macro I get the following:

```<code>Range("A2:Z74").AutoFilter
ActiveSheet.Range("$A$2:$Z$74").AutoFilter Field:=2, Criteria1:="<>"
</code>```

But when I run this macro, I get error

```<code>1004 This can't be applied to the selected range. Select a single cell in a range and try again.Select a single cell in a range and try again.
</code>```

Any idea how to fix this?

答:
Just in case I can help people in the future,

I had the same error occur when the range I selected was empty. After I corrected the range to cover cells with drop-downs in them the error stopped occurring.

Title: Excel VBA AutoFilter Error 1004

Body:
When I record the macro I get the following:

Range("A2:Z74").AutoFilter
ActiveSheet.Range("$A$2:$Z$74").AutoFilter Field:=2, Criteria1:="<>"

But when I run this macro, I get error

1004 This can't be applied to the selected range. Select a single cell in a range and try again.Select a single cell in a range and try again.

Any idea how to fix this?


问:
Return an array element inside a nested array
I've got one that I'm not getting too much traction on, Ive got everything working correctly except one element. Essentially I want to filter a return of "ev3_4" in the code. I'm not sure of the correct function. I'm pulling from an external source to get the data. and the info is inside a nested array of the array that I have been able to correctly return.

```<code><template>

<!-- the array for the ev data -->
    <div id="ev-deck" class="content">
      <div id="text-box-ev" class="field">
        <div class="control">
<!-- To change the number of events shown change the value for X in v-for="item in infodata.slice(0, X), this is the limiter for how many will loop before it stops -->
          <div class="card-content has-background-dark has-text-light" id="ev-card" v-for="item in p3data.slice(0, 2)" :key="item.infodata">
<!-- Every row is a separate line in the event element and its position is manipulated by the column css -->
            <div class="row">
              <div id="ev-title" class="column">  <b>ev1:</b> {{ item.ev1 (firstname) }}</div>
              <div id="ev-title" class="column"><b>ev2:</b> {{ item.ev2 (lastname)}}</div>
              <div id="ev-title" class="column"><b>ev3:</b> {{ item.ev3_4 (city)}}</div>
            </div>
            <div class="row">
              <div id="ev-title" class="column"><b>ev4:</b> {{ item.ev4 }}</div>
              <div id="ev-title" class="column"><b>ev5:</b> {{ item.ev5 }}</div>
            </div>
            <div class="row">
              <div id="ev-title" class="column-centered"><b>ev6:</b> {{ item.ev6 }}</div>
            </div>
            <div class="row">
              <div id="ev-title" class="column-centered"><b>ev7:</b> {{ item.ev7 }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

</template>
</code>```
```<code><script>

    export default {
 name: 'ev',
    }
    data() {
    return {
      infodata: [],
    },
// I know this is wrong and need help making this logic correct

     item.ev3.filter(data => {
      return data.ev3 === item.ev3_4
     })
  },

  created() {
    var info = 'some url'

    axios.get(info)
      .then( response => {
      this.infodata = response.data;

        console.log(response.data);
      })
  },

  </script>
</code>```

Here is an example of the the array its pulling

(infodata Array)

```<code>0:
  ev1 (first name):   joe
  ev2 (lastname):     blow
  ev3 (address):
      0:
          ev3_1 (street number):  1234
          ev3_2 (street name):    main
          ev3_3 (zip code):       12345
          ev3_4 (city):           tempe
</code>```

答:
Thanks for updating your question. Glad to hear you found a solution to access the data you needed.

Based on your edit, I think there are still some things worth noting. The data you are referring to is actually stored in an object rather than an array (though it does contain an array).

An array has the structure:

```<code>data = ["val1", "val2", "val3"]
</code>```

And the data is accessed by index.

```<code>data[0] -> "val1"
data[1] -> "val2"
data[data.length - 1] -> "val3"

ev3[0]
</code>```

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Objects, on the other hand, contain properties consisting of key-value pairs. And have the following structure:

```<code>data: {
  val1: "first",
  val2: "second",
  val3: {
    a: "third a",
    b: "third b",
    c: "third c"
  }
}
</code>```

Object values are accessed using the key.

```<code>data.val1 -> "first"
data.val3.b -> "third b"
</code>```

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

Given the solution that worked for you,

```<code>item.ev3[0].ev3_4
</code>```

Your data is stored as an object (item) with a property (ev3) that contains an array whose first index ([0]) is an object that has a property (ev3_4).

Your edit to your question definitely helps to clarify the structure of your data.

```<code>0:
  ev1 (first name):   joe
  ev2 (lastname):     blow
  ev3 (address):
    0:
      ev3_1 (street number):  1234
      ev3_2 (street name):    main
      ev3_3 (zip code):       12345
      ev3_4 (city):           tempe
</code>```

But there are still some adjustments that you could make that would greatly improve your ability to work with and follow your data. And might help further clarify the concepts.

First, I would highly recommend using clear names for your object keys. What you have included in brackets is perfect, just use camel case to eliminate spaces.
This will make things much easier for you when writing code to accesses data (item.address.city as opposed to using names like ev3 and ev3_4), and will also help make your code more readable for others trying to follow your code.

Second, you are storing your address data (ev3[0]) as an object, inside of an array (hence the [0]).
From what you have shown, you are only using the first index of the array ([0]).
If this is the case you can just store the address object directly inside ev3, which will eliminate the need for you to specify [0] when you access the data.

```<code>person: {
   firstName: "Joe",
   lastName: "Blow",
   address: {
      streetNumber: "1234"
      streetName: "Main Street",
      zipCode: "90210",
      city: "Fakesville"
   },
   phone: "1(222)333-4444"
}
</code>```

Now you are able to access the same data you were looking to with the following:

```<code>person.address.city
</code>```

And if you have additional people to store, that could/should be done inside an array, where they can then be accessed by their index or in a loop.

```<code>people = [
  {
    firstName: "Joe",
    lastName: "Blow",
    address: {
      streetNumber: "1234"
      streetName: "Main Street",
      zipCode: "90210",
      city: "Fakesville"
    },
    phone: "1(222)333-4444"
  },{
    firstName: "Rick",
    lastName: "Sanchez",
    address: {
      streetNumber: "132"
      streetName: "Cool Avenue",
      zipCode: "98101",
      city: "Seattle"
    },
    phone: "1(222)333-4444"
  }
]

people[1].address.city -> "Seattle"
people[0].firstName -> "Joe"
</code>```

Body:
I've got one that I'm not getting too much traction on, Ive got everything working correctly except one element. Essentially I want to filter a return of "ev3_4" in the code. I'm not sure of the correct function. I'm pulling from an external source to get the data. and the info is inside a nested array of the array that I have been able to correctly return.

<template>

  ev1: {{ item.ev1 (firstname) }}

ev2: {{ item.ev2 (lastname)}}

ev3: {{ item.ev3_4 (city)}}

ev4: {{ item.ev4 }}

ev5: {{ item.ev5 }}

ev6: {{ item.ev6 }}

ev7: {{ item.ev7 }}

</template>

Here is an example of the the array its pulling

(infodata Array)

0:
  ev1 (first name):   joe
  ev2 (lastname):     blow
  ev3 (address):
      0:
          ev3_1 (street number):  1234
          ev3_2 (street name):    main
          ev3_3 (zip code):       12345
          ev3_4 (city):           tempe

Body:
Thanks for updating your question. Glad to hear you found a solution to access the data you needed.

Based on your edit, I think there are still some things worth noting. The data you are referring to is actually stored in an object rather than an array (though it does contain an array).

An array has the structure:

data = ["val1", "val2", "val3"]

And the data is accessed by index.

data[0] -> "val1"
data[1] -> "val2"
data[data.length - 1] -> "val3"

ev3[0]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Objects, on the other hand, contain properties consisting of key-value pairs. And have the following structure:

data: {
  val1: "first",
  val2: "second",
  val3: {
    a: "third a",
    b: "third b",
    c: "third c"
  }
}

Object values are accessed using the key.

data.val1 -> "first"
data.val3.b -> "third b"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

Given the solution that worked for you,

item.ev3[0].ev3_4

Your data is stored as an object (item) with a property (ev3) that contains an array whose first index ([0]) is an object that has a property (ev3_4).

Your edit to your question definitely helps to clarify the structure of your data.

0:
  ev1 (first name):   joe
  ev2 (lastname):     blow
  ev3 (address):
    0:
      ev3_1 (street number):  1234
      ev3_2 (street name):    main
      ev3_3 (zip code):       12345
      ev3_4 (city):           tempe

But there are still some adjustments that you could make that would greatly improve your ability to work with and follow your data. And might help further clarify the concepts.

First, I would highly recommend using clear names for your object keys. What you have included in brackets is perfect, just use camel case to eliminate spaces.
This will make things much easier for you when writing code to accesses data (item.address.city as opposed to using names like ev3 and ev3_4), and will also help make your code more readable for others trying to follow your code.

Second, you are storing your address data (ev3[0]) as an object, inside of an array (hence the [0]).
From what you have shown, you are only using the first index of the array ([0]).
If this is the case you can just store the address object directly inside ev3, which will eliminate the need for you to specify [0] when you access the data.

person: {
   firstName: "Joe",
   lastName: "Blow",
   address: {
      streetNumber: "1234"
      streetName: "Main Street",
      zipCode: "90210",
      city: "Fakesville"
   },
   phone: "1(222)333-4444"
}

Now you are able to access the same data you were looking to with the following:

person.address.city

And if you have additional people to store, that could/should be done inside an array, where they can then be accessed by their index or in a loop.

people = [
  {
    firstName: "Joe",
    lastName: "Blow",
    address: {
      streetNumber: "1234"
      streetName: "Main Street",
      zipCode: "90210",
      city: "Fakesville"
    },
    phone: "1(222)333-4444"
  },{
    firstName: "Rick",
    lastName: "Sanchez",
    address: {
      streetNumber: "132"
      streetName: "Cool Avenue",
      zipCode: "98101",
      city: "Seattle"
    },
    phone: "1(222)333-4444"
  }
]

people[1].address.city -> "Seattle"
people[0].firstName -> "Joe"


问:
Finding frequency of range of numbers in Mathematica
Given a list of numbers in Mathematica, how would I extract from that list the total number of numbers between numbers a and b that I specify?

答:
Please look into BinCount:

```<code>In[176]:= BinCounts[Range[30], {{2, 11/2}}]

Out[176]= {4}
</code>```

Compare with direct count:

```<code>In[177]:= Count[Range[30], x_ /; 2 <= x < 11/2]

Out[177]= 4
</code>```

Body:
Please look into BinCount:

In[176]:= BinCounts[Range[30], {{2, 11/2}}]

Out[176]= {4}

Compare with direct count:

In[177]:= Count[Range[30], x_ /; 2 <= x < 11/2]

Out[177]= 4


问:
Integrating a boolean into an array parameter
I need to create an array of random numbers using user inputted parameters(size, highest random number, lowest random number) and also include a  boolean that dictates weather the highest number will be included in the random numbers or not. The boolean is whats causing me runtime errors. I cant figure out whats going wrong. i've tried if statements as well as switch statements but i dont think the problem is there. If you guys could help me id really appreciate it. I come here for many questions but this is my first time posting so sorry if my etiquette is wrong. here is my code thus far:

```<code>import  java.util.*;

public class Question1 {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    boolean yesNo = false;
    String yesOrNo;
    int highest;

    System.out.print("Please enter array size: ");
    int size = scan.nextInt();

    System.out.print("Please enter highest number: ");
    int high = scan.nextInt();

    System.out.print("Please enter lowest number: ");
    int low = scan.nextInt();

    System.out.print("Would you like to include " + high +" into the list of random numbers(Yes or No)?");
    yesOrNo = scan.nextLine();

    switch (yesOrNo.toUpperCase()) {
    case "YES":
        yesNo = true;
        break;
    }
    if (yesNo==true)
        high=high+1;

    randomNumberGenerator(size,high,low);
    }

public static void randomNumberGenerator(int size, int high, int low) {
    int[] randomNums = new int [size];
    for(int count = 0; count<randomNums.length; count++) {
        Random generator = new Random();
        int num = generator.nextInt(high) + (low);
        randomNums[count] = num;
    }
    System.out.print(Arrays.toString(randomNums));
 }
 }
</code>```

```<code>Please enter array size: 10
Please enter highest number: 5
Please enter lowest number: 0
Would you like to incloud 5 into the list of random numbers(Yes or No)?[0, 0, 2, 1, 2, 4, 3, 3, 0, 2]
-----------------------------------------------------------

it seems like the array is skipping over the boolean section of my code and im not sure why.
</code>```

答: write "scan.nextLine();" after "YesOrNo = scan.nextLine" and it will show u the yes/no line</p>

Body:
I need to create an array of random numbers using user inputted parameters(size, highest random number, lowest random number) and also include a  boolean that dictates weather the highest number will be included in the random numbers or not. The boolean is whats causing me runtime errors. I cant figure out whats going wrong. i've tried if statements as well as switch statements but i dont think the problem is there. If you guys could help me id really appreciate it. I come here for many questions but this is my first time posting so sorry if my etiquette is wrong. here is my code thus far:

import  java.util.*;

public class Question1 {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    boolean yesNo = false;
    String yesOrNo;
    int highest;

    System.out.print("Please enter array size: ");
    int size = scan.nextInt();

    System.out.print("Please enter highest number: ");
    int high = scan.nextInt();

    System.out.print("Please enter lowest number: ");
    int low = scan.nextInt();

    System.out.print("Would you like to include " + high +" into the list of random numbers(Yes or No)?");
    yesOrNo = scan.nextLine();

    switch (yesOrNo.toUpperCase()) {
    case "YES":
        yesNo = true;
        break;
    }
    if (yesNo==true)
        high=high+1;

    randomNumberGenerator(size,high,low);
    }

public static void randomNumberGenerator(int size, int high, int low) {
    int[] randomNums = new int [size];
    for(int count = 0; count<randomNums.length; count++) {
        Random generator = new Random();
        int num = generator.nextInt(high) + (low);
        randomNums[count] = num;
    }
    System.out.print(Arrays.toString(randomNums));
 }
 }

Please enter array size: 10
Please enter highest number: 5
Please enter lowest number: 0
Would you like to incloud 5 into the list of random numbers(Yes or No)?[0, 0, 2, 1, 2, 4, 3, 3, 0, 2]
-----------------------------------------------------------

it seems like the array is skipping over the boolean section of my code and im not sure why.


问:
GCP service account - access denied for NodeJS script
Hello I am getting desperate.

I am trying to import data into Google BigQuery, using Cron and NodeJS script. But I am getting access denied error:

```<code>Access Denied: Dataset arcane-pillar-XXX:MyProj: User does not have bigquery.datasets.get permission for dataset arcane-pillar-XXX:MyProj
</code>```

I've created a service account bq-data-import-user@arcane-pillar-XXX.iam.gserviceaccount.com

I've created a key, downloaded it as a JSON file and set the environment variable

When I run my NodeJS script on my local machine I get the error.

I've tested the account with Policy Troubleshooter. The Troubleshooter says that the permission is granted.

I've tried to recreate the account many times but nothing have helped. I've verified that there is no project mismatch, because the error changes when I delete the dataset.

Any tips?

```<code>#!/usr/bin/env node
"use strict";

const {BigQuery} = require('@google-cloud/bigquery');

process.env["GOOGLE_APPLICATION_CREDENTIALS"] = "/etc/my-app/google-application-credentials.json";

const bq = new BigQuery();
const bqDataset = (await bq.dataset("TheDataset").get({ autoCreate: true }))[0]; // THIS LINE THROWS THE ERROR
const bqTable = (await bqDataset.table("TheTable").get({ autoCreate: true, schema: [ /* The BQ schema */ ] }))[0];

for await (const row of rows) { // Rows is a async generator (cursor in MySQL)
    await bqTable.insert(row);
}
</code>```

答:
This is our public article shows the recommended way to authenticate to a Cloud API.

Based on our public document, create credentials in your application from the service account file. Then use the credentials to create a service object with the BigQuery Client Libraries.

```<code>// Create a BigQuery client explicitly using service account credentials.
// by specifying the private key file.

const {BigQuery} = require('@google-cloud/bigquery');

const options = {
  keyFilename: 'path/to/service_account.json',
  projectId: 'my_project',
};

const bigquery = new BigQuery(options);
</code>```

Body:
Hello I am getting desperate.

I am trying to import data into Google BigQuery, using Cron and NodeJS script. But I am getting access denied error:

Access Denied: Dataset arcane-pillar-XXX:MyProj: User does not have bigquery.datasets.get permission for dataset arcane-pillar-XXX:MyProj

I've created a service account bq-data-import-user@arcane-pillar-XXX.iam.gserviceaccount.com

I've created a key, downloaded it as a JSON file and set the environment variable

When I run my NodeJS script on my local machine I get the error.

I've tested the account with Policy Troubleshooter. The Troubleshooter says that the permission is granted.

I've tried to recreate the account many times but nothing have helped. I've verified that there is no project mismatch, because the error changes when I delete the dataset.

Any tips?

#!/usr/bin/env node
"use strict";

const {BigQuery} = require('@google-cloud/bigquery');

process.env["GOOGLE_APPLICATION_CREDENTIALS"] = "/etc/my-app/google-application-credentials.json";

const bq = new BigQuery();
const bqDataset = (await bq.dataset("TheDataset").get({ autoCreate: true }))[0]; // THIS LINE THROWS THE ERROR
const bqTable = (await bqDataset.table("TheTable").get({ autoCreate: true, schema: [ /* The BQ schema */ ] }))[0];

for await (const row of rows) { // Rows is a async generator (cursor in MySQL)
    await bqTable.insert(row);
}

Body:
This is our public article shows the recommended way to authenticate to a Cloud API.

Based on our public document, create credentials in your application from the service account file. Then use the credentials to create a service object with the BigQuery Client Libraries.

// Create a BigQuery client explicitly using service account credentials.
// by specifying the private key file.

const {BigQuery} = require('@google-cloud/bigquery');

const options = {
  keyFilename: 'path/to/service_account.json',
  projectId: 'my_project',
};

const bigquery = new BigQuery(options);


问:
service to perform scheduled task operation
Is it possible to create a Windows Scheduled Task from a Windows batch file with another batchfile as a parameter:

```<code>For eg : schtasks.exe /create /tn "taskName" /tr "%Home%\bin\bootstrap.cmd" /sc DAILY /st 00:01:00 /ri 1 /du 0023:59 %schTaskAccountArgs%"
</code>```

Background

The batch file 'bootstrap.cmd' in the script above has calls to other batchfiles and eventually an exe. It creates a scheduled task in the Microsoft console which triggers the same exe, but in my case due to a GPO policy, the scheduled task couldn't be created (policy being-not able to store passwords for the user that runs the scheduled job). As a workaround I want to create a service in the same Batch file by replacing the above by:

```<code>sc create "service for taskName" start= demand displayname= "service for taskName" binpath= "%Home%\bin\bootstrap.cmd"
</code>```

is it a feasible method to create a service for this scenario.

答:
Windows appears to not run .bat (and .cmd) files as services.

Here are some alternatives:

Create a scheduled task that runs at
startup.

Convert the .cmd into an executable. See How can a .bat
file be 'converted' to .exe without third party tools?

Use external tools (like NSSM featured here)

Body:
Is it possible to create a Windows Scheduled Task from a Windows batch file with another batchfile as a parameter:

For eg : schtasks.exe /create /tn "taskName" /tr "%Home%\bin\bootstrap.cmd" /sc DAILY /st 00:01:00 /ri 1 /du 0023:59 %schTaskAccountArgs%"

Background

The batch file 'bootstrap.cmd' in the script above has calls to other batchfiles and eventually an exe. It creates a scheduled task in the Microsoft console which triggers the same exe, but in my case due to a GPO policy, the scheduled task couldn't be created (policy being-not able to store passwords for the user that runs the scheduled job). As a workaround I want to create a service in the same Batch file by replacing the above by:

sc create "service for taskName" start= demand displayname= "service for taskName" binpath= "%Home%\bin\bootstrap.cmd"

is it a feasible method to create a service for this scenario.


问:
Await socket.on('answerToRequest') possible with Socket.io?
Is the following somehow possible?</p>

```<code>async function doesSocketAgree(){
    socket.emit('doesOtherSocketAgree', otherSocketId);
    await socket.on('responseDoesSocketAgree', (answer)=>{
      console.log('answer');
});
}
</code>```

答:
In socket.io you can use "acknowledgements" callbacks:

async function doesSocketAgree(){
  await new Promise(resolve => {
    socket.emit('doesOtherSocketAgree', otherSocketId, (answer) => {
      resolve(answer);
    });
  });
}```

https://socket.io/docs/#Sending-and-getting-data-acknowledgements

So you can use a single emit() and can trigger a callback.
That has the advantage you dont have to deal with memory leaks from register an event listener every time you call this function.

Body:
Is the following somehow possible?

async function doesSocketAgree(){
    socket.emit('doesOtherSocketAgree', otherSocketId);
    await socket.on('responseDoesSocketAgree', (answer)=>{
      console.log('answer');
});
}

Body:
In socket.io you can use "acknowledgements" callbacks:

async function doesSocketAgree(){
  await new Promise(resolve => {
    socket.emit('doesOtherSocketAgree', otherSocketId, (answer) => {
      resolve(answer);
    });
  });
}

https://socket.io/docs/#Sending-and-getting-data-acknowledgements

So you can use a single emit() and can trigger a callback.
That has the advantage you dont have to deal with memory leaks from register an event listener every time you call this function.


问:
How to break div id text after n number of characters in PHP
I trying to break long text.

The text look like this: Inquire about space/Enter Library. The text is currently separated using the slash. So we can use the / to tell the code where to break though I don't mind using character count to break the text (preferable) because the text doesn't change. The div containing this text is referenced by the id #npali

Output should look like this

Inquire about space

Enter Library

I am unable to get this to work. I was wondering if a PHP alternative would be available to help me achieve this.

Please help if you might know the fix.

答:
This can be done with the explode() See more: https://www.php.net/manual/en/function.explode.php

An example:

```<code>function slash2br($str){
  $parts = explode("/", $str);
  return implode("<br>", $parts);
}
</code>```

You could also preg_replace() and replace the / with
.

Body:
This can be done with the explode() See more: https://www.php.net/manual/en/function.explode.php

An example:

function slash2br($str){
  $parts = explode("/", $str);
  return implode("<br>", $parts);
}

You could also preg_replace() and replace the / with <br>.


问:
dispatching function/action vs dispatching {type: x}
When calling

```<code>store.dispatch(...)
</code>```

we can use it like so (1):

```<code>store.dispatch(dispatch => {
   dispatch(someOtherAction())
});
</code>```

or we can use it like so (2):

```<code>store.dispatch({type: constants.X})
</code>```

First question: What are the two different types arguments to dispatch called?
Second question: What is the difference between calling (1) versus calling (2)?

答:
In (1), you're dispatching a "thunk." In (2), you're dispatching an "action." Additionally, in (1), someOtherAction is an "action creator." You need some kind of additional middleware (e.g., redux-thunk) to dispatch a thunk.

Generally, your goal is to dispatch actions, but if you need to asynchronously dispatch an action (e.g., after an API call), you can use a thunk to be able to dispatch the action asynchronously. For example:

```<code>store.dispatch(dispatch => {
  fetch('api/user')
    .then(res => res.json())
    .then(user => {
      dispatch(loadUser(user))
    })
});
</code>```

In this example, we take advantage of the thunk concept by only dispatching a user-loading action after the user has been loaded from some API.

Body:
When calling

store.dispatch(...)

we can use it like so (1):

store.dispatch(dispatch => {
   dispatch(someOtherAction())
});

or we can use it like so (2):

store.dispatch({type: constants.X})

First question: What are the two different types arguments to dispatch called?
Second question: What is the difference between calling (1) versus calling (2)?

Body:
In (1), you're dispatching a "thunk." In (2), you're dispatching an "action." Additionally, in (1), someOtherAction is an "action creator." You need some kind of additional middleware (e.g., redux-thunk) to dispatch a thunk.

Generally, your goal is to dispatch actions, but if you need to asynchronously dispatch an action (e.g., after an API call), you can use a thunk to be able to dispatch the action asynchronously. For example:

store.dispatch(dispatch => {
  fetch('api/user')
    .then(res => res.json())
    .then(user => {
      dispatch(loadUser(user))
    })
});

In this example, we take advantage of the thunk concept by only dispatching a user-loading action after the user has been loaded from some API.


问:
Use type comments to narrow typing of already declared Python variable
How can one use type comments in Python to change or narrow the type of an already declared variable, in such a way as to make pycharm or other type-aware systems understand the new type.

For instance, I might have two classes:

class A:
   is_b = False
   ...

class B(A):
   is_b = True

   def flummox(self):
       return '?'
```

<p>and another function elsewhere:</p>

<pre class="lang-py prettyprint-override"><code>def do_something_to_A(a_in: A):
    ...
    if a_in.is_b:
       assert isinstance(a_in, B)  # THIS IS THE LINE...
       a_in.flummox()
</code>```

As long as I have the assert statement, PyCharm will understand that I've narrowed a_in to be of class B, and not complain about .flummox().  Without it, errors/warnings such as a_in has no method flummox will appear.

The question I have is, is there a PEP 484 (or successor) way of showing that a_in (which might have originally been of type A or B or something else) is now of type B without having the assert statement.  The statement b_in : B = a_in also gives type errors.

In TypeScript I could do something like this:

if a_in.is_b:
   const b_in = <any> a_in;
   b_in.flummox()

// or

if a_in.is_b:
   (a_in as B).flummox()
```

There are two main reasons I don't want to use the assert line is (1) speed is very important to this part of code, and having an extra is_instance call for every time the line is run slows it down too much, and (2) a project code style that forbids bare assert statements.

答:
So long as you are using Python 3.6+, you can "re-annotate" the type of a variable arbitrarily using the same syntax as you would use to "declare" the type of a variable without initializing it (PEP 526).

In the example you have provided, the following snippet has the behavior you expect:

```<code>def do_something_to_A(a_in: A):
    ...
    if a_in.is_b:
       a_in: B
       a_in.flummox()

</code>```

I have tested that this technique is properly detected by PyCharm 2019.2.

It is worth noting that this incurs no runtime cost since the same bytecode is generated with or without this added annotation statement. Given the following defintions,

```<code>def do_something_with_annotation(a_in: A):
     if a_in.is_b:
        a_in: B
        a_in.flummox()

def do_something_without_annotation(a_in: A):
     if a_in.is_b:
        a_in.flummox()
</code>```

dis produce the following bytecode:

```<code>>>> dis.dis(do_something_with_annotation)
  3           0 LOAD_FAST                0 (a_in)
              2 LOAD_ATTR                0 (is_b)
              4 POP_JUMP_IF_FALSE       14

  5           6 LOAD_FAST                0 (a_in)
              8 LOAD_ATTR                1 (flummox)
             10 CALL_FUNCTION            0
             12 POP_TOP
        >>   14 LOAD_CONST               0 (None)
             16 RETURN_VALUE
>>> dis.dis(do_something_without_annotation)
  3           0 LOAD_FAST                0 (a_in)
              2 LOAD_ATTR                0 (is_b)
              4 POP_JUMP_IF_FALSE       14

  4           6 LOAD_FAST                0 (a_in)
              8 LOAD_ATTR                1 (flummox)
             10 CALL_FUNCTION            0
             12 POP_TOP
        >>   14 LOAD_CONST               0 (None)
             16 RETURN_VALUE
</code>```

As a side note, you could also keep the assertion statements and disable assertions in your production environment by invoking the interpreter with the -O flag. This may or may not be considered more readable by your colleagues, depending on their familiarity with type hinting in Python.

Body:
How can one use type comments in Python to change or narrow the type of an already declared variable, in such a way as to make pycharm or other type-aware systems understand the new type.

For instance, I might have two classes:

class A:
   is_b = False
   ...

class B(A):
   is_b = True

   def flummox(self):
       return '?'

and another function elsewhere:

def do_something_to_A(a_in: A):
    ...
    if a_in.is_b:
       assert isinstance(a_in, B)  # THIS IS THE LINE...
       a_in.flummox()

As long as I have the assert statement, PyCharm will understand that I've narrowed a_in to be of class B, and not complain about .flummox().  Without it, errors/warnings such as a_in has no method flummox will appear.

The question I have is, is there a PEP 484 (or successor) way of showing that a_in (which might have originally been of type A or B or something else) is now of type B without having the assert statement.  The statement b_in : B = a_in also gives type errors.

In TypeScript I could do something like this:

if a_in.is_b:
   const b_in = <any> a_in;
   b_in.flummox()

// or

if a_in.is_b:
   (a_in as B).flummox()

There are two main reasons I don't want to use the assert line is (1) speed is very important to this part of code, and having an extra is_instance call for every time the line is run slows it down too much, and (2) a project code style that forbids bare assert statements.

Body:
So long as you are using Python 3.6+, you can "re-annotate" the type of a variable arbitrarily using the same syntax as you would use to "declare" the type of a variable without initializing it (PEP 526).

In the example you have provided, the following snippet has the behavior you expect:

def do_something_to_A(a_in: A):
    ...
    if a_in.is_b:
       a_in: B
       a_in.flummox()

I have tested that this technique is properly detected by PyCharm 2019.2.

It is worth noting that this incurs no runtime cost since the same bytecode is generated with or without this added annotation statement. Given the following defintions,

def do_something_with_annotation(a_in: A):
     if a_in.is_b:
        a_in: B
        a_in.flummox()

def do_something_without_annotation(a_in: A):
     if a_in.is_b:
        a_in.flummox()

dis produce the following bytecode:

>>> dis.dis(do_something_with_annotation)
  3           0 LOAD_FAST                0 (a_in)
              2 LOAD_ATTR                0 (is_b)
              4 POP_JUMP_IF_FALSE       14

  5           6 LOAD_FAST                0 (a_in)
              8 LOAD_ATTR                1 (flummox)
             10 CALL_FUNCTION            0
             12 POP_TOP
        >>   14 LOAD_CONST               0 (None)
             16 RETURN_VALUE
>>> dis.dis(do_something_without_annotation)
  3           0 LOAD_FAST                0 (a_in)
              2 LOAD_ATTR                0 (is_b)
              4 POP_JUMP_IF_FALSE       14

  4           6 LOAD_FAST                0 (a_in)
              8 LOAD_ATTR                1 (flummox)
             10 CALL_FUNCTION            0
             12 POP_TOP
        >>   14 LOAD_CONST               0 (None)
             16 RETURN_VALUE

As a side note, you could also keep the assertion statements and disable assertions in your production environment by invoking the interpreter with the -O flag. This may or may not be considered more readable by your colleagues, depending on their familiarity with type hinting in Python.


问:
Why multi-stage docker image is bigger than single stage?
I've created a microsservice (https://github.com/staticdev/enelvo-microservice) that needs to clone a git repository to create a docker image, with a single stage Dockerfile the final image has 759MB:

```<code>FROM python:3.7.6-slim-stretch

# set the working directory to /app
WORKDIR /app

# copy the current directory contents into the container at /app
COPY . /app

RUN apt-get update && apt-get install -y git \
 && pip install -r requirements.txt \
 && git clone https://github.com/tfcbertaglia/enelvo.git enelvo-src \
 && cd enelvo-src \
 && python setup.py install \
 && cd .. \
 && mv enelvo-src/enelvo enelvo \
 && rm -fr enelvo-src

EXPOSE 50051

# run app.py when the container launches
CMD ["python", "app.py"]
</code>```

I've tried the approach of using a multistage build (https://blog.bitsrc.io/a-guide-to-docker-multi-stage-builds-206e8f31aeb8) to reduce the image size without git and apt-get lists (from update):

```<code>FROM python:3.7.6-slim-stretch as cloner

RUN apt-get update && apt-get install -y git \
 && git clone https://github.com/tfcbertaglia/enelvo.git enelvo-src

FROM python:3.7.6-slim-stretch

COPY --from=cloner /enelvo-src /app/enelvo-src

# set the working directory to /app
WORKDIR /app

# copy the current directory contents into the container at /app
COPY . /app

RUN pip install -r requirements.txt \
 && cd enelvo-src \
 && python setup.py install \
 && cd .. \
 && mv enelvo-src/enelvo enelvo \
 && rm -fr enelvo-src

EXPOSE 50051

# run app.py when the container launches
CMD ["python", "app.py"]
</code>```

The problem is that, after doing that, the final size got even bigger (815MB). Any idea of what could be wrong in this case?

答:
In you're first example you're running

```<code>RUN git clone https://github.com/tfcbertaglia/enelvo.git enelvo-src \
    ... \
 && rm -fr enelvo-src
</code>```

and so the enelvo-src tree never exists outside this particular RUN instruction; it's deleted before Docker can build a layer out of it.

In the second example you're running

```<code>COPY --from=cloner /enelvo-src /app/enelvo-src
RUN rm -fr enelvo-src
</code>```

Docker internally creates an image layer after the first step that contains the content of that source tree.  The subsequent RUN rm doesn't actually make the image smaller, it just records that the content that was there from the earlier layer technically isn't part of the filesystem any more.

Generally the standard way to use a multi-stage build is to to as much building as you actually can in the earlier stage, and only COPY a final result into your runtime image.  For Python packages, one approach that can work well is to build a wheel out of the package:

FROM python:3.7.6-slim-stretch as build
WORKDIR /build
RUN apt-get update && apt-get install -y git \
 && git clone https://github.com/tfcbertaglia/enelvo.git enelvo-src
 && ...
 && python setup.py bdist_wheel  # (not "install")

FROM python:3.7.6-slim-stretch
WORKDIR /app
COPY --from=build /build/dist/wheel/enelvo*.whl .
RUN pip install enelvo*.whl
...
```

Body:
I've created a microsservice (https://github.com/staticdev/enelvo-microservice) that needs to clone a git repository to create a docker image, with a single stage Dockerfile the final image has 759MB:

FROM python:3.7.6-slim-stretch

# set the working directory to /app
WORKDIR /app

# copy the current directory contents into the container at /app
COPY . /app

RUN apt-get update && apt-get install -y git \
 && pip install -r requirements.txt \
 && git clone https://github.com/tfcbertaglia/enelvo.git enelvo-src \
 && cd enelvo-src \
 && python setup.py install \
 && cd .. \
 && mv enelvo-src/enelvo enelvo \
 && rm -fr enelvo-src

EXPOSE 50051

# run app.py when the container launches
CMD ["python", "app.py"]

I've tried the approach of using a multistage build (https://blog.bitsrc.io/a-guide-to-docker-multi-stage-builds-206e8f31aeb8) to reduce the image size without git and apt-get lists (from update):

FROM python:3.7.6-slim-stretch as cloner

RUN apt-get update && apt-get install -y git \
 && git clone https://github.com/tfcbertaglia/enelvo.git enelvo-src

FROM python:3.7.6-slim-stretch

COPY --from=cloner /enelvo-src /app/enelvo-src

# set the working directory to /app
WORKDIR /app

# copy the current directory contents into the container at /app
COPY . /app

RUN pip install -r requirements.txt \
 && cd enelvo-src \
 && python setup.py install \
 && cd .. \
 && mv enelvo-src/enelvo enelvo \
 && rm -fr enelvo-src

EXPOSE 50051

# run app.py when the container launches
CMD ["python", "app.py"]

The problem is that, after doing that, the final size got even bigger (815MB). Any idea of what could be wrong in this case?

Body:
In you're first example you're running

RUN git clone https://github.com/tfcbertaglia/enelvo.git enelvo-src \
    ... \
 && rm -fr enelvo-src

and so the enelvo-src tree never exists outside this particular RUN instruction; it's deleted before Docker can build a layer out of it.

In the second example you're running

COPY --from=cloner /enelvo-src /app/enelvo-src
RUN rm -fr enelvo-src

Docker internally creates an image layer after the first step that contains the content of that source tree.  The subsequent RUN rm doesn't actually make the image smaller, it just records that the content that was there from the earlier layer technically isn't part of the filesystem any more.

Generally the standard way to use a multi-stage build is to to as much building as you actually can in the earlier stage, and only COPY a final result into your runtime image.  For Python packages, one approach that can work well is to build a wheel out of the package:

FROM python:3.7.6-slim-stretch as build
WORKDIR /build
RUN apt-get update && apt-get install -y git \
 && git clone https://github.com/tfcbertaglia/enelvo.git enelvo-src
 && ...
 && python setup.py bdist_wheel  # (not "install")

FROM python:3.7.6-slim-stretch
WORKDIR /app
COPY --from=build /build/dist/wheel/enelvo*.whl .
RUN pip install enelvo*.whl
...


问:
Automatically build using the latest tag
Is there a way of setting up a job, that builds using the latest tag from a SVN repository?

The project structure is as follows

```<code>Project
|
|\trunk
|\branches
|\tags
 |
 |\REL_1.0.1
 |\REL_1.0.2
 |\REL_1.0.3
 |\REL_1.1.0
 |\REL_1.1.1
</code>```

I would like to replace REL_1.1.1, such that it always uses the latest tag.

EDIT: This is using Jenkins.

答: Have Hudson monitor a particular url. Say repo/latesttag. Suppose that latesttag has a file tag.txt with the tag name. The tag.txt gets updated through a post-commit hook whenever a new tag is added  ( through a new commit ). Now with every commit to tag.txt, ie whenever a new tag is created, a build gets triggered and use the tagname from the tag.txt to checkout / switch an existing checked out version of the previous latest tag and start a build from there.

Body:
Is there a way of setting up a job, that builds using the latest tag from a SVN repository?

The project structure is as follows

Project
|
|\trunk
|\branches
|\tags
 |
 |\REL_1.0.1
 |\REL_1.0.2
 |\REL_1.0.3
 |\REL_1.1.0
 |\REL_1.1.1

I would like to replace REL_1.1.1, such that it always uses the latest tag.

EDIT: This is using Jenkins.


答:
Try as below -

```<code>System.out.print("Would you like to include " + high + " into the list of random numbers(Yes or No)?");
yesOrNo = scan.next();
</code>```

Because of previous nextInt() method, nextLine() is getting skipped.

More explanation here - https://stackoverflow.com/a/13102066

Title: Integrating a boolean into an array parameter

Body:
Try as below -

System.out.print("Would you like to include " + high + " into the list of random numbers(Yes or No)?");
yesOrNo = scan.next();

Because of previous nextInt() method, nextLine() is getting skipped.

More explanation here - https://stackoverflow.com/a/13102066


问:
How do I display a final score and high score on gameover screen?
I am using libgdx and I am trying to figure out how to display the final score my players achieve, and the overall high score for their games when the game goes to the game over screen. I am unsure as to how to bring the score integer over from the game screen to the game over screen.</p>

答:
Option 1: Storing high score using preferences

I think you want to be able to close the game (close the window or kill the app) and have the high scores stored for the next time someone plays the game (executes the game or opens the app).

In this case preferences are the way to go and here's a simple example:

Game class

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;

public class PreferenceExample extends Game {

    @Override
    public void create() {
        // Initialize the preferences
        Preferences preferences = Gdx.app.getPreferences("examplePreferences");
        // Go to your game screen sending this LibGDX Game and the LibGDX Preferences
        setScreen(new GameScreen(this, preferences));
    }
}
```

<p><strong>Game screen class</strong></p>

<pre class="lang-java prettyprint-override"><code>import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.ScreenAdapter;

class GameScreen extends ScreenAdapter {

    private PreferenceExample game;
    private Preferences preferences;

    GameScreen(PreferenceExample game, Preferences preferences) {
        // Store reference to LibGDX Game
        this.game = game;
        // Store reference to LibGDX Preferences
        this.preferences = preferences;
    }

    @Override
    public void render(float delta) {
        if (Gdx.input.isKeyJustPressed(Input.Keys.L)) {
            saveHighScore(MathUtils.random(3));
            goToGameOverScreen();
        }
    }

    // Call this whenever you want to save the high score
    private void saveHighScore(int highScore) {
        preferences.putInteger("High score", highScore);
        preferences.flush();
    }

    // Call this whenever you want to switch to the game over screen
    private void goToGameOverScreen() {
        game.setScreen(new GameOverScreen(preferences));
    }
}
</code>```

Game over screen class

import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.ScreenAdapter;

class GameOverScreen extends ScreenAdapter {

    private Preferences preferences;
    private int highScore;

    GameOverScreen(Preferences preferences) {
        // Store reference to LibGDX Preferences
        this.preferences = preferences;
    }

    @Override
    public void show() {
        // Load high score, default value is 0 in case you didn't store it properly
        highScore = preferences.getInteger("High score", 0);
    }

    @Override
    public void render(float delta) {
        // Do something with the high score you retrieved
        System.out.println(highScore);
    }
}
```

<p><strong>Warning</strong>: be aware that storing and retrieving methods from <code>Preferences</code> are case sensitive so it is a good idea to put the <code>String</code> referencing the value on a variable to minimize mistakes.</p>

<h2>Option 2: Passing high score between screens</h2>

<p>Maybe you don't need the high scores stored for when the game is closed so passing the high score information from one screen to another should be easier, here's an example:  </p>

<p><strong>Game class</strong></p>

<pre class="lang-java prettyprint-override"><code>import com.badlogic.gdx.Game;

public class ScreenToScreenExample extends Game {

    @Override
    public void create() {
        // Go to your game screen sending this LibGDX Game and the LibGDX Preferences
        setScreen(new GameScreen(this));
    }
}
</code>```

Game screen class

import com.badlogic.gdx.ScreenAdapter;

class GameScreen extends ScreenAdapter {

    private ScreenToScreenExample game;
    private int highScore;

    GameScreen(ScreenToScreenExample game) {
        // Store reference to LibGDX Game
        this.game = game;
    }

    // Call this whenever you want to save the high score
    void saveHighScore(int highScore) {
        this.highScore = highScore;
    }

    // Call this whenever you want to switch to the game over screen
    void goToGameOverScreen() {
        game.setScreen(new GameOverScreen(highScore));
    }
}
```

<p><strong>Game over screen class</strong></p>

<pre class="lang-java prettyprint-override"><code>import com.badlogic.gdx.ScreenAdapter;

class GameOverScreen extends ScreenAdapter {

    private int highScore;

    GameOverScreen(int highScore) {
        this.highScore = highScore;
    }

    @Override
    public void render(float delta) {
        // Do something with the high score you retrieved
        System.out.println(highScore);
    }
}
</code>```

Body:
Option 1: Storing high score using preferences

I think you want to be able to close the game (close the window or kill the app) and have the high scores stored for the next time someone plays the game (executes the game or opens the app).

In this case preferences are the way to go and here's a simple example:

Game class

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;

public class PreferenceExample extends Game {

    @Override
    public void create() {
        // Initialize the preferences
        Preferences preferences = Gdx.app.getPreferences("examplePreferences");
        // Go to your game screen sending this LibGDX Game and the LibGDX Preferences
        setScreen(new GameScreen(this, preferences));
    }
}

Game screen class

import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.ScreenAdapter;

class GameScreen extends ScreenAdapter {

    private PreferenceExample game;
    private Preferences preferences;

    GameScreen(PreferenceExample game, Preferences preferences) {
        // Store reference to LibGDX Game
        this.game = game;
        // Store reference to LibGDX Preferences
        this.preferences = preferences;
    }

    @Override
    public void render(float delta) {
        if (Gdx.input.isKeyJustPressed(Input.Keys.L)) {
            saveHighScore(MathUtils.random(3));
            goToGameOverScreen();
        }
    }

    // Call this whenever you want to save the high score
    private void saveHighScore(int highScore) {
        preferences.putInteger("High score", highScore);
        preferences.flush();
    }

    // Call this whenever you want to switch to the game over screen
    private void goToGameOverScreen() {
        game.setScreen(new GameOverScreen(preferences));
    }
}

Game over screen class

import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.ScreenAdapter;

class GameOverScreen extends ScreenAdapter {

    private Preferences preferences;
    private int highScore;

    GameOverScreen(Preferences preferences) {
        // Store reference to LibGDX Preferences
        this.preferences = preferences;
    }

    @Override
    public void show() {
        // Load high score, default value is 0 in case you didn't store it properly
        highScore = preferences.getInteger("High score", 0);
    }

    @Override
    public void render(float delta) {
        // Do something with the high score you retrieved
        System.out.println(highScore);
    }
}

Warning: be aware that storing and retrieving methods from Preferences are case sensitive so it is a good idea to put the String referencing the value on a variable to minimize mistakes.

Option 2: Passing high score between screens

Maybe you don't need the high scores stored for when the game is closed so passing the high score information from one screen to another should be easier, here's an example:

Game class

import com.badlogic.gdx.Game;

public class ScreenToScreenExample extends Game {

    @Override
    public void create() {
        // Go to your game screen sending this LibGDX Game and the LibGDX Preferences
        setScreen(new GameScreen(this));
    }
}

Game screen class

import com.badlogic.gdx.ScreenAdapter;

class GameScreen extends ScreenAdapter {

    private ScreenToScreenExample game;
    private int highScore;

    GameScreen(ScreenToScreenExample game) {
        // Store reference to LibGDX Game
        this.game = game;
    }

    // Call this whenever you want to save the high score
    void saveHighScore(int highScore) {
        this.highScore = highScore;
    }

    // Call this whenever you want to switch to the game over screen
    void goToGameOverScreen() {
        game.setScreen(new GameOverScreen(highScore));
    }
}

Game over screen class

import com.badlogic.gdx.ScreenAdapter;

class GameOverScreen extends ScreenAdapter {

    private int highScore;

    GameOverScreen(int highScore) {
        this.highScore = highScore;
    }

    @Override
    public void render(float delta) {
        // Do something with the high score you retrieved
        System.out.println(highScore);
    }
}


问:
PWA (progressive web app) with nodejs+expressjs points to /public/ folder at start. How to fix?
Thanks for checking in :)

I am working on making PWA of my web app. My project is yet another nodejs+express set up. It serves public files via node and nginx all good. But when working with PWA all is dancing aroung public folder and routing breaks. So I put manifest.json and service worker js file there, installed my app to desktop and it works fine until I close it. When I fire it up again it points to /public/ folder by default just exposing file folder and nothing else.

In manifest.json: {"start_url":"/", "scope": "/"}. I also tried {"start_url":"./", "scope": "."} and all known to me relative variations, all the same - points to /public/.

I tried to res.send manifest file via router directly - no good, again points to directory where manifest.json resides.

When I install and open app on my android it just points to /public/ at start.

Have any idea what's going on here and how to solve it?

Thanks beforehands! :)

答:
So I solved it bypassing public folder, putting files to root of project and by sending files directly and it worked:</p>

```<code>router.get('/:filename', async function(req, res) {
    if(req.params.filename=='manifest.json'){
        res.sendFile(path.resolve('./manifest.json'))

    } else if(req.params.filename=='service_worker.js'){
        res.sendFile(path.resolve('./service_worker.js'))
    }
})
</code>```

Body:
So I solved it bypassing public folder, putting files to root of project and by sending files directly and it worked:

router.get('/:filename', async function(req, res) {
    if(req.params.filename=='manifest.json'){
        res.sendFile(path.resolve('./manifest.json'))

    } else if(req.params.filename=='service_worker.js'){
        res.sendFile(path.resolve('./service_worker.js'))
    }
})


问:
How can I get the data in Vue from Node.js
index.js

```<code>router.get('/', (req, res) => {
    var cart = req.cookies.cart;
    res.sendFile(path.join(__dirname,'../../src/components/cart.html'),cart);
})
</code>```

cart.html

```<code><body>
    <div id="app" class="container mt-3">
        <h2> cart View </h2>
    </div>
</body>

<script>
    new Vue({
        el: '#app',
        data: {

        }
    })
</script>
</code>```

I want to get cookies in vue..

How to get 'cart' data in Vue ?

Is that right way make res.send('../cart.html',cart)?

答:
You have to do request from vue to your server to fetch the data. You can use axios for that.

BUT in this case you are sending cookies to server and trying to return cookies from request, why? You can take your cookies on front-end without any request, use js-cookie.

```<code>Cookie.get('cart')
</code>```

Body:
index.js

router.get('/', (req, res) => {
    var cart = req.cookies.cart;
    res.sendFile(path.join(__dirname,'../../src/components/cart.html'),cart);
})

cart.html

 cart View

I want to get cookies in vue..

How to get 'cart' data in Vue ?

Is that right way make res.send('../cart.html',cart)?

Body:
You have to do request from vue to your server to fetch the data. You can use axios for that.

BUT in this case you are sending cookies to server and trying to return cookies from request, why? You can take your cookies on front-end without any request, use js-cookie.

Cookie.get('cart')


问:
Is it possible to use django-celery-beat with django-tenant?
I am using celery for scheduling tasks. So far everything was fine, including hosted on AWS. However, I decided to transform my single application to multi tenant, using django-tenant. That way, I can create the subdomains perfectly.

./manage.py create_tenant
```

<p>However, when running the command <code>celery -A myproject worker -B</code>, despite not showing me any error, It seems to me that he cannot run for the created schema (test with only one created).</p>

<p>I tried to specify the schema, using <code>python manage.py tenant_command celery worker -B --loglevel = info --schema = myschema</code>
but I received the following error:</p>

<pre class="lang-py prettyprint-override"><code>raise CommandError ("Unknown command:% r"% argv [2])
django.core.management.base.CommandError: Unknown command: 'celery'
</code>```

If anyone can help me, I really appreciate It!
If It is possible to run the command for a specific schema, is It also possible to run globally for all schemas created? Thanks!

答:
You should extend celery Task implementation and inject the db_schema and use it instead

But it would be also OK not to reinvent the wheel and use
https://github.com/maciej-gol/tenant-schemas-celery

Body:
I am using celery for scheduling tasks. So far everything was fine, including hosted on AWS. However, I decided to transform my single application to multi tenant, using django-tenant. That way, I can create the subdomains perfectly.

./manage.py create_tenant

However, when running the command celery -A myproject worker -B, despite not showing me any error, It seems to me that he cannot run for the created schema (test with only one created).

I tried to specify the schema, using python manage.py tenant_command celery worker -B --loglevel = info --schema = myschema
but I received the following error:

raise CommandError ("Unknown command:% r"% argv [2])
django.core.management.base.CommandError: Unknown command: 'celery'

If anyone can help me, I really appreciate It!
If It is possible to run the command for a specific schema, is It also possible to run globally for all schemas created? Thanks!


问:
HIVE-SQL_SERVER: HadoopExecutionException: Not enough columns in this line
I have a hive table with the following structure and data:

Table structure:

```<code>CREATE EXTERNAL TABLE IF NOT EXISTS  db_crprcdtl.shcar_dtls
  ID  string,
  CSK string,
  BRND string,
  MKTCP string,
  AMTCMP string,
  AMTSP string,
  RLBRND string,
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION '/on/hadoop/dir/'

-------------------------------------------------------------------------------
ID  |     CSK |          BRND |          MKTCP |            AMTCMP
-------------------------------------------------------------------------------
782    flatn,grpl,mrtn  hnd,mrc,nsn    34555,56566,66455     38900,59484,71450
1231   jikl,bngr        su,mrc,frd     56566,32333,45000     59872,35673,48933
123    unsrvl           tyt,frd,vlv    25000,34789,33443     29892,38922,36781
</code>```

Trying to push this data into the SQL Server. But while doing so, getting the following error message:

```<code>SQL Error [107090] [S0001]: HdfsBridge::recordReaderFillBuffer - Unexpected error encountered filling record reader buffer: HadoopExecutionException: Not enough columns in this line.
</code>```

What I tried:

There's an online article where the author has documented similar kind of issues. I tried to implement one of them Looked in Excel and found two columns that had carriage returns but this also doesn't come handy.

Any suggestion/help would be really appreciated. Thanks

答:
If I'm able to understand your issue, then it seems that your , separated data is getting divided into various columns rather one column on the SQL-SERVER, something like:

```<code>------------------------------
ID  |CSK |BRND |MKTCP |AMTCMP
------------------------------
782    flatn grpl mrtn  hnd mrc nsn  345   56566 66455   38900 59484 71450
1231   jikl bngr        su  mrc frd  56566 32333 45000   59872 35673 48933
123    unsrvl           tyt frd vlv  25000 34789 33443   29892 38922 36781
</code>```

So, if you look on Hive there are only 5 columns. While on SQL-SERVER the same. This I presume as you haven't shared the schema. But if that's the case, then you see that there are more than 5 values are being passed. While the schema definition is only of 5 columns.
So the error is populating.

Refer this Document by MS and try to create a FILE_FORMAT with FIELD_TERMINATOR ='\t',
like:

```<code>CREATE EXTERNAL FILE FORMAT <name>
WITH (
   FORMAT_TYPE = DELIMITEDTEXT,
   FORMAT_OPTIONS (
        FIELD_TERMINATOR ='\t',
        | STRING_DELIMITER = string_delimiter
        | First_Row = integer -- ONLY AVAILABLE SQL DW
        | DATE_FORMAT = datetime_format
        | USE_TYPE_DEFAULT = { TRUE | FALSE }
        | Encoding = {'UTF8' | 'UTF16'} )
  );
</code>```

Hope that helps to resolve to your issue :)

Body:
I have a hive table with the following structure and data:

Table structure:

CREATE EXTERNAL TABLE IF NOT EXISTS  db_crprcdtl.shcar_dtls
  ID  string,
  CSK string,
  BRND string,
  MKTCP string,
  AMTCMP string,
  AMTSP string,
  RLBRND string,
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION '/on/hadoop/dir/'

-------------------------------------------------------------------------------
ID  |     CSK |          BRND |          MKTCP |            AMTCMP
-------------------------------------------------------------------------------
782    flatn,grpl,mrtn  hnd,mrc,nsn    34555,56566,66455     38900,59484,71450
1231   jikl,bngr        su,mrc,frd     56566,32333,45000     59872,35673,48933
123    unsrvl           tyt,frd,vlv    25000,34789,33443     29892,38922,36781

Trying to push this data into the SQL Server. But while doing so, getting the following error message:

SQL Error [107090] [S0001]: HdfsBridge::recordReaderFillBuffer - Unexpected error encountered filling record reader buffer: HadoopExecutionException: Not enough columns in this line.

What I tried:

There's an online article where the author has documented similar kind of issues. I tried to implement one of them Looked in Excel and found two columns that had carriage returns but this also doesn't come handy.

Any suggestion/help would be really appreciated. Thanks

Body:
If I'm able to understand your issue, then it seems that your , separated data is getting divided into various columns rather one column on the SQL-SERVER, something like:

------------------------------
ID  |CSK |BRND |MKTCP |AMTCMP
------------------------------
782    flatn grpl mrtn  hnd mrc nsn  345   56566 66455   38900 59484 71450
1231   jikl bngr        su  mrc frd  56566 32333 45000   59872 35673 48933
123    unsrvl           tyt frd vlv  25000 34789 33443   29892 38922 36781

So, if you look on Hive there are only 5 columns. While on SQL-SERVER the same. This I presume as you haven't shared the schema. But if that's the case, then you see that there are more than 5 values are being passed. While the schema definition is only of 5 columns.
So the error is populating.

Refer this Document by MS and try to create a FILE_FORMAT with FIELD_TERMINATOR ='\t',
like:

CREATE EXTERNAL FILE FORMAT <name>
WITH (
   FORMAT_TYPE = DELIMITEDTEXT,
   FORMAT_OPTIONS (
        FIELD_TERMINATOR ='\t',
        | STRING_DELIMITER = string_delimiter
        | First_Row = integer -- ONLY AVAILABLE SQL DW
        | DATE_FORMAT = datetime_format
        | USE_TYPE_DEFAULT = { TRUE | FALSE }
        | Encoding = {'UTF8' | 'UTF16'} )
  );

Hope that helps to resolve to your issue :)


问:
Why does vega-lite draw the legend for layers that have legend set to null?
I have a plot with a separate layer for each of two categories of data. Each category has two subcategories. Only the first top-level category should have a legend. So I put legend: null on the second category and put a resolve at the top level to make the legends independent. But it's not working. Here's the plot, and below it is my code. I expect to see only a and b in the legend.

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>legend test</title>
    <link rel="stylesheet" href="styles/style.css" />
    <script src="https://cdn.jsdelivr.net/npm/vega@5.9.1"></script>
    <script src="https://cdn.jsdelivr.net/npm/vega-lite@4.2.0"></script>
    <script src="https://cdn.jsdelivr.net/npm/vega-embed@6.2.2"></script>
  </head>
  <body>
    <div id="plot-div"></div>
    <script>
let spec = {
    $schema: "https://vega.github.io/schema/vega-lite/v4.json",
    description: "sigmatcher",
    data: {
        values: [
            {legendGroup: true, x: 1, y: 1, cat: "a"},
            {legendGroup: true, x: 2, y: 2, cat: "b"},
            {legendGroup: true, x: 3, y: 4, cat: "a"},
            {legendGroup: true, x: 4, y: 8, cat: "b"},
            {legendGroup: false, x: 1, y: 11, cat: "c"},
            {legendGroup: false, x: 2, y: 12, cat: "d"},
            {legendGroup: false, x: 3, y: 14, cat: "c"},
            {legendGroup: false, x: 4, y: 18, cat: "d"},
            {legendGroup: false, x: 5, y: 26, cat: "c"},
        ]},
    width: 400,
    height: 400,
    resolve: {
        legend: {
            color: "independent",
        }
    },
    layer: [{
        transform: [{
            filter: {
                field: "legendGroup",
                equal: true
            }}],
        encoding: {
            x: {
                field: "x",
                type: "quantitative"
            },
            y: {
                field: "y",
                type: "quantitative"
            },
            color: {
                field: "cat",
                type: "nominal"
            }
        },
        mark: {
            type: "point"
        }
    }, {
        transform: [{
            filter: {
                field: "legendGroup",
                equal: false
            }}],
        encoding: {
            x: {
                field: "x",
                type: "quantitative"
            },
            y: {
                field: "y",
                type: "quantitative"
            },
            color: {
                field: "cat",
                type: "nominal",
                legend: null
            }
        },
        mark: {
            type: "point"
        }
    }]};
vegaEmbed("#plot-div", spec);
    </script>
  </body>
</html>
</code>```

答:
Independent legends will still share a color scale unless you specify otherwise. You can change this by specifying resolve.scale.

In your case, instead of

```<code>"resolve": {"legend": {"color": "independent"}}
</code>```

you should use

```<code>"resolve": {"scale": {"color": "independent"}}
</code>```

Otherwise the scales will still be shared despite the legends being independent. If desired, you can then adjust the color schemes used by each layer to distinguish the points.

See it in action here:

Body:
I have a plot with a separate layer for each of two categories of data. Each category has two subcategories. Only the first top-level category should have a legend. So I put legend: null on the second category and put a resolve at the top level to make the legends independent. But it's not working. Here's the plot, and below it is my code. I expect to see only a and b in the legend.

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>legend test</title>
    <link rel="stylesheet" href="styles/style.css" />

Body:
Independent legends will still share a color scale unless you specify otherwise. You can change this by specifying resolve.scale.

In your case, instead of

"resolve": {"legend": {"color": "independent"}}

you should use

"resolve": {"scale": {"color": "independent"}}

Otherwise the scales will still be shared despite the legends being independent. If desired, you can then adjust the color schemes used by each layer to distinguish the points.

See it in action <a href="https://vega.github.io/editor/#/url/vega-lite/N4KABGBEAkDODGALApgWwIaQFxUQFzwAdYsB6UgN2QHN0A6agSz0QFcAjOxge1IRQyUa6ALQAbZskoAWOgCtY3AHaQANOCgATZAgBOjQnh4qckWI2oY8SZLrUbIm9Hkw5QECJAroxrHdjAAbQ0PMGBIMRpkJU0AcV1uVkIAvF0-VSgADwCARgzIAE9c-PhnAMhMAF91UIhwyOpouISklLTkfOycACZ8op6SstN2SGqQj3qomPjE5JxU9KyAgGY+gOlBvHKqmtrJxumWubAFjqWcDah+sAAOTfKRsdqwiKnm2YCAMx9YM8gusB5K65IGQUpbUzwUa7UL7JozVo4b5iX6dAK9YE4HIYsFDLTQ8Z1V4Hd6IsDI1HnMCrTGAy64iFQKFPPbE+FHL4-P4A+nXHJ3Jl4xwE55ww4fJFctE4ACsax6ADZ7pDRuMALoaFmQADujE0LHWAAZDbtICgLPgjSaHLodNwxFQAuEED5kE6wfbuHZTIwYshCE1oltKlqxOgCrYAsFYYSoKl0EpYJ8vago+FPowxHhI25IBnkGJNOUGuyPvlkABHVg+Np+ENqmEeSDReDcTS+6hO2OeAHpxgFoumbL5PAFAPlKsJowuIyOlnPQru-OF8pFEdjt2mSdKafORhzxuhD1iL1L-sryFldfj0xKbioX01yqx+dNjC6ADW7tHN6ghG4vrBuMr7uLUkDxomya6KmOCBH2WY5i8y6DlAJbiq05aTmInIosg9aHlALZth2XbPD2Z4DuUw5xhuE7VjuzB7ge3a0n2lGmGuNG-pA267rObqvkerYnt6SHnihDJqFxm5QHeD5KDW+RoShSisGIYjPs8glQO+X65j+MmQP+gGqqEmlgBqlRAA" rel="nofollow noreferrer">here:


问:
When would an 'is' predicate ever be needed, as opposed to using the 'in' operator?
According to the TypeScript documentation we can use TypeGuards to differentiate between types.

The documentation gives examples using the is predicate, and using the in operator.

is predicate:

```<code>function isFish(pet: Fish | Bird): pet is Fish {
    return (pet as Fish).swim !== undefined;
}

if (isFish(pet)) {
    pet.swim();
}
else {
    pet.fly();
}
</code>```

in operator:

```<code>function move(pet: Fish | Bird) {
    if ("swim" in pet) {
        return pet.swim();
    }
    return pet.fly();
}
</code>```

The in operator seems a lot more concise and simpler - although perhaps explicitly pulling the type differentiation into a function is helpful and easier to maintain in the long run.

Are there any cases where the is predicate can differentiate between types where the in operator cannot?

答:
The in operator is just one way of narrowing the type of a variable. You can write type guards using any checks you like:

type JSONPrimitive = number | string | boolean | null;

function isJsonPrimitive(x: any): x is JSONPrimitive {
    return x === null
        || typeof x === 'number'
        || typeof x === 'string'
        || typeof x === 'boolean';
}
```

<p>Or:</p>

```interface TreeNode {
    value: number;
    left: TreeNode | null;
    right: TreeNode | null;
}
type InternalNode = TreeNode & ({ left: TreeNode } | { right: TreeNode });

function isInternalNode(node: TreeNode): node is InternalNode {
    return node.left !== null || node.right !== null;
}
```

Neither of these examples can be rewritten equivalently using the in operator.

That said, user-defined type guards are similar to type assertions, in that Typescript does not check their correctness. So you can use literally any logic you like in the implementation of your type guard; even an unconditional return true; is allowed.

Body:
According to the TypeScript documentation we can use TypeGuards to differentiate between types.

The documentation gives examples using the is predicate, and using the in operator.

is predicate:

function isFish(pet: Fish | Bird): pet is Fish {
    return (pet as Fish).swim !== undefined;
}

if (isFish(pet)) {
    pet.swim();
}
else {
    pet.fly();
}

in operator:

function move(pet: Fish | Bird) {
    if ("swim" in pet) {
        return pet.swim();
    }
    return pet.fly();
}

The in operator seems a lot more concise and simpler - although perhaps explicitly pulling the type differentiation into a function is helpful and easier to maintain in the long run.

Are there any cases where the is predicate can differentiate between types where the in operator cannot?

Body:
The in operator is just one way of narrowing the type of a variable. You can write type guards using any checks you like:

type JSONPrimitive = number | string | boolean | null;

function isJsonPrimitive(x: any): x is JSONPrimitive {
    return x === null
        || typeof x === 'number'
        || typeof x === 'string'
        || typeof x === 'boolean';
}

Or:

interface TreeNode {
    value: number;
    left: TreeNode | null;
    right: TreeNode | null;
}
type InternalNode = TreeNode & ({ left: TreeNode } | { right: TreeNode });

function isInternalNode(node: TreeNode): node is InternalNode {
    return node.left !== null || node.right !== null;
}

Neither of these examples can be rewritten equivalently using the in operator.

That said, user-defined type guards are similar to type assertions, in that Typescript does not check their correctness. So you can use literally any logic you like in the implementation of your type guard; even an unconditional return true; is allowed.


问:
Using permutation with int arrays (C)
The following code has the user input the length of the first array, then takes in the values of the first array. After this, the code takes in the values for a second array that is one size smaller than the initial array. After finding these values, the code then permutes both arrays. However the second array keeps failing to permute correctly, can anyone tell me why?</p>

```<code> #include <stdio.h>
 #include <math.h>
 #include <stdlib.h>
 #define N 12
 #define M 11

 int print(int *arr, int n)
 {
 int i;
for ( i = 0 ; i < n ; i++)
    printf("%d ", arr[i]);
    printf(“\n”);
    }

 int main()
 {
  int count = 0;
  int n;
  scanf("%d", &n);
  if (n>12)
  {
  printf("Please choose a      number less than or equal to 12");
 return 0;
 }
 int i, j;
 int arr[N];
 int bok[M];
 int temp;
 int k=n-1;
 for (int i = 0 ; i < n; ++i)
 {

scanf("%d", &arr[i]);
}
for (int i=0; i < k; ++i)
 {
   scanf("%d", &bok[i]);
   }
   for (j = 1; j <= n; j++) {
   for (i = 0; i < n-1; i++) {
        temp = arr[i];
        arr[i] = arr[i+1];
        arr[i+1] = temp;
        print(arr, n);
     }
     }
    for (j = 1; j <= n; j++) {
    for (i = 0; i < n-1; i++)                  {
        temp = bok[i];
        bok[i] = bok[i+1];
        bok[i+1] = temp;
        print(bok, n);
       }
     }
   return 0;
</code>```

答:
Since the second array is one smaller than the first, it has n-1 elements, and the index of its last assigned element is n-2. A loop for (i = 0; i < n-1; i++) is used, which iterates i to a maximum value of n-2. Then, inside the loop, bok[i+1] is accessed. When i has the value n-2, this is bok[n-2+1] = bok[n-1]. But that is beyond the last assigned element of bok, which is bok[n-2].

It appears you intend k to represent n-1. Given this, every instance of n in the second set of permutation code should be changed to k.

If the code is intended to print every permutation of the numbers, it is incomplete; the algorithm apparently intended cannot do the job.

Title: Using permutation with int arrays (C)

Body:
The following code has the user input the length of the first array, then takes in the values of the first array. After this, the code takes in the values for a second array that is one size smaller than the initial array. After finding these values, the code then permutes both arrays. However the second array keeps failing to permute correctly, can anyone tell me why?

 #include <stdio.h>
 #include <math.h>
 #include <stdlib.h>
 #define N 12
 #define M 11

 int print(int *arr, int n)
 {
 int i;
for ( i = 0 ; i < n ; i++)
    printf("%d ", arr[i]);
    printf(“\n”);
    }

 int main()
 {
  int count = 0;
  int n;
  scanf("%d", &n);
  if (n>12)
  {
  printf("Please choose a      number less than or equal to 12");
 return 0;
 }
 int i, j;
 int arr[N];
 int bok[M];
 int temp;
 int k=n-1;
 for (int i = 0 ; i < n; ++i)
 {

scanf("%d", &arr[i]);
}
for (int i=0; i < k; ++i)
 {
   scanf("%d", &bok[i]);
   }
   for (j = 1; j <= n; j++) {
   for (i = 0; i < n-1; i++) {
        temp = arr[i];
        arr[i] = arr[i+1];
        arr[i+1] = temp;
        print(arr, n);
     }
     }
    for (j = 1; j <= n; j++) {
    for (i = 0; i < n-1; i++)                  {
        temp = bok[i];
        bok[i] = bok[i+1];
        bok[i+1] = temp;
        print(bok, n);
       }
     }
   return 0;


问:
Find a reference to AppCompatDialogFragment
In my Andriod app, I've got a Dialog extended from AppCompatDialogFragment. I show it immediatelly in my App's main Activity's onCreate:

```<code>@Override
protected void onCreate(Bundle savedState)
  {
  super.onCreate(savedState);

  // ....

  if( savedState==null )
    {
    MyDialog diag = new MyDialog();
    diag.show(getSupportFragmentManager(), null);
    }
  }
</code>```

later on I want to dismiss this dialog - so I need to find it. I cannot simply remember a reference to it in my Activity, as when I e.g. rotate the phone the Dialog gets recreated and my reference would be invalid.

How do I get a reference to MyDialog later on in my code?

答:
The second parameter to show() is the tag.

This tag is what allows you to use findFragmentByTag() later to retrieve that Fragment.

Therefore, just use any other value than null

```<code>diag.show(getSupportFragmentManager(), "dialog");
</code>```

And then you can retrieve the fragment:

```<code>MyDialog diag = (MyDialog) getSupportFragmentManager().findFragmentByTag("dialog");
</code>```

Body:
In my Andriod app, I've got a Dialog extended from AppCompatDialogFragment. I show it immediatelly in my App's main Activity's onCreate:

@Override
protected void onCreate(Bundle savedState)
  {
  super.onCreate(savedState);

  // ....

  if( savedState==null )
    {
    MyDialog diag = new MyDialog();
    diag.show(getSupportFragmentManager(), null);
    }
  }

later on I want to dismiss this dialog - so I need to find it. I cannot simply remember a reference to it in my Activity, as when I e.g. rotate the phone the Dialog gets recreated and my reference would be invalid.

How do I get a reference to MyDialog later on in my code?

Body:
The second parameter to show() is the tag.

This tag is what allows you to use findFragmentByTag() later to retrieve that Fragment.

Therefore, just use any other value than null

diag.show(getSupportFragmentManager(), "dialog");

And then you can retrieve the fragment:

MyDialog diag = (MyDialog) getSupportFragmentManager().findFragmentByTag("dialog");


问:
Feathers - Socket.io - /socket.io/?EIO=3&transport=websocket - 404 not found
I get the following error https://0.0.0.0:3030/socket.io/?EIO=3&transport=websocket 404 not found.

I am using this code for my server side :

// index.ts
import fs from "fs";
import https from "https";

const server = https
  .createServer(
    {
      cert: fs.readFileSync("server.crt"),
      key: fs.readFileSync("server.key"),
      requestCert: true,
      rejectUnauthorized: true,
      ca: fs.readFileSync("rootCA.crt")
    },
    app
  )
  .listen("3030");
```

<p>And I am using this code for the client side :</p>

<pre class="lang-js prettyprint-override"><code>// feathers-client.ts
const socket = io("https://0.0.0.0:3030", {
  transports: ["websocket"],
  secure: true
});
</code>```

答:
A socket.io client connects to a socket.io server.  The server code you show is only a plain web server.  You need the socket.io server library to hook into your web server so that it can handle incoming socket.io connections.  You can do that like this:

```<code>// index.ts
import fs from "fs";
import https from "https";
import socketIO from 'socket.io';

const server = https.createServer(
    {
      cert: fs.readFileSync("server.crt"),
      key: fs.readFileSync("server.key"),
      requestCert: true,
      rejectUnauthorized: true,
      ca: fs.readFileSync("rootCA.crt")
    },
    app
  )
  .listen("3030");

// hook socket.io into your server to make an instance of a socket.io server
const io = socketIO(server);
</code>```

Now, your server is reading for incoming socket.io client connections with the client code you show.

Body:
I get the following error https://0.0.0.0:3030/socket.io/?EIO=3&transport=websocket 404 not found.

I am using this code for my server side :

// index.ts
import fs from "fs";
import https from "https";

const server = https
  .createServer(
    {
      cert: fs.readFileSync("server.crt"),
      key: fs.readFileSync("server.key"),
      requestCert: true,
      rejectUnauthorized: true,
      ca: fs.readFileSync("rootCA.crt")
    },
    app
  )
  .listen("3030");

And I am using this code for the client side :

// feathers-client.ts
const socket = io("https://0.0.0.0:3030", {
  transports: ["websocket"],
  secure: true
});

Body:
A socket.io client connects to a socket.io server.  The server code you show is only a plain web server.  You need the socket.io server library to hook into your web server so that it can handle incoming socket.io connections.  You can do that like this:

// index.ts
import fs from "fs";
import https from "https";
import socketIO from 'socket.io';

const server = https.createServer(
    {
      cert: fs.readFileSync("server.crt"),
      key: fs.readFileSync("server.key"),
      requestCert: true,
      rejectUnauthorized: true,
      ca: fs.readFileSync("rootCA.crt")
    },
    app
  )
  .listen("3030");

// hook socket.io into your server to make an instance of a socket.io server
const io = socketIO(server);

Now, your server is reading for incoming socket.io client connections with the client code you show.


问:
Unable to serialise AWSDate from Elasticsearch
I'm building an AppSync project using AWS elasticsearch service as my db, and got this error when querying:

"Can't serialize value (/getUsers/created_at) : Unable to serialize
  2020-01-18T07:36:13 as a valid DateTime Object."

This happens when I get a User object which looks like this:

```<code>type Users {
  id: String!
  name: String!
  description: String
  created_at: AWSDateTime
  updated_at: AWSDateTime
  logged_in: AWSDateTime
}
</code>```

The data stored in elasticsearch is of string type and of this format: 2020-01-18T07:36:13.

I saw similar posts of this sort but can't find any solution for it. So, is there any way, I should deserialize it to AWSDataTime in my response mapping template or should I store in some date format in elasticsearch.

One solution I got from this post Unable to serialise AWSDate from RDS in AppSync response mapping template is that to make the type of the date as String. But then, what's the use of AWSDateTime at all.

答: Looking at the AWS AppSync docs, it seems that the time zone offset is compulsory for this scalar (AWSDateTime that is). From your example, it seems this is missing since there is nothing after the seconds field. You could try appending the time zone offset yourself in which case, it will serialize correctly. </p>

Body:
I'm building an AppSync project using AWS elasticsearch service as my db, and got this error when querying:

"Can't serialize value (/getUsers/created_at) : Unable to serialize
  2020-01-18T07:36:13 as a valid DateTime Object."

This happens when I get a User object which looks like this:

type Users {
  id: String!
  name: String!
  description: String
  created_at: AWSDateTime
  updated_at: AWSDateTime
  logged_in: AWSDateTime
}

The data stored in elasticsearch is of string type and of this format: 2020-01-18T07:36:13.

I saw similar posts of this sort but can't find any solution for it. So, is there any way, I should deserialize it to AWSDataTime in my response mapping template or should I store in some date format in elasticsearch.

One solution I got from this post Unable to serialise AWSDate from RDS in AppSync response mapping template is that to make the type of the date as String. But then, what's the use of AWSDateTime at all.