问:
Do split one class hierarchy into several or not?
For now, we have a .NET application that leans on the standard .NET XML serialization/deserialization mechanism. The example is simplified but the meaning is the same.

```<code>public abstract class Shape
{
    [XmlAttribute("id")]
    public string Id { get; set; }
    [XmlAttribute("level")]
    public int Level { get; set; }

    public abstract void Draw();
    public abstract void Clear();
    public abstract void Scale(double scale);
}

[XmlType("Circle")]
public class Circle : Shape
{
    public double Radius { get; set; }

    public override void Draw() {}

    public override void Clear() {}

    public override void Scale(double scale) {}
}

[XmlType("Rectangle")]
public class Rectangle: Shape
{
    public double Height { get; set; }
    public double Width { get; set; }

    public override void Draw() {}

    public override void Clear() {}

    public override void Scale(double scale) {}
}

public class Picture
{
    public double Scale { get; set; }
    [XmlArrayAttribute("Shapes")]
    public Collection<Shape> Shapes { get; set; }

    public void Setup()
    {
        foreach (Shape shape in Shapes)
        {
            shape.Draw();
        }

        foreach (Shape shape in Shapes)
        {
            shape.Scale(Scale);
        }
    }

    public void Cleanup()
    {
        foreach (Shape shape in Shapes)
        {
            shape.Clear();
        }
    }

    public static Picture FromXml(XmlReader xmlReader)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Picture));
        return serializer.Deserialize(xmlReader) as Picture;
    }
}
</code>```

And for example the input XML file will look like:

```<code><Picture>
    <Scale>0.9</Scale>
    <Shapes>
        <Circle id="1">
            <Radius>1.5</Radius>
        </Circle>
        <Circle id="2">
            <Radius>3</Radius>
        </Circle>
        <Rectangle id="3">
            <Height>300</Height>
            <Width>300</Width>
        </Rectangle>
    </Shapes>
</Picture>
</code>```

But model classes contain a logic (Draw(), Clear() and Scale() methods) and it seems that it breaks a single responsibility principle. And therefore we don't know does it make sense to split that logic into several classes or not?

If yes, then how? Because once we read the XML file, all objects are accessible only as Shape objects and therefore we will have to explicitly cast the object either before passing if to the handler class or inside that method, for example:

```<code>public abstract class Drawer
{
    public abstract void Draw(Shape shape);
}

public class CircleDrawer : Drawer
{
    public override void Draw(Shape shape)
    {
        Circle circle = shape as Circle;
        if (circle == null)
        {
            throw new ArgumentException("Passed object is not of type Circle");
        }
    }
}
</code>```

If that issue is known, please just redirect me to that resource.

Thank you in advance.

答:
You should separate the model and business logic,
So the object that will be deserialized will contain only the properties.
Then, in the factory or method that creates the business logic, insert it as a member of the circle (for example) business logic. </p>

Body:
For now, we have a .NET application that leans on the standard .NET XML serialization/deserialization mechanism. The example is simplified but the meaning is the same.

public abstract class Shape
{
    [XmlAttribute("id")]
    public string Id { get; set; }
    [XmlAttribute("level")]
    public int Level { get; set; }

    public abstract void Draw();
    public abstract void Clear();
    public abstract void Scale(double scale);
}

[XmlType("Circle")]
public class Circle : Shape
{
    public double Radius { get; set; }

    public override void Draw() {}

    public override void Clear() {}

    public override void Scale(double scale) {}
}

[XmlType("Rectangle")]
public class Rectangle: Shape
{
    public double Height { get; set; }
    public double Width { get; set; }

    public override void Draw() {}

    public override void Clear() {}

    public override void Scale(double scale) {}
}

public class Picture
{
    public double Scale { get; set; }
    [XmlArrayAttribute("Shapes")]
    public Collection<Shape> Shapes { get; set; }

    public void Setup()
    {
        foreach (Shape shape in Shapes)
        {
            shape.Draw();
        }

        foreach (Shape shape in Shapes)
        {
            shape.Scale(Scale);
        }
    }

    public void Cleanup()
    {
        foreach (Shape shape in Shapes)
        {
            shape.Clear();
        }
    }

    public static Picture FromXml(XmlReader xmlReader)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Picture));
        return serializer.Deserialize(xmlReader) as Picture;
    }
}

And for example the input XML file will look like:

<Picture>
    <Scale>0.9</Scale>
    <Shapes>
        <Circle id="1">
            <Radius>1.5</Radius>
        </Circle>
        <Circle id="2">
            <Radius>3</Radius>
        </Circle>
        <Rectangle id="3">
            <Height>300</Height>
            <Width>300</Width>
        </Rectangle>
    </Shapes>
</Picture>

But model classes contain a logic (Draw(), Clear() and Scale() methods) and it seems that it breaks a single responsibility principle. And therefore we don't know does it make sense to split that logic into several classes or not?

If yes, then how? Because once we read the XML file, all objects are accessible only as Shape objects and therefore we will have to explicitly cast the object either before passing if to the handler class or inside that method, for example:

public abstract class Drawer
{
    public abstract void Draw(Shape shape);
}

public class CircleDrawer : Drawer
{
    public override void Draw(Shape shape)
    {
        Circle circle = shape as Circle;
        if (circle == null)
        {
            throw new ArgumentException("Passed object is not of type Circle");
        }
    }
}

If that issue is known, please just redirect me to that resource.

Thank you in advance.


来源: stackexchange

问:
Is DocuSign Payment possible through DocuSign SOAP API?
We're currently have our application integrated to DocuSign through the DocuSign SOAP API.  We want to use DocuSign Payment with Stripe.  Trying to determine if the DocuSign SOAP API will work in creating the payment tab or will we need to switch to using DocuSign REST API.

The effort of rewriting our integration to use DocuSign REST API is a bigger task so looking to see if the SOAP API will work with DocuSign Payment since I couldn't find any example.

答:
For many use cases, a template can hold the fields (tags) needed for payments. So you could create a template that includes payments using the DocuSign web tool, then create an envelope via SOAP that uses the template.

If you want to include the specific payment tag via SOAP, that might be problematic since the tag is not in the WSDL. There is no plan to update the WSDL.

If you can create the SOAP message manually, you could try to add the payment tag. See workflow example 14. Here is the Java version.

ContentLicense: CC BY-SA 4.0


问:
MySQL performance tuning for DELETE query
Can any one help me to re-write the query to speed up the execution time? It took 37 seconds to execute.

```<code>DELETE FROM storefront_categories
WHERE userid IN (SELECT userid
                FROM MASTER
                where expirydate<'2020-2-4'
                )
</code>```

At the same time, this query took only 4.69 seconds only to execute.

```<code>DELETE FROM storefront_categories
WHERE userid NOT IN (SELECT userid FROM MASTER)
</code>```

The table storefront_categories have 97K records where as in MASTER have 40K records. We have created a index on MASTER.expirydate field.

答:
I would try with exists :

```<code>DELETE
FROM storefront_categories
WHERE EXISTS (SELECT 1
              FROM MASTER M
              WHERE M.userid = storefront_categories.userid AND
                    M.expirydate <'2020-02-04'
              );
</code>```

Index would be metter here i would expect index on storefront_categories(userid) & MASTER(userid, expirydate).

Body:
Can any one help me to re-write the query to speed up the execution time? It took 37 seconds to execute.

DELETE FROM storefront_categories
WHERE userid IN (SELECT userid
                FROM MASTER
                where expirydate<'2020-2-4'
                )

At the same time, this query took only 4.69 seconds only to execute.

DELETE FROM storefront_categories
WHERE userid NOT IN (SELECT userid FROM MASTER)

The table storefront_categories have 97K records where as in MASTER have 40K records. We have created a index on MASTER.expirydate field.

Body:
I would try with exists :

DELETE
FROM storefront_categories
WHERE EXISTS (SELECT 1
              FROM MASTER M
              WHERE M.userid = storefront_categories.userid AND
                    M.expirydate <'2020-02-04'
              );

Index would be metter here i would expect index on storefront_categories(userid) & MASTER(userid, expirydate).


问:
Python: Object to list of tuples extraction
I have an object in the following format:

```<code>{
  'af': {
    'bidi': False,
    'code': 'af',
    'name': 'Afrikaans',
    'name_local': 'Afrikaans'
  },
  'ar': {
    'bidi': True,
    'code': 'ar',
    'name': 'Arabic',
    'name_local': 'العربيّة'
  },
  ...
}
</code>```

This is a list of locales as found in django.conf.locale.LANG_INFO. (see here for full reference: https://github.com/django/django/blob/master/django/conf/locale/init.py).

Now, I am hoping to utilise this list in a model class:

```<code>locale = models.CharField(max_length=5, choices=get_locale_choices(), default='en')
</code>```

Such that I have the following utility function:

```<code>from django.conf.locale import LANG_INFO

def get_locale_choices():
    return ?
</code>```

Now, that ? that gets returned, I'd like to be in the following format:

```<code>[
    ('af', 'Afrikaans'),
    ('ar', 'Arabic'),
    ...
]
</code>```

My question is this, how would I turn the LANG_INFO dictionary into the above list of tuples?

It feels like something like this is close:

```<code>a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
d_items = a_dict.items()
d_items  # Here d_items is a view of items
dict_items([('color', 'blue'), ('fruit', 'apple'), ('pet', 'dog')])
</code>```

But...hmmm, not sure? I want to extract a sub-value from the key item...

答:
Use list comprehension:

```<code>from django.conf.locale import LANG_INFO

def get_locale_choices():
    return [(k, v['name']) for k, v in LANG_INFO.items() if 'name' in v]
</code>```

The ... if 'name' in v part is necessary to ensure that the cases that have a 'fallback' but no 'name' (e.g. zh-cn, zh-my, zh-sg, etc.) are ignored.

Result:

```<code>[('af', 'Afrikaans'), ('ar', 'Arabic'), ...]
</code>```

Note: django.conf.locale.LANG_INFO seems to be internal to Django, so your use of it isn't officially sanctioned by Django.

Body:
I have an object in the following format:

{
  'af': {
    'bidi': False,
    'code': 'af',
    'name': 'Afrikaans',
    'name_local': 'Afrikaans'
  },
  'ar': {
    'bidi': True,
    'code': 'ar',
    'name': 'Arabic',
    'name_local': 'العربيّة'
  },
  ...
}

This is a list of locales as found in django.conf.locale.LANG_INFO. (see here for full reference: https://github.com/django/django/blob/master/django/conf/locale/init.py).

Now, I am hoping to utilise this list in a model class:

locale = models.CharField(max_length=5, choices=get_locale_choices(), default='en')

Such that I have the following utility function:

from django.conf.locale import LANG_INFO

def get_locale_choices():
    return ?

Now, that ? that gets returned, I'd like to be in the following format:

[
    ('af', 'Afrikaans'),
    ('ar', 'Arabic'),
    ...
]

My question is this, how would I turn the LANG_INFO dictionary into the above list of tuples?

It feels like something like this is close:

a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
d_items = a_dict.items()
d_items  # Here d_items is a view of items
dict_items([('color', 'blue'), ('fruit', 'apple'), ('pet', 'dog')])

But...hmmm, not sure? I want to extract a sub-value from the key item...

Body:
Use list comprehension:

from django.conf.locale import LANG_INFO

def get_locale_choices():
    return [(k, v['name']) for k, v in LANG_INFO.items() if 'name' in v]

The ... if 'name' in v part is necessary to ensure that the cases that have a 'fallback' but no 'name' (e.g. zh-cn, zh-my, zh-sg, etc.) are ignored.

Result:

[('af', 'Afrikaans'), ('ar', 'Arabic'), ...]

Note: django.conf.locale.LANG_INFO seems to be internal to Django, so your use of it isn't officially sanctioned by Django.


问:
how to make chart using data from database?
HI
i am making a window application using visual studio 2010 and vb.net. i want to make charts daynimacilly using data from the database. how this can be done?

thanks
Yatin

答: Microsoft has a set of charting controls that you can download for free.  There are extensive sample applications in both c# and vb.net for ASP.Net and Windows Forms that come packaged with the controls.  You should be able to find what you need.</p>

ContentLicense: CC BY-SA 3.0


问:
Download pdf files from external url's - Heroku, NodeJS, Angular 7
I am trying to download multiple pdf files from external sources to my nodejs server (in Heroku) temporarily and upload it to AWS S3 bucket.

I have tried multiple methods all of which works fine in my local machine but not in Heroku Dyno NodeJS Server. I am unable to even create folder in Heroku. I guess due to limited permission.

In Node

1) using var download = require('download-file') (using this currently in below code)

2) axios

3) res.download()

Download Files Code

```<code>const downloadFiles = async (unique_files) =>  {

  for (let index = 0; index < unique_files.length; index++) {
    let file_ext = unique_files[index].substr(unique_files[index].length - 4);
      if(file_ext == ".pdf") {
        await downloadzz(unique_files[index])
      }
  }

}

function downloadzz(link) {
  download(link, function(err){
    if (err) throw err
    console.log("DOWNLOAD Complete");

  });
}
</code>```

Upload Files Code

```<code>const uploadFiles = async (unique_files) =>  {

  for (let index = 0; index < unique_files.length; index++) {
    let file_ext = unique_files[index].substr(unique_files[index].length - 4);
      if(file_ext == ".pdf") {
        await uploadzz(unique_files[index])
      }
  }
}

function uploadzz(link) {
    fs.readFile(require('path').resolve(__dirname+'/../external-pdfs/', link.slice(link.lastIndexOf('/') + 1)), function (err, data) {

    params = {Bucket: pdfBucket, Key: link.slice(link.lastIndexOf('/') + 1), Body: data, ACL: "public-read" };
    s3.putObject(params, function(err, data) {
        if (err) {
            console.log("Failed Upload", err);
        } else {
            console.log("Successfully uploaded data to bucket", data);
        }
    });

  });
}
</code>```

I don't get any error but no folder seem to exist with a name external-pdfs on heroku server.

I am open for better solutions: for example, directly uploading file from external url to s3...
How can I in read file from a external url and directly upload to AWS S3 bucket?

答:
In Angular, we can use FileSaver library to save the pdf file from library.

Find the below sample code to do this way.
enter image description here

Body:
I am trying to download multiple pdf files from external sources to my nodejs server (in Heroku) temporarily and upload it to AWS S3 bucket.

I have tried multiple methods all of which works fine in my local machine but not in Heroku Dyno NodeJS Server. I am unable to even create folder in Heroku. I guess due to limited permission.

In Node

1) using var download = require('download-file') (using this currently in below code)

2) axios

3) res.download()

Download Files Code

const downloadFiles = async (unique_files) =>  {

  for (let index = 0; index < unique_files.length; index++) {
    let file_ext = unique_files[index].substr(unique_files[index].length - 4);
      if(file_ext == ".pdf") {
        await downloadzz(unique_files[index])
      }
  }

}

function downloadzz(link) {
  download(link, function(err){
    if (err) throw err
    console.log("DOWNLOAD Complete");

  });
}

Upload Files Code

const uploadFiles = async (unique_files) =>  {

  for (let index = 0; index < unique_files.length; index++) {
    let file_ext = unique_files[index].substr(unique_files[index].length - 4);
      if(file_ext == ".pdf") {
        await uploadzz(unique_files[index])
      }
  }
}

function uploadzz(link) {
    fs.readFile(require('path').resolve(__dirname+'/../external-pdfs/', link.slice(link.lastIndexOf('/') + 1)), function (err, data) {

    params = {Bucket: pdfBucket, Key: link.slice(link.lastIndexOf('/') + 1), Body: data, ACL: "public-read" };
    s3.putObject(params, function(err, data) {
        if (err) {
            console.log("Failed Upload", err);
        } else {
            console.log("Successfully uploaded data to bucket", data);
        }
    });

  });
}

I don't get any error but no folder seem to exist with a name external-pdfs on heroku server.

I am open for better solutions: for example, directly uploading file from external url to s3...
How can I in read file from a external url and directly upload to AWS S3 bucket?


问:
Cordova android volume/up button event on release not press
Seeing a strange (unwanted) behaviour on a ZTE A112 Android 6 with our very simple Cordova app, which is currently just listening for volumedown/volumeup events.  Registered the listeners after ondeviceready.  The event is firing on release of the appropriate button, not on press (which is what we need).  Can't seem to get to the bottom of it.

after ondeviceready:

```<code>document.addEventListener('volumeupbutton', volumeUpKeyHandler, false);
document.addEventListener('volumedownbutton', volumeDownKeyHandler, false);
</code>```

Going to try on other brand phones and see if it follows or it's a handset specific thing.  If anyone has seen this before or any clues it would be very much appreciated.

答:
As of Feb 2020 Cordova for Android still doesn't support this.

Here are the necessary changes to make this work: https://github.com/trullock/launch-pad/commit/244d67971063203491434bbd03cf91a0493eb04f

This hasn't been rigorously tested, and it's only the Android implementation.

Better than nothing!

Body:
Seeing a strange (unwanted) behaviour on a ZTE A112 Android 6 with our very simple Cordova app, which is currently just listening for volumedown/volumeup events.  Registered the listeners after ondeviceready.  The event is firing on release of the appropriate button, not on press (which is what we need).  Can't seem to get to the bottom of it.

after ondeviceready:

document.addEventListener('volumeupbutton', volumeUpKeyHandler, false);
document.addEventListener('volumedownbutton', volumeDownKeyHandler, false);

Going to try on other brand phones and see if it follows or it's a handset specific thing.  If anyone has seen this before or any clues it would be very much appreciated.


问:
Python Concatenation and Sort 3 Dataframes
I am doing concat on three dataframes, doing code like this:

```<code>df_bigram = pd.concat([bigramFreqTable, skipgram, df2],axis=1)
df_bigram
</code>```

And the output of df_bigram is

```<code>                      bigramf   freq           Skipgram   Freq                         bigram          PMI
0  (Asam, deoksiribonukleat,)      1      (unting, DNA)    22                        (12, Å.)    11.487338
1 (deoksiribonukleat,, lebih)      1      (DNA, unting)    22                        (22, Å,)    11.487338
2            (lebih, dikenal)      1        (DNA, yang)    20                     (220, juta)    11.487338
3           (dikenal, dengan)      2        (yang, DNA)    20                 (34, ÅngströmÅ)    11.487338
4         (dengan, singkatan)      1       (DNA, dalam)    13                (A-DNA,, B-DNA,)    11.487338
5            (singkatan, DNA)      1       (dalam, DNA)    13   (Akibatnya,, protein-protein)    11.487338
6                    (DNA, ,)      2   (pasangan, basa)    11                (Alec, Jeffreys)    11.487338
7                 (,, adalah)      1   (basa, pasangan)    11        (Alfred, HersheyHershey)    11.487338
8           (adalah, sejenis)      1    (terdiri, dari)    10      (Asam, deoksiribonukleat,)    11.487338
9       (sejenis, biomolekul)      1    (dari, terdiri)    10            (Bacillus, subtilis)    11.487338
10         (biomolekul, yang)      1        (pada, DNA)    10            (Banyak, yurisdiksi)    11.487338
...            ...                ...          ...         ...               ...                  ...
</code>```

The problem is I want to sort 'freq' by descending value. I just confused why the other column name like 'Freq' and 'PMI', they have been sorted by descending value, meanwhile 'freq' haven't been. So, I am coding this for sorting:

```<code>x = df_bigram.sort_values(by='freq', ascending=False)
x
</code>```

And the output be like this:

```<code>                bigramf   freq             Skipgram   Freq                      bigram          PMI
72        (unting, DNA)    17    (hidrogen, ikatan)     5     (ditranskripsikan., Para)    11.487338
212         (DNA, yang)    15          (satu, pada)     3           (Temperatur, lebur)    10.487338
136    (pasangan, basa)    10          (dalam, ===)     4              (myeloid, akut.)    11.487338
83      (yang, disebut)     9      (rantai, Proses)     5             (gen., Sedangkan)    11.487338
432  (disebut, sebagai)     9     (unting, disebut)     2           (sama., Karenanya,)     9.902375
58      (terdiri, dari)     9       (DNA, memiliki)     6             (darah,, sperma,)    11.487338
525          (Hal, ini)     8       (disebut, satu)     2          (resisten, terhadap)     9.487338
888     (heliks, ganda)     7    (tergulung, lebih)     2         (banyak, kemungkinan)     7.902375
657       (rantai, DNA)     7      (Diplonema, dan)     2                (sebuah, cara)     8.902375
...          ...           ...            ...          ...                 ...                ...
</code>```

while actually I want to sort all of the column name like 'freq', 'Freq', 'PMI' by descending value. What am I doing wrong?

答:
Problem is if sorting in final joined column is not possible sorting only pairs bigrams columns and freq, possible solution is sorting first and mainly create default index by DataFrame.reset_index with drop=True:

```<code>df1 = bigramFreqTable.sort_values(by='freq', ascending=False).reset_index(drop=True)
df2 = skipgram.sort_values(by='Freq', ascending=False).reset_index(drop=True)
df3 = df2.sort_values(by='PMI', ascending=False).reset_index(drop=True)

df_bigram = pd.concat([df1, df2, df3],axis=1)
</code>```

Body:
I am doing concat on three dataframes, doing code like this:

df_bigram = pd.concat([bigramFreqTable, skipgram, df2],axis=1)
df_bigram

And the output of df_bigram is

                      bigramf   freq           Skipgram   Freq                         bigram          PMI
0  (Asam, deoksiribonukleat,)      1      (unting, DNA)    22                        (12, Å.)    11.487338
1 (deoksiribonukleat,, lebih)      1      (DNA, unting)    22                        (22, Å,)    11.487338
2            (lebih, dikenal)      1        (DNA, yang)    20                     (220, juta)    11.487338
3           (dikenal, dengan)      2        (yang, DNA)    20                 (34, ÅngströmÅ)    11.487338
4         (dengan, singkatan)      1       (DNA, dalam)    13                (A-DNA,, B-DNA,)    11.487338
5            (singkatan, DNA)      1       (dalam, DNA)    13   (Akibatnya,, protein-protein)    11.487338
6                    (DNA, ,)      2   (pasangan, basa)    11                (Alec, Jeffreys)    11.487338
7                 (,, adalah)      1   (basa, pasangan)    11        (Alfred, HersheyHershey)    11.487338
8           (adalah, sejenis)      1    (terdiri, dari)    10      (Asam, deoksiribonukleat,)    11.487338
9       (sejenis, biomolekul)      1    (dari, terdiri)    10            (Bacillus, subtilis)    11.487338
10         (biomolekul, yang)      1        (pada, DNA)    10            (Banyak, yurisdiksi)    11.487338
...            ...                ...          ...         ...               ...                  ...

The problem is I want to sort 'freq' by descending value. I just confused why the other column name like 'Freq' and 'PMI', they have been sorted by descending value, meanwhile 'freq' haven't been. So, I am coding this for sorting:

x = df_bigram.sort_values(by='freq', ascending=False)
x

And the output be like this:

                bigramf   freq             Skipgram   Freq                      bigram          PMI
72        (unting, DNA)    17    (hidrogen, ikatan)     5     (ditranskripsikan., Para)    11.487338
212         (DNA, yang)    15          (satu, pada)     3           (Temperatur, lebur)    10.487338
136    (pasangan, basa)    10          (dalam, ===)     4              (myeloid, akut.)    11.487338
83      (yang, disebut)     9      (rantai, Proses)     5             (gen., Sedangkan)    11.487338
432  (disebut, sebagai)     9     (unting, disebut)     2           (sama., Karenanya,)     9.902375
58      (terdiri, dari)     9       (DNA, memiliki)     6             (darah,, sperma,)    11.487338
525          (Hal, ini)     8       (disebut, satu)     2          (resisten, terhadap)     9.487338
888     (heliks, ganda)     7    (tergulung, lebih)     2         (banyak, kemungkinan)     7.902375
657       (rantai, DNA)     7      (Diplonema, dan)     2                (sebuah, cara)     8.902375
...          ...           ...            ...          ...                 ...                ...

while actually I want to sort all of the column name like 'freq', 'Freq', 'PMI' by descending value. What am I doing wrong?

Body:
Problem is if sorting in final joined column is not possible sorting only pairs bigrams columns and freq, possible solution is sorting first and mainly create default index by DataFrame.reset_index with drop=True:

df1 = bigramFreqTable.sort_values(by='freq', ascending=False).reset_index(drop=True)
df2 = skipgram.sort_values(by='Freq', ascending=False).reset_index(drop=True)
df3 = df2.sort_values(by='PMI', ascending=False).reset_index(drop=True)

df_bigram = pd.concat([df1, df2, df3],axis=1)


问:
Is there a simpler function or one liner to check if folder exists if not create it and paste a specific file into it?
I am aiming to create a function that does the following:

Declare a path with a file, not just a folder. e.g. 'C:/Users/Lampard/Desktop/Folder1/File.py'

Create a folder in same folder as the declared file path - Calling it 'Archive'

Cut the file and paste it into the new folder just created.

If the folder 'Archive' already exists - then simply cut and paste the file into there

I have spent approx. 15-20min going through these:

https://www.programiz.com/python-programming/directory

Join all except last x in list

https://docs.python.org/3/library/pathlib.html#operators

And here is what I got to:

```<code>import os
from pathlib import Path, PurePath
from shutil import copy

#This path will change every time - just trying to get function right first
path = 'C:/Users/Lampard/Desktop/Folder1/File.py'

#Used to allow suffix function
p = PurePath(path)

#Check if directory is a file not a folder
if not p.suffix:
    print("Not an extension")

#If it is a file
else:
    #Create new folder before last file
    #Change working directory
    split = path.split('/')
    new_directory = '/'.join(split[:-1])
    apply_new_directory = os.chdir(new_directory)
    #If folder does not exist create it
    try:
        os.mkdir('Archive')#Create new folder
    #If not, continue process to copy file and paste it into Archive
    except FileExistsError:
        copy(path, new_directory + '/Archive/' + split[-1])
</code>```

Is this code okay? - does anyone know a simpler method?

答:
As you're already using pathlib, there's no need to use shutil:

```<code>from pathlib import Path
path = 'C:/Users/Lampard/Desktop/Folder1/File.py' # or whatever
p = Path(path)
target = Path(p.with_name('Archive')) # replace the filename with 'Archive'
target.mkdir()                        # create target directory
p.rename(target.joinpath(p.name))     # move the file to the target directory
</code>```

Feel free to add appriopriate try…except statements to handle any errors.

Update: you might find this version more readable:

```<code>target = p.parent / 'Archive'
target.mkdir()
p.rename(target / p.name)
</code>```

This is an example of overloading / operator.

Body:
I am aiming to create a function that does the following:

Declare a path with a file, not just a folder. e.g. 'C:/Users/Lampard/Desktop/Folder1/File.py'

Create a folder in same folder as the declared file path - Calling it 'Archive'

Cut the file and paste it into the new folder just created.

If the folder 'Archive' already exists - then simply cut and paste the file into there

I have spent approx. 15-20min going through these:

https://www.programiz.com/python-programming/directory

Join all except last x in list

https://docs.python.org/3/library/pathlib.html#operators

And here is what I got to:

import os
from pathlib import Path, PurePath
from shutil import copy

#This path will change every time - just trying to get function right first
path = 'C:/Users/Lampard/Desktop/Folder1/File.py'

#Used to allow suffix function
p = PurePath(path)

#Check if directory is a file not a folder
if not p.suffix:
    print("Not an extension")

#If it is a file
else:
    #Create new folder before last file
    #Change working directory
    split = path.split('/')
    new_directory = '/'.join(split[:-1])
    apply_new_directory = os.chdir(new_directory)
    #If folder does not exist create it
    try:
        os.mkdir('Archive')#Create new folder
    #If not, continue process to copy file and paste it into Archive
    except FileExistsError:
        copy(path, new_directory + '/Archive/' + split[-1])

Is this code okay? - does anyone know a simpler method?

Body:
As you're already using pathlib, there's no need to use shutil:

from pathlib import Path
path = 'C:/Users/Lampard/Desktop/Folder1/File.py' # or whatever
p = Path(path)
target = Path(p.with_name('Archive')) # replace the filename with 'Archive'
target.mkdir()                        # create target directory
p.rename(target.joinpath(p.name))     # move the file to the target directory

Feel free to add appriopriate try…except statements to handle any errors.

Update: you might find this version more readable:

target = p.parent / 'Archive'
target.mkdir()
p.rename(target / p.name)

This is an example of overloading / operator.


问:
What code should I surround with run(){}?
I finished a 2000-line Swing + SQL program and I'd like to add to it a login window before everything is initialized. The login window is a JFrame class, instanced from the main program.

So my main app needs to implement Runnable. All I want with the thread I'm creating out of it is waiting -with wait()- until the login thread finishes -and uses notify()-.

My program consist of dozens of visual components, methods, main(), constructor, initializer, etc. What's the minimum amount of code I should surround with run(){}?

This is an example of what I want to do. It's not by any means correct (I suppose) but you'll get it:

```<code>private void initialize() { // Called from main()

    this.setBounds(100, 200, 1024, 576);
    this.setTitle("Main app");
    this.setVisible(false);

    Runnable runnable = new Visual_Login();
    Thread login_thread = new Thread(runnable);

    login_thread.run();
    main_thread.wait();

    this.setVisible(true);
    this.setContentPane(getJContentPane());

}
</code>```

(...I hope I'm understanding concurrency well)

Thank you in advance.

答:
Not sure if I get what you want to achieve but ... if you want run initialize in background then you need:

```<code> Runnable doInit = new Runnable() {
     public void run() {
        component.initialize()
     }
 };
</code>```

To run it you can optionally do:

```<code>// if you are running a swing UI and you want the dispatcher to handle the thread.
SwingUtilities.invokeLater(doInit);
</code>```

or

```<code>//if you want to start the thread yourself.
Thread t = new Thread(doInit);
t.start()
</code>```

... can't really go further than this because the rest really depends on your logic.

And just to finish, it is not worth to use a thread here unless your initialize method does something that takes considerable amount of time freezing the rest of the app. It doesn't seem that initialize is doing anything but to set some SWING properties.

Body:
I finished a 2000-line Swing + SQL program and I'd like to add to it a login window before everything is initialized. The login window is a JFrame class, instanced from the main program.

So my main app needs to implement Runnable. All I want with the thread I'm creating out of it is waiting -with wait()- until the login thread finishes -and uses notify()-.

My program consist of dozens of visual components, methods, main(), constructor, initializer, etc. What's the minimum amount of code I should surround with run(){}?

This is an example of what I want to do. It's not by any means correct (I suppose) but you'll get it:

private void initialize() { // Called from main()

    this.setBounds(100, 200, 1024, 576);
    this.setTitle("Main app");
    this.setVisible(false);

    Runnable runnable = new Visual_Login();
    Thread login_thread = new Thread(runnable);

    login_thread.run();
    main_thread.wait();

    this.setVisible(true);
    this.setContentPane(getJContentPane());

}

(...I hope I'm understanding concurrency well)

Thank you in advance.

Body:
Not sure if I get what you want to achieve but ... if you want run initialize in background then you need:

 Runnable doInit = new Runnable() {
     public void run() {
        component.initialize()
     }
 };

To run it you can optionally do:

// if you are running a swing UI and you want the dispatcher to handle the thread.
SwingUtilities.invokeLater(doInit);

or

//if you want to start the thread yourself.
Thread t = new Thread(doInit);
t.start()

... can't really go further than this because the rest really depends on your logic.

And just to finish, it is not worth to use a thread here unless your initialize method does something that takes considerable amount of time freezing the rest of the app. It doesn't seem that initialize is doing anything but to set some SWING properties.


问:
Plotting relationship between categorcial variable and Datetime
Consider a dataframe

```<code>some_id  timestamp
  a         1.2.2019
  b         2.2.2019
  c         3.2.2019
  a         4.2.2019
  b         5.2.2019
</code>```

Now you can see there are 3 unique ids and among that a and b is associated with 2 timestamps , I want ids to come on x axis and blocks of dates on y axis. How can this be done ? Thank you for your patience. I want this in python using matplotlib or seaborn or any other visualization library. I also appreciate if you can mention a different way of meaningful visualization between these two variables. I  want the figure to look like this below.

答:
Here is a way to visualize the data with the id's on the x-axis and the dates on the y-axis. Supposing your dates are in the format day.month.year.

With ax.text you can put text inside the bars, either the date or an other column of interest.

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
import pandas as pd

def timestr_to_num(timestr):
    print(datetime.strptime(timestr, '%d.%m.%Y'))
    return mdates.date2num(datetime.strptime(timestr, '%d.%m.%Y'))

rows = [['a', '1.2.2019'],
        ['b', '2.2.2019'],
        ['c', '3.2.2019'],
        ['a', '4.2.2019'],
        ['b', '5.2.2019']]
columns = ['some_id', 'timestamp']
df = pd.DataFrame(data=rows, columns=columns)

fig, ax = plt.subplots(figsize=(10, 5))

xs = list(df['some_id'].unique())
for row in df.itertuples():
    x = xs.index( row.some_id)
    y = timestr_to_num(row.timestamp)
    ax.barh(y, left=x-0.5, width=1, height=1)
    ax.text(x, y, row.timestamp, ha='center', va='center', color='white', fontsize=16)
ax.yaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%Y'))
ax.yaxis.set_major_locator(mdates.DayLocator(interval=1))  # set a tick every hour
ax.set_xlabel('some_id')
ax.set_ylabel('timestamp')
ax.set_xticks(range(len(xs)))
ax.set_xticklabels(xs)

plt.tight_layout()
plt.show()
```

<p><img src="https://i.stack.imgur.com/TEdvl.png" alt="example plot"></p>

<p>Another idea could be:</p>

```df.sort_values(by=['some_id', 'timestamp']).groupby(['some_id', 'timestamp']).size().unstack().plot(kind='bar', stacked=True)
```

But then the dates are in a legend, which might not be suitable if the list is too long.

Body:
Consider a dataframe

some_id  timestamp
  a         1.2.2019
  b         2.2.2019
  c         3.2.2019
  a         4.2.2019
  b         5.2.2019

Now you can see there are 3 unique ids and among that a and b is associated with 2 timestamps , I want ids to come on x axis and blocks of dates on y axis. How can this be done ? Thank you for your patience. I want this in python using matplotlib or seaborn or any other visualization library. I also appreciate if you can mention a different way of meaningful visualization between these two variables. I  want the figure to look like this below.

Body:
Here is a way to visualize the data with the id's on the x-axis and the dates on the y-axis. Supposing your dates are in the format day.month.year.

With ax.text you can put text inside the bars, either the date or an other column of interest.

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
import pandas as pd

def timestr_to_num(timestr):
    print(datetime.strptime(timestr, '%d.%m.%Y'))
    return mdates.date2num(datetime.strptime(timestr, '%d.%m.%Y'))

rows = [['a', '1.2.2019'],
        ['b', '2.2.2019'],
        ['c', '3.2.2019'],
        ['a', '4.2.2019'],
        ['b', '5.2.2019']]
columns = ['some_id', 'timestamp']
df = pd.DataFrame(data=rows, columns=columns)

fig, ax = plt.subplots(figsize=(10, 5))

xs = list(df['some_id'].unique())
for row in df.itertuples():
    x = xs.index( row.some_id)
    y = timestr_to_num(row.timestamp)
    ax.barh(y, left=x-0.5, width=1, height=1)
    ax.text(x, y, row.timestamp, ha='center', va='center', color='white', fontsize=16)
ax.yaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%Y'))
ax.yaxis.set_major_locator(mdates.DayLocator(interval=1))  # set a tick every hour
ax.set_xlabel('some_id')
ax.set_ylabel('timestamp')
ax.set_xticks(range(len(xs)))
ax.set_xticklabels(xs)

plt.tight_layout()
plt.show()

Another idea could be:

df.sort_values(by=['some_id', 'timestamp']).groupby(['some_id', 'timestamp']).size().unstack().plot(kind='bar', stacked=True)

But then the dates are in a legend, which might not be suitable if the list is too long.


问:
Firebase simple query gives error: "Converting circular structure to JSON at JSON.stringify"
I'm trying to loop through a /users path and join it to my auth().listUsers result however this code:

https://github.com/QuantumInformation/svelte-fullstack-starter/blob/master/firebase_specific/functions/src/users.ts#L32

export async function getSomeUsers(amount: number) {
    try {
        const listUsersResult = await admin.auth().listUsers(amount)
        const parsedUsers = listUsersResult.users.map(stripUserSensitiveInfo).map(async user => {
            console.log("try read_______________" + user.uid)
            let userProfileSnapshot = await admin
                .database()
                .ref("users/" + user.uid)
                .once("value")

            console.log("end try read_______________" + user.uid)
            return { ...user, userProfileSnapshot }
        })

        return parsedUsers
    } catch (error) {
        console.error("Error listing users:", error)
        throw new Error("Error users" + error)
    }
}

```

<p>gives this error</p>

<blockquote>
  <p>Converting circular structure to JSON at JSON.stringify () at stringify </p>
</blockquote>

<p>but this code works fine</p>

<pre class="lang-js prettyprint-override"><code>export async function getSomeUsers(amount: number) {
    try {
        const listUsersResult = await admin.auth().listUsers(amount)

        const parsedUsers = listUsersResult.users.map(stripUserSensitiveInfo).map( user => {

            return 1
        })

        return parsedUsers
    } catch (error) {
        console.error("Error listing users:", error)
        throw new Error("Error users" + error)
    }
}
</code>```

答:
You cannot use it like this. For your second map function, it will return an array of promises. So, you will have to keep all the promises and then use Promise.all to resolve them.

```<code>return Promise.all(parsedUsers);
</code>```

Body:
I'm trying to loop through a /users path and join it to my auth().listUsers result however this code:

https://github.com/QuantumInformation/svelte-fullstack-starter/blob/master/firebase_specific/functions/src/users.ts#L32

export async function getSomeUsers(amount: number) {
    try {
        const listUsersResult = await admin.auth().listUsers(amount)
        const parsedUsers = listUsersResult.users.map(stripUserSensitiveInfo).map(async user => {
            console.log("try read_______________" + user.uid)
            let userProfileSnapshot = await admin
                .database()
                .ref("users/" + user.uid)
                .once("value")

            console.log("end try read_______________" + user.uid)
            return { ...user, userProfileSnapshot }
        })

        return parsedUsers
    } catch (error) {
        console.error("Error listing users:", error)
        throw new Error("Error users" + error)
    }
}

gives this error

Converting circular structure to JSON at JSON.stringify () at stringify

but this code works fine

export async function getSomeUsers(amount: number) {
    try {
        const listUsersResult = await admin.auth().listUsers(amount)

        const parsedUsers = listUsersResult.users.map(stripUserSensitiveInfo).map( user => {

            return 1
        })

        return parsedUsers
    } catch (error) {
        console.error("Error listing users:", error)
        throw new Error("Error users" + error)
    }
}

Body:
You cannot use it like this. For your second map function, it will return an array of promises. So, you will have to keep all the promises and then use Promise.all to resolve them.

return Promise.all(parsedUsers);


问:
How to fix os.path error in windows machine?
I am trying to write a function that will send email with or without attachment based on the attachment file input but its failing with file not found error.

Here is my function

```<code>def sendEmail(TO, FROM, SUBJECT, BODY, *FILETOSEND):
"""Function to send email"""

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart("alternative")
msg["Subject"] = SUBJECT
msg["From"] = FROM
msg["To"] = TO

if FILETOSEND:
    file_string = str(FILETOSEND)

    finalFile = file_string[1 : len(file_string) - 2]

    fp = open(finalFile)
    attachment = MIMEText(fp.read())
    fp.close()
    attachment.add_header("Content-Disposition", "attachment", filename=fp)
    msg.attach(attachment)

# Create the body of the message
text = BODY
part1 = MIMEText(text, "plain")
msg.attach(part1)

# Send the message via local SMTP server.
s = smtplib.SMTP("smtpservername")
s.sendmail(msg["From"], msg["To"], msg.as_string())
s.quit()
</code>```

fileToSend = r"C:\Users\n123456\Desktop\DomainFolder\D1\NEWDATASET.txt"
sendEmail(TO, FROM, SUBJECT, BODY, *FILETOSEND)

I have passed all the arguments without filetosend and it worked but when passing with fileToSend its failing with OSerror

```<code>OSError: [Errno 22] Invalid argument:
"'C:\\\\Users\\\\n123456\\\\Desktop\\\\DomainFolder\\\\D1\\\\NEWDATASET.txt'"
</code>```

I have tested with placing file in different directory and drive also with putting forward slash but still same issue.
As *FILETOSEND will return tuple I am trying string manipulation to make it correct path but no luck.
I am using windows 10 with Python 3.8. Seeking help.

答:
Try to use path like this </p>

```<code>open(r"C:\Users\n123456\Desktop\DomainFolder\D1\NEWDATASET.txt","r")
</code>```

Body:
I am trying to write a function that will send email with or without attachment based on the attachment file input but its failing with file not found error.

Here is my function

def sendEmail(TO, FROM, SUBJECT, BODY, *FILETOSEND):
"""Function to send email"""

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart("alternative")
msg["Subject"] = SUBJECT
msg["From"] = FROM
msg["To"] = TO

if FILETOSEND:
    file_string = str(FILETOSEND)

    finalFile = file_string[1 : len(file_string) - 2]

    fp = open(finalFile)
    attachment = MIMEText(fp.read())
    fp.close()
    attachment.add_header("Content-Disposition", "attachment", filename=fp)
    msg.attach(attachment)

# Create the body of the message
text = BODY
part1 = MIMEText(text, "plain")
msg.attach(part1)

# Send the message via local SMTP server.
s = smtplib.SMTP("smtpservername")
s.sendmail(msg["From"], msg["To"], msg.as_string())
s.quit()

fileToSend = r"C:\Users\n123456\Desktop\DomainFolder\D1\NEWDATASET.txt"
sendEmail(TO, FROM, SUBJECT, BODY, *FILETOSEND)

I have passed all the arguments without filetosend and it worked but when passing with fileToSend its failing with OSerror

OSError: [Errno 22] Invalid argument:
"'C:\\\\Users\\\\n123456\\\\Desktop\\\\DomainFolder\\\\D1\\\\NEWDATASET.txt'"

I have tested with placing file in different directory and drive also with putting forward slash but still same issue.
As *FILETOSEND will return tuple I am trying string manipulation to make it correct path but no luck.
I am using windows 10 with Python 3.8. Seeking help.

Body:
Try to use path like this

open(r"C:\Users\n123456\Desktop\DomainFolder\D1\NEWDATASET.txt","r")


问:
ERROR: Failed to resolve: com.google.android.gms:play-services-ads:18.3.0
While syncing the project after added play-services-ads, I am always getting this error "failed to resolve play-services-ads".

build.gradle at project level

```<code>    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath 'com.google.gms:google-services:4.3.3'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}
</code>```

build.gradle at app level

```<code>dependencies {
   implementation 'androidx.media:media:1.0.1'
   implementation 'com.google.ads.interactivemedia.v3:interactivemedia:3.11.3'
   implementation 'com.google.android.gms:playservices-ads:18.3.0'
}
</code>```

答:
Add Maven repos in allprojects.

Project build file:

```<code>implementation 'com.google.android.gms:play-services-ads:18.3.0'
</code>```

Top level build file:

```<code>buildscript {
ext.kotlin_version = '1.3.50'
repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.5.3'
    classpath 'com.google.gms:google-services:4.3.3'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    google()
    jcenter()
    maven {
        url "https://maven.google.com"
    }
    maven {
        url "https://jitpack.io"
    }
}
}
</code>```

Body:
While syncing the project after added play-services-ads, I am always getting this error "failed to resolve play-services-ads".

build.gradle at project level

    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath 'com.google.gms:google-services:4.3.3'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

build.gradle at app level

dependencies {
   implementation 'androidx.media:media:1.0.1'
   implementation 'com.google.ads.interactivemedia.v3:interactivemedia:3.11.3'
   implementation 'com.google.android.gms:playservices-ads:18.3.0'
}

Body:
Add Maven repos in allprojects.

Project build file:

implementation 'com.google.android.gms:play-services-ads:18.3.0'

Top level build file:

buildscript {
ext.kotlin_version = '1.3.50'
repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.5.3'
    classpath 'com.google.gms:google-services:4.3.3'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    google()
    jcenter()
    maven {
        url "https://maven.google.com"
    }
    maven {
        url "https://jitpack.io"
    }
}
}


问:
Copy file (image) from CacheDir to SD Card
I want to be able to either move or copy a file from the internal Cache of an android device and put this into permanent storage on the SD Card. This is what I have so far:</p>

```<code>public void onClickSaveSecret(View v){

    File image = new File(getApplication().getCacheDir() + "/image.png");
    File newImage = new File(Environment.getExternalStorageDirectory() + "/image.png");

    Toast.makeText(this, "Image Saved", 100).show();

}
</code>```

答:
```<code>/**
 * copy file from source to destination
 *
 * @param src source
 * @param dst destination
 * @throws java.io.IOException in case of any problems
 */
void copyFile(File src, File dst) throws IOException {
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dst).getChannel();
    try {
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null)
            inChannel.close();
        if (outChannel != null)
            outChannel.close();
    }
}
</code>```

Body:
I want to be able to either move or copy a file from the internal Cache of an android device and put this into permanent storage on the SD Card. This is what I have so far:

public void onClickSaveSecret(View v){

    File image = new File(getApplication().getCacheDir() + "/image.png");
    File newImage = new File(Environment.getExternalStorageDirectory() + "/image.png");

    Toast.makeText(this, "Image Saved", 100).show();

}


问:
Dynamically create buttons in react native
I want to create a checkbox dynamically according to the data in API and then call the function inside my render function.

Can anyone suggest me any way, as I had used forEach but the data seem do not passed and hence I'm getting an error: forEach is undefined.

My snippet:

```<code>sizel=()=> this.state.data.sizes.forEach(function(size){
    <CheckBox
     title={size}
   checked=''
   />
 })
</code>```

答:
You need to add a validation before invoking forEach method, just like this:</p>

```<code>   sizel = () => this.state.data && this.state.data.sizes && this.state.data.sizes.forEach(function (size) {
    return (
      <CheckBox
        title={size}
        checked=''
      />
    )
  })
</code>```

Body:
I want to create a checkbox dynamically according to the data in API and then call the function inside my render function.

Can anyone suggest me any way, as I had used forEach but the data seem do not passed and hence I'm getting an error: forEach is undefined.

My snippet:

sizel=()=> this.state.data.sizes.forEach(function(size){
    <CheckBox
     title={size}
   checked=''
   />
 })

Body:
You need to add a validation before invoking forEach method, just like this:

   sizel = () => this.state.data && this.state.data.sizes && this.state.data.sizes.forEach(function (size) {
    return (
      <CheckBox
        title={size}
        checked=''
      />
    )
  })


问:
mongoose find collection by _id in a list of array
Here's my Schema

```<code>var PositiveSchema = new mongoose.Schema({
    schoolID: {
        type: mongoose.Schema.Types.ObjectId, ref: 'School'
    },
    name: String,
    restrictAwardTo: Object
})
</code>```

Now restrictAwardTo saves the data in this format

```<code>"restrictAwardTo" : [
        {
            "_id" : "5c31907d908eb8404657cbf0",
            "firstName" : "Admin 2a"
        },
        {
            "_id" : "5c1a7677c98da061141475a8",
            "firstName" : "Justice"
        },
        {
            "_id" : "5c1a7677c98da061141475a9",
            "firstName" : "Itik"
        }
    ],
</code>```

How can I search inside my document using one of the _id listed under restrictAwardTo? I tried the solutions given below

mongooseJS find docs with IDs in an array

mongoose query: find an object by id in an array but it returns empty.

in Robo3t db.getCollection('positives').find({ 'restrictAwardTo._id' : ObjectId('5c31907d908eb8404657cbf0') })

Update: In Robo3t, this query db.getCollection('positives').find({ 'restrictAwardTo._id' : {$in: ['5c1a7677c98da061141475a7']} }) works. Now I'm making it work for mongoose too.

答:
You could go through this way.</p>

```<code>Positive.findOne({'restrictAwardTo': {$elemMatch: {_id: userID}}},
        (err,schoolInfo) => { });
</code>```

Body:
Here's my Schema

var PositiveSchema = new mongoose.Schema({
    schoolID: {
        type: mongoose.Schema.Types.ObjectId, ref: 'School'
    },
    name: String,
    restrictAwardTo: Object
})

Now restrictAwardTo saves the data in this format

"restrictAwardTo" : [
        {
            "_id" : "5c31907d908eb8404657cbf0",
            "firstName" : "Admin 2a"
        },
        {
            "_id" : "5c1a7677c98da061141475a8",
            "firstName" : "Justice"
        },
        {
            "_id" : "5c1a7677c98da061141475a9",
            "firstName" : "Itik"
        }
    ],

How can I search inside my document using one of the _id listed under restrictAwardTo? I tried the solutions given below

mongooseJS find docs with IDs in an array

mongoose query: find an object by id in an array but it returns empty.

in Robo3t db.getCollection('positives').find({ 'restrictAwardTo._id' : ObjectId('5c31907d908eb8404657cbf0') })

Update: In Robo3t, this query db.getCollection('positives').find({ 'restrictAwardTo._id' : {$in: ['5c1a7677c98da061141475a7']} }) works. Now I'm making it work for mongoose too.

Body:
You could go through this way.

Positive.findOne({'restrictAwardTo': {$elemMatch: {_id: userID}}},
        (err,schoolInfo) => { });


问:
How to get the previous value of a node in firebase realtime database
I am sending a request to the firebase client SDK (JavaScript) which sends to the location of a vehicle in realtime..I get the following object

```<code>{
  "bearing": 264.8562316894531,
  "latitude": "19.9742249",
  "longitude": "73.7910482",
  "timestamp": "1582103153697",
  "trip": "40be478c-b0b0-41fb-bc70-66b2507719ef",
  "user": "1985"
}
</code>```

I want to be able to get the value before it changes so I can calculate the angle to rotate my marker(HEADING).

any help is appreciated

答:
By using one of the Firebase Client SDKs there is no out-of-the-box way to get the previous value of a given Realtime Database node when you write a new value to this node.

You will need to first read the node, by querying the database (in your case, I guess through a vehicle Id or a user Id), "storing" this value in your front end and then write the new value of the node to the Realtime Database.

You haven't given any detail on which kind of client/app you are developing for (Web? Android? iOS?) so it is impossible to give you more detail on how to implement this workflow/sequence.

Body:
I am sending a request to the firebase client SDK (JavaScript) which sends to the location of a vehicle in realtime..I get the following object

{
  "bearing": 264.8562316894531,
  "latitude": "19.9742249",
  "longitude": "73.7910482",
  "timestamp": "1582103153697",
  "trip": "40be478c-b0b0-41fb-bc70-66b2507719ef",
  "user": "1985"
}

I want to be able to get the value before it changes so I can calculate the angle to rotate my marker(HEADING).

any help is appreciated


问:
Remove Duplicate object from Array Deep Check
I have a array of objects, like:

```<code>[{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-a004-da0cda639065",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    }
  }
},
{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-2121-da0cda6390ae",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    }
  }
}]
</code>```

I want this array to be unique on the basis of offerId. If offerId is the same, then I want to remove that object from the array.

答:
It is possible to use reduce method. It checks whether there is a property with the same key and if it exists it creates a key, otherwise it does nothing:

```<code>arr.reduce((a, c)=> {
    a[c.productComponentAction.productComponent.offerId] =
        a[c.productComponentAction.productComponent.offerId] || {...c};
    return a;
}, {})
</code>```

An example:

let arr = [{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-a004-da0cda639065",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    }
  }
},
{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-2121-da0cda6390ae",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    }
  }
}];

let filteredList = arr.reduce((a, c)=> {
  a[c.productComponentAction.productComponent.offerId] =
      a[c.productComponentAction.productComponent.offerId] || {...c};
  return a;
}, {})

console.log(Object.values(filteredList));```

Body:
I have a array of objects, like:

[{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-a004-da0cda639065",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    }
  }
},
{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-2121-da0cda6390ae",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    }
  }
}]

I want this array to be unique on the basis of offerId. If offerId is the same, then I want to remove that object from the array.

Body:
It is possible to use reduce method. It checks whether there is a property with the same key and if it exists it creates a key, otherwise it does nothing:

arr.reduce((a, c)=> {
    a[c.productComponentAction.productComponent.offerId] =
        a[c.productComponentAction.productComponent.offerId] || {...c};
    return a;
}, {})

An example:

let arr = [{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-a004-da0cda639065",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    }
  }
},
{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-2121-da0cda6390ae",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    }
  }
}];

let filteredList = arr.reduce((a, c)=> {
  a[c.productComponentAction.productComponent.offerId] =
      a[c.productComponentAction.productComponent.offerId] || {...c};
  return a;
}, {})

console.log(Object.values(filteredList));


问:
Python write both commands and their output to a file
Is there any way to write both commands and their output to an external file?

Let's say I have a script outtest.py :

```<code>import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
d_median = round(median(d), 2)
print(f'median: {d_median}')
</code>```

Now if I want to capture its output only I know I can just do:

```<code>python3 outtest.py > outtest.txt
</code>```

However, this will only give me an outtest.txt file with e.g.:

```<code>mean: 0.34
median: 0.27
</code>```

What I'm looking for is a way to get an output file like:

```<code>import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
>> mean: 0.34
d_median = round(median(d), 2)
print(f'median: {d_median}')
>> median: 0.27
</code>```

Or some other format (markdown, whatever). Essentially, something like jupyter notebook or Rmarkdown but with using standard .py files.

Is there any easy way to achieve this?

答:
My answer might be similar to @Felix answer, but I'm trying to do it in a pythonic way.

Just grab the source code (mycode) and then execute it and capture the results, finally write them back to the output file.

Remember that I've used exec to the demonstration for the solution and you shouldn't use it in a production environment.

I also used this answer to capture stdout from exec.
    import mycode
    import inspect
    import sys
    from io import StringIO
    import contextlib

```<code>source_code = inspect.getsource(mycode)
output_file = "output.py"

@contextlib.contextmanager
def stdoutIO(stdout=None):
    old = sys.stdout
    if stdout is None:
        stdout = StringIO()
    sys.stdout = stdout
    yield stdout
    sys.stdout = old

# execute code
with stdoutIO() as s:
    exec(source_code)

# capture stdout
stdout = s.getvalue().splitlines()[::-1]

# write to file
with open(output_file, "w") as f:
    for line in source_code.splitlines():
        f.write(line)
        f.write('\n')
        if 'print' in line:
            f.write(">> {}".format(stdout.pop()))
            f.write('\n')
</code>```

Body:
Is there any way to write both commands and their output to an external file?

Let's say I have a script outtest.py :

import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
d_median = round(median(d), 2)
print(f'median: {d_median}')

Now if I want to capture its output only I know I can just do:

python3 outtest.py > outtest.txt

However, this will only give me an outtest.txt file with e.g.:

mean: 0.34
median: 0.27

What I'm looking for is a way to get an output file like:

import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
>> mean: 0.34
d_median = round(median(d), 2)
print(f'median: {d_median}')
>> median: 0.27

Or some other format (markdown, whatever). Essentially, something like jupyter notebook or Rmarkdown but with using standard .py files.

Is there any easy way to achieve this?

Body:
My answer might be similar to @Felix answer, but I'm trying to do it in a pythonic way.

Just grab the source code (mycode) and then execute it and capture the results, finally write them back to the output file.

Remember that I've used exec to the demonstration for the solution and you shouldn't use it in a production environment.

I also used this answer to capture stdout from exec.
    import mycode
    import inspect
    import sys
    from io import StringIO
    import contextlib

source_code = inspect.getsource(mycode)
output_file = "output.py"

@contextlib.contextmanager
def stdoutIO(stdout=None):
    old = sys.stdout
    if stdout is None:
        stdout = StringIO()
    sys.stdout = stdout
    yield stdout
    sys.stdout = old

# execute code
with stdoutIO() as s:
    exec(source_code)

# capture stdout
stdout = s.getvalue().splitlines()[::-1]

# write to file
with open(output_file, "w") as f:
    for line in source_code.splitlines():
        f.write(line)
        f.write('\n')
        if 'print' in line:
            f.write(">> {}".format(stdout.pop()))
            f.write('\n')


问:
Angular 8 multiple mat-checkbox required validation
I have multiple dynamic mat-checkbox and i want to implement validation "at least one of them is selected".
Here is the html code:

```<code><div class="form-check" *ngFor="let data of pointsDepart; let i=index" [ngClass]="i == 1 ? 'marginTop': ''">
        <mat-checkbox color="primary" formControlName="pointDepart" ngDefaultControl>{{data}}</mat-checkbox>
</div>
</code>```

How can I implement my validator, please ? thank you

答: Thank you, so you recommend to not use angular material's <mat-checkbox> and use <input type="checkbox"> instead ?

Body:
I have multiple dynamic mat-checkbox and i want to implement validation "at least one of them is selected".
Here is the html code:

        <mat-checkbox color="primary" formControlName="pointDepart" ngDefaultControl>{{data}}</mat-checkbox>

How can I implement my validator, please ? thank you


问:
How to make background color same as image?
I'm trying to set an image center of the screen, and the dimension of the image is not as big as the entire screen. How can I make the background color seem like part of the image? Thus creating the illusion that the image is full screen?

I tried using the color of the image and setting it as part of background color, but it still doesn't match.

html

```<code>  <section class="container">
    <img class="bg-img" src="../assets/beauty-bg-img.jpg" alt="background image">
  </section>
</code>```

css

```<code>.container {
    background-color: #F3D5DB;
}
</code>```

As can be seen, the image is centered, but image and background color doesnt go hand in hand.

How can this be done?

答:
You could try using 'mix-blend-mode', the background color of your image will match with the background color of it's parent.

Please note that this might not work with your image since you are using a gradient or it could happen that your gradient will be replaced by only one color.

It's also not compatible with some browsers.

.container {
    background-color: #F3D5DB;
}

.bg-img {
    mix-blend-mode: darken;
}

```

Check this for more options.

Body:
I'm trying to set an image center of the screen, and the dimension of the image is not as big as the entire screen. How can I make the background color seem like part of the image? Thus creating the illusion that the image is full screen?

I tried using the color of the image and setting it as part of background color, but it still doesn't match.

html

css

.container {
    background-color: #F3D5DB;
}

As can be seen, the image is centered, but image and background color doesnt go hand in hand.

How can this be done?

Body:
You could try using 'mix-blend-mode', the background color of your image will match with the background color of it's parent.

Please note that this might not work with your image since you are using a gradient or it could happen that your gradient will be replaced by only one color.

It's also not compatible with some browsers.

.container {
    background-color: #F3D5DB;
}

.bg-img {
    mix-blend-mode: darken;
}

Check this for more options.


问:
Flask redirect(urlfor()) doesn't work why?
```<code>@app.route('/result',methods=['GET','POST'])

def result(res):

    return render_template('public/inherit.html',res=res)

@app.route('/',methods=["POST","GET"])

def index():

    if request.method == "POST":
        a = 12
        redirect(url_for('result',res=a))
    return render_template('public/index.html'

</code>```

index.html

```<code>    <form method="post" action="{{ url_for('index') }}">
        <input type="submit" name="Login" value="Submit">
    </form>
</code>```

inherit.html

```<code><p>{{ res }}<p>
</code>```

答:
Change

```<code>@app.route('/result',methods=['GET','POST'])
</code>```

To

```<code>@app.route('/result/<res:int>',methods=['GET','POST'])
</code>```

Body:
@app.route('/result',methods=['GET','POST'])

def result(res):

    return render_template('public/inherit.html',res=res)

@app.route('/',methods=["POST","GET"])

def index():

    if request.method == "POST":
        a = 12
        redirect(url_for('result',res=a))
    return render_template('public/index.html'

index.html

    <form method="post" action="{{ url_for('index') }}">
        <input type="submit" name="Login" value="Submit">
    </form>

inherit.html

{{ res }}

Body:
Change

@app.route('/result',methods=['GET','POST'])

To

@app.route('/result/<res:int>',methods=['GET','POST'])


问:
Can parse a projection interface to object? Spring
Actually have a projection interface in Spring. Like this:

```<code>public interface DaoObjectProjection{
    Integer getTotalAmount();
    String getCode();
    String getName();
    String getLastName();
}

</code>```

And i want send this to another microservice, i know cant send the interface because the proxy funcionality dont work if use RestTemplate. For thar reason i use an another Object like that:

```<code>public class ObjectWantSend {
    private Integer totalAmount;
    private String code;
    private String name;
    private String lastName;

//Getters
//Setters

}

</code>```

My question if exist any way to parse directly my projection interface into this object or need setting one by one like this:

```<code>ObjectWantSend.setTotalAmount(DaoObjectProjection.getTotalAmount);
</code>```

I am using Hibernate with Spring.

答:
I think, like other user says, you should use MapStruct. This could be a solution for your problem:

```<code>    @Mapper
    public interface ObjectMapper {

        ObjectMapper INSTANCE = Mappers.getMapper( ObjectMapper.class );

        @Mapping(source = "totalAmount", target = "totalAmount")
        ObjectWantSend objectWantSend(DaoObjectProjection aux);
    }
</code>```

That library works so good with Spring and Hibernate. I hope you find it usefull.

Body:
Actually have a projection interface in Spring. Like this:

public interface DaoObjectProjection{
    Integer getTotalAmount();
    String getCode();
    String getName();
    String getLastName();
}

And i want send this to another microservice, i know cant send the interface because the proxy funcionality dont work if use RestTemplate. For thar reason i use an another Object like that:

public class ObjectWantSend {
    private Integer totalAmount;
    private String code;
    private String name;
    private String lastName;

//Getters
//Setters

}

My question if exist any way to parse directly my projection interface into this object or need setting one by one like this:

ObjectWantSend.setTotalAmount(DaoObjectProjection.getTotalAmount);

I am using Hibernate with Spring.

Body:
I think, like other user says, you should use MapStruct. This could be a solution for your problem:

    @Mapper
    public interface ObjectMapper {

        ObjectMapper INSTANCE = Mappers.getMapper( ObjectMapper.class );

        @Mapping(source = "totalAmount", target = "totalAmount")
        ObjectWantSend objectWantSend(DaoObjectProjection aux);
    }

That library works so good with Spring and Hibernate. I hope you find it usefull.


问:
TypeScript Array of Tuples
So I have this simple example:

```<code>type SomeTuple = [string, number];

const foo = (options: SomeTuple[]) => console.log(options);

const options = [
    ['first', 1],
    ['second', 2],
];

const otherOptions: SomeTuple[] = [
    ['first', 1],
    ['second', 2],
];

foo(options); // Error

foo(otherOptions); // OK
</code>```

Basically there no more much to tell, I just can't figure out why TS keeps showing me error in case where I'am not providing type for options explicitly;

Playground

Thank you for your time!

答:
TypeScript infers the type of options to be (string | number)[][] — an array of arrays containing either strings or numbers. It does not infer [string, number][].

This is a case of needing to specify the type, as in your otherOptions:

```<code>const otherOptions: SomeTuple[] = [
    ['first', 1],
    ['second', 2],
];
</code>```

TypeScript inference is really good, but it doesn't handle this specific case for you. It would be too limiting on options for it to assume you won't do options.push([1, 2]) in other code.

In this case, even as const doesn't help, because then the array entries are too specific (you can't assign readonly ['first', 1] to a SomeTuple).

Title: TypeScript Array of Tuples

Body:
So I have this simple example:

type SomeTuple = [string, number];

const foo = (options: SomeTuple[]) => console.log(options);

const options = [
    ['first', 1],
    ['second', 2],
];

const otherOptions: SomeTuple[] = [
    ['first', 1],
    ['second', 2],
];

foo(options); // Error

foo(otherOptions); // OK

Basically there no more much to tell, I just can't figure out why TS keeps showing me error in case where I'am not providing type for options explicitly;

Playground

Thank you for your time!

Body:
TypeScript infers the type of options to be (string | number)[][] — an array of arrays containing either strings or numbers. It does not infer [string, number][].

This is a case of needing to specify the type, as in your otherOptions:

const otherOptions: SomeTuple[] = [
    ['first', 1],
    ['second', 2],
];

TypeScript inference is really good, but it doesn't handle this specific case for you. It would be too limiting on options for it to assume you won't do options.push([1, 2]) in other code.

In this case, even as const doesn't help, because then the array entries are too specific (you can't assign readonly ['first', 1] to a SomeTuple).


问:
R: How to use current function output's within this function
I write a R function using if & else if in it. See the code below:

```<code>i_ti_12 <- function(x){
  if (x <= 44)
  {ti = exp(-13.2238 + 0.152568*x)}
  else if (x >= 49)
  {ti = -0.01245109 + 0.000315605*x}
  else (x > 44 & x < 49)
  {ti = (x-44)*(i_ti_12(49))/(49-44) + (49-x)*(i_ti_12(44))/(49-44)}
  return(ti)
}
</code>```

I want to use this function's output, i_ti_12(49) within this function, but the above code doesn't work. The output is:

```<code>> i_ti_12(49)
Error: C stack usage  7974292 is too close to the limit
</code>```

The simple solution is just replace i_ti_12(49) by -0.01245109 + 0.000315605*49, but its not a clear way to solve it and might not work in complex cases.

So I really want to know and to learn if there are clear methods to do this? I mean, like above simple example, write a conditional function using one condition's output in this function. Any help is highly appreciate.

答:
Your last else is followed by a condition (x > 44 & x < 49), which actually is not correct. If you have (x > 44 & x < 49) there, that means you will execute that statement, and ti = (x-44)*(i_ti_12(49))/(49-44) + (49-x)*(i_ti_12(44))/(49-44) is something independent with your if-else structure.

In that case, when you call i_ti_12(49), your function does not know when the recursion should be terminated since you did not define that case.

You can try the code below:

```<code>i_ti_12 <- function(x){
  if (x <= 44)
  {ti = exp(-13.2238 + 0.152568*x)}
  else if (x >= 49)
  {ti = -0.01245109 + 0.000315605*x}
  else
  {ti = (x-44)*(i_ti_12(49))/(49-44) + (49-x)*(i_ti_12(44))/(49-44)}
  return(ti)
}
</code>```

such that

```<code>> i_ti_12(49)
[1] 0.003013555
</code>```

Body:
I write a R function using if & else if in it. See the code below:

i_ti_12 <- function(x){
  if (x <= 44)
  {ti = exp(-13.2238 + 0.152568*x)}
  else if (x >= 49)
  {ti = -0.01245109 + 0.000315605*x}
  else (x > 44 & x < 49)
  {ti = (x-44)*(i_ti_12(49))/(49-44) + (49-x)*(i_ti_12(44))/(49-44)}
  return(ti)
}

I want to use this function's output, i_ti_12(49) within this function, but the above code doesn't work. The output is:

> i_ti_12(49)
Error: C stack usage  7974292 is too close to the limit

The simple solution is just replace i_ti_12(49) by -0.01245109 + 0.000315605*49, but its not a clear way to solve it and might not work in complex cases.

So I really want to know and to learn if there are clear methods to do this? I mean, like above simple example, write a conditional function using one condition's output in this function. Any help is highly appreciate.

Body:
Your last else is followed by a condition (x > 44 & x < 49), which actually is not correct. If you have (x > 44 & x < 49) there, that means you will execute that statement, and ti = (x-44)*(i_ti_12(49))/(49-44) + (49-x)*(i_ti_12(44))/(49-44) is something independent with your if-else structure.

In that case, when you call i_ti_12(49), your function does not know when the recursion should be terminated since you did not define that case.

You can try the code below:

i_ti_12 <- function(x){
  if (x <= 44)
  {ti = exp(-13.2238 + 0.152568*x)}
  else if (x >= 49)
  {ti = -0.01245109 + 0.000315605*x}
  else
  {ti = (x-44)*(i_ti_12(49))/(49-44) + (49-x)*(i_ti_12(44))/(49-44)}
  return(ti)
}

such that

> i_ti_12(49)
[1] 0.003013555


问:
How to get an age from a D.O.B field in MySQL?
I need to calculate the age of a "customer" from their date of birth.

I have tried to use the following:

DATEDIFF(year, customer.dob, "2010-01-01");

But it does not seem to work.

Any ideas? I KNOW it is going to be something simple!

Thanks

答:
If you want years, months and days like "26 years 4 months and 27 days" then following is the age function for you:

```<code>delimiter $$

create function age(dob date)
returns varchar(30)
deterministic
begin
declare years int default 0;
declare months int default 0;
declare days int default 0;
declare today date default curdate();

set years = timestampdiff(year, dob, today);
set months = timestampdiff(month, dob, today - interval years year);
set days = timestampdiff(day, dob, today - interval years year - interval months month);

return (concat(years, ' years ', months,' months and ', days,' days'));

end$$

delimiter;
</code>```

We are calculating the age from current date so I set today to curdate().
Now we are getting our years, months and days as following.

years: We get the difference in years from today to date of birth.

months: First we subtract the years from the today so that we only
    get months that are extra from the years and then find the difference in
    months from date of birth. Here "years" is the variable and "year" is interval type.

days: And here we subtract years and months that we
    have already calculated from today which is current date then find
    the diff in days from birth. Here "months" is the variable and "month" is interval type.

You can use datetime instead of date as argument if you want also you can format the return values as you like.

Body:
If you want years, months and days like "26 years 4 months and 27 days" then following is the age function for you:

delimiter $$

create function age(dob date)
returns varchar(30)
deterministic
begin
declare years int default 0;
declare months int default 0;
declare days int default 0;
declare today date default curdate();

set years = timestampdiff(year, dob, today);
set months = timestampdiff(month, dob, today - interval years year);
set days = timestampdiff(day, dob, today - interval years year - interval months month);

return (concat(years, ' years ', months,' months and ', days,' days'));

end$$

delimiter;

We are calculating the age from current date so I set today to curdate().
Now we are getting our years, months and days as following.

years: We get the difference in years from today to date of birth.

months: First we subtract the years from the today so that we only
    get months that are extra from the years and then find the difference in
    months from date of birth. Here "years" is the variable and "year" is interval type.

days: And here we subtract years and months that we
    have already calculated from today which is current date then find
    the diff in days from birth. Here "months" is the variable and "month" is interval type.

You can use datetime instead of date as argument if you want also you can format the return values as you like.


答:
By default ['first', 1] is an array with a string or a number, or one can say it's type is (string|number)[]. Note that an array does not specify it's length, nor does it specify which element is a string or which is a number. You can push an item with 3 or more values in it and TypeScript will be just fine with that.

In your second example (['first', 1]) it's an [string, number][]. Note that this differs from (string|number)[]. Now it knows it's an array with two elements, the first being a string, the second being a number. To be able to help figure TypeScript this out, an explicit declaration is required.

If it were to infer [string, number][] from the start, you wouldn't be able to add [123, 'foobar'], [123] or [] anymore. This would lead to more confusing errors as you would have to specify the type for each of those cases instead (fixing one issue, having other issues return). And if it would infer based on the entire file or codebase, compilation would take years for a complex program.

Title: TypeScript Array of Tuples


问:
Running Ruby on Rails in browser
Hi I really want to learn Ruby on Rails and I have heard it is a great community so hopefully someone can help with this. Couldn't find any direct answering this already but if there is one I'm sure someone will close this and point me in the right direction.

Is it possible to create Ruby on Rails applications from just a browser? I have bought a book and want the easiest possible way to do the exercises and experiment with building some applications, try Gems etc. I know the greatest chance of success is if I can do this when I have a spare 30 minutes ideally on my iPad.

As I am also looking at learning node.js I have signed upto Duostack and Joyent but both still need SSH setup, Github install etc. I'm looking for something that is just in a browser Window, I can write code and see it execute without having to setup any infrastructure. Found this on HackerNews today (reticular activation system?): http://bellard.org/jslinux/ . Looks promising will need to play with it to see if I can get Ruby on Rails working there but HN comments say no Internet connection so maybe not.

I do have a small netbook which I am going to run Ubuntu on which I guess is the other option but carrying this around will reduce my chances of success.

答:
Have you tried the Cloud9 IDE? It's an IDE in a browser. I've not had a chance to try it out myself, so can't promise it'll do the trick. I think the primary limitation is going to be actually /running/ the code. I think Cloud9 supports Node.js, but obviously that's not going to help when you're coding a rails app.

You might also want to look at their editor (which forms just /part/ of the overall offering).

Title: Running Ruby on Rails in browser