问:
Upload file to S3 but return observable
How would I ensure that the following method returns an observable?

```<code>  uploadFile(file, filename) {
    const contentType = file.type;
    const bucket = new S3(
      {
        accessKeyId: environment.awsAccessKeyId,
        secretAccessKey: environment.awssecretAccessKey,
        region: environment.awsRegion
      }
    );
    const params = {
      Bucket: environment.awsBucket,
      Key: environment.awsKey + filename,
      Body: file,
      ACL: 'public-read',
      ContentType: contentType
    };

    bucket.upload(params, function (err, data) {
      if (err) {
        this.logger.debug('There was an error uploading your file: ', err);
        return null;
      }
      this.logger.debug('Successfully uploaded file.', data);
      return data;
    });
  }
</code>```

I'd like to call it from an component as follows and capture the return output:

```<code>  this.ngxLoader.start();
  this.uploadService.uploadFile(newFile, sermonName), ((data) => {
    if (data) {
      // this.sermon.id = data.id;
      // this.logger.debug(`Posted file: ${JSON.stringify(data)}`);
      // this.logger.debug(`Updating file id: ${JSON.stringify(this.sermon.id)}`);
      // this.update();
      this.ngxLoader.stop();
    }
  }, error => {
    this.ngxLoader.stop();
    this.modalService.displayMessage('Oops!', error.message);
  });
</code>```

答:
Changes to return the result/error as Observable

```<code>
return Observable.create(observer => {
  bucket.upload(params, function (err, data) {
    if (err) {
      this.logger.debug('There was an error uploading your file: ', err);
      observer.error(err);
    }
    this.logger.debug('Successfully uploaded file.', data);
    observer.next(data);
    observer.complete();
  });
});

</code>```

Changes to handle result/error in component

```<code>
this.uploadService.uploadFile(newFile, sermonName)
.subscribe(
  data => {
    if (data) {
      // this.sermon.id = data.id;
      // this.logger.debug(`Posted file: ${JSON.stringify(data)}`);
      // this.logger.debug(`Updating file id: ${JSON.stringify(this.sermon.id)}`);
      // this.update();
      this.ngxLoader.stop();
    }
  },
  error => {
    this.ngxLoader.stop();
    this.modalService.displayMessage('Oops!', error.message);
  });

</code>```

of course we need to import the below.

```<code>import { Observable } from 'rxjs';
</code>```

also add the explicit return for the function for type checking.

```<code>uploadFile(file, filename): Observable<any> {
</code>```

Title: Upload file to S3 but return observable

Body:
How would I ensure that the following method returns an observable?

  uploadFile(file, filename) {
    const contentType = file.type;
    const bucket = new S3(
      {
        accessKeyId: environment.awsAccessKeyId,
        secretAccessKey: environment.awssecretAccessKey,
        region: environment.awsRegion
      }
    );
    const params = {
      Bucket: environment.awsBucket,
      Key: environment.awsKey + filename,
      Body: file,
      ACL: 'public-read',
      ContentType: contentType
    };

    bucket.upload(params, function (err, data) {
      if (err) {
        this.logger.debug('There was an error uploading your file: ', err);
        return null;
      }
      this.logger.debug('Successfully uploaded file.', data);
      return data;
    });
  }

I'd like to call it from an component as follows and capture the return output:

  this.ngxLoader.start();
  this.uploadService.uploadFile(newFile, sermonName), ((data) => {
    if (data) {
      // this.sermon.id = data.id;
      // this.logger.debug(`Posted file: ${JSON.stringify(data)}`);
      // this.logger.debug(`Updating file id: ${JSON.stringify(this.sermon.id)}`);
      // this.update();
      this.ngxLoader.stop();
    }
  }, error => {
    this.ngxLoader.stop();
    this.modalService.displayMessage('Oops!', error.message);
  });

Body:
Changes to return the result/error as Observable

return Observable.create(observer => {
  bucket.upload(params, function (err, data) {
    if (err) {
      this.logger.debug('There was an error uploading your file: ', err);
      observer.error(err);
    }
    this.logger.debug('Successfully uploaded file.', data);
    observer.next(data);
    observer.complete();
  });
});

Changes to handle result/error in component

this.uploadService.uploadFile(newFile, sermonName)
.subscribe(
  data => {
    if (data) {
      // this.sermon.id = data.id;
      // this.logger.debug(`Posted file: ${JSON.stringify(data)}`);
      // this.logger.debug(`Updating file id: ${JSON.stringify(this.sermon.id)}`);
      // this.update();
      this.ngxLoader.stop();
    }
  },
  error => {
    this.ngxLoader.stop();
    this.modalService.displayMessage('Oops!', error.message);
  });

of course we need to import the below.

import { Observable } from 'rxjs';

also add the explicit return for the function for type checking.

uploadFile(file, filename): Observable<any> {


来源: stackexchange

问:
Is there any package like cls-rtracer to log with request id in sails.js?
I am using SailsJS to develop my web server, I found the logs are mixed with different request and it is difficult to unique them. Is there any package like cls-rtracer in SailsJS framework?</p>

答:
You should use any of them

```<code>sails.log.info("Log Info");
sails.log.debug("Log Debug");
sails.log.warn("Log Warn");
sails.log.error("Log Error");
</code>```

And you will see logs like below, I hope this is enough to differentiate logs.

ContentLicense: CC BY-SA 4.0

Body:
You should use any of them

sails.log.info("Log Info");
sails.log.debug("Log Debug");
sails.log.warn("Log Warn");
sails.log.error("Log Error");

And you will see logs like below, I hope this is enough to differentiate logs.


问:
c# linq if item is in list and get matching items from list
If my list contains: english cat, french cat, japanese dog, spanish dog

and I have an item: dog

Not only do I want to see if the list contains my item, but return the items that match, so I would expect: japanese dog, spanish dog

I have got as far as seeing if the item is in the list using the following code:

```<code>if (myList.Any(myItem.ToLower().Contains)) { }
</code>```

答:
I think you are looking for something like this, using the where clause:

```<code>string filter = "dog";
IEnumerable<string> filteredItems = myList.Where(m => m.ToLower().Contains(filter.ToLower()));
</code>```

Body:
If my list contains: english cat, french cat, japanese dog, spanish dog

and I have an item: dog

Not only do I want to see if the list contains my item, but return the items that match, so I would expect: japanese dog, spanish dog

I have got as far as seeing if the item is in the list using the following code:

if (myList.Any(myItem.ToLower().Contains)) { }

Body:
I think you are looking for something like this, using the where clause:

string filter = "dog";
IEnumerable<string> filteredItems = myList.Where(m => m.ToLower().Contains(filter.ToLower()));


问:
Outlook COM Add-In - Show TaskPane in Outlook Compose Window
Config: Outlook 2016, COM Add-In (C# not office.js) -- We are also using Addin-Express' COM library but that's built on top of existing TaskPane in Outlook.

We currently are using the Outlook TaskPane and it works well in Outlook's main window:

If not obvious, it is dockable (and set to Right) and is visible as users switch between Mail/Appointment/etc.

Please excuse my lack of familiarity in this area.

Does anyone know if it's possible to have the same TaskPane appear in the Outlook Compose window (or Meeting Request window)?

ie:

Any help/guidance/documentation/even feasibility/LoE is greatly appreciated.

答:
To ensure Outlook Sub-Pane appears in a certain area (when using ADXO1 form), ensure the following are set:

```<code>this.adxOlFormsCollectionItem1.InspectorLayout = AddinExpress.OL.ADXOlInspectorLayout.RightSubpane;
this.adxOlFormsCollectionItem1.InspectorItemTypes = (AddinExpress.OL.ADXOlInspectorItemTypes)AddinExpress.OL.ADXOlInspectorItemTypes.olMeetingRequest;
</code>```

Which tells Outlook to automatically add the form to selected window (ie. Meeting request/Compose window)

Body:
To ensure Outlook Sub-Pane appears in a certain area (when using ADXO1 form), ensure the following are set:

this.adxOlFormsCollectionItem1.InspectorLayout = AddinExpress.OL.ADXOlInspectorLayout.RightSubpane;
this.adxOlFormsCollectionItem1.InspectorItemTypes = (AddinExpress.OL.ADXOlInspectorItemTypes)AddinExpress.OL.ADXOlInspectorItemTypes.olMeetingRequest;

Which tells Outlook to automatically add the form to selected window (ie. Meeting request/Compose window)


问:
created NULL constraint failed Django 2.2.1
So, first of all, no pending migrations.

I get:

```<code>[...]
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: backup_basenode.created
</code>```

on this line:

```<code>        node = Node(id=old_node.id, name=clean["name"], customer=customer)
        node.save()
</code>```

The relevant model:

```<code>class BaseNode(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    def __str__(self):
        return f"{str(self.id)}"

class Node(BaseNode):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    name = models.CharField(max_length=200)
    def __str__(self):
        return f"{self.name}({self.customer})"
</code>```

From what I gather, the created field should be automatically populated and therefore should not be null?

As to expected behaviour, I'm trying to elevate a BaseNode to a Node, since I haven't found a direct way of doing it, I went with creating a new Node instance and deleting the BaseNode instance.

答: Deleting the old instance before creating the "enhanced" one did the trick.</p>

Body:
So, first of all, no pending migrations.

I get:

[...]
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: backup_basenode.created

on this line:

        node = Node(id=old_node.id, name=clean["name"], customer=customer)
        node.save()

The relevant model:

class BaseNode(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    def __str__(self):
        return f"{str(self.id)}"

class Node(BaseNode):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    name = models.CharField(max_length=200)
    def __str__(self):
        return f"{self.name}({self.customer})"

From what I gather, the created field should be automatically populated and therefore should not be null?

As to expected behaviour, I'm trying to elevate a BaseNode to a Node, since I haven't found a direct way of doing it, I went with creating a new Node instance and deleting the BaseNode instance.


问:
join previous line with next depending of pattern of previous line
I have this Input:

```<code>1 a
a
2 b b
3 c
c
4 d d
5 e e
6 f
f
7 g
g
</code>```

I want this output using sed command

```<code>1 a a
2 b b
3 c c
4 d d
5 e e
6 f f
7 g g
</code>```

I'm trying this without success

```<code>sed '/^[^0-9]/ x; N; { s/\n/ / }; n' file
</code>```

答:
This might work for you (GNU sed):

```<code>sed '/^[0-9]/{:a;N;s/\n\([^0-9]\)/ \1/;ta;P;D}' file
</code>```

If the current line begins with an integer,  append the following line. If that line does not begin with an integer, replace the newline by a space and repeat. Otherwise print/delete the first line in the pattern space and repeat.

Body:
I have this Input:

1 a
a
2 b b
3 c
c
4 d d
5 e e
6 f
f
7 g
g

I want this output using sed command

1 a a
2 b b
3 c c
4 d d
5 e e
6 f f
7 g g

I'm trying this without success

sed '/^[^0-9]/ x; N; { s/\n/ / }; n' file

Body:
This might work for you (GNU sed):

sed '/^[0-9]/{:a;N;s/\n\([^0-9]\)/ \1/;ta;P;D}' file

If the current line begins with an integer,  append the following line. If that line does not begin with an integer, replace the newline by a space and repeat. Otherwise print/delete the first line in the pattern space and repeat.


问:
Loop SQL by month
In Oracle SQL Developer I need to calculate some figures (count for instance) since first day till today monthly. How can I create a loop by changing month in a date field? Now I have a time range on WHERE clause like (date >= '2017-01-01' and date < '2019-01-01'). So what I need is a table that counts for months and inserts results in two columns: month (2019_01, 2019_02, etc) and count</p>

答:
Here's an example which might help you do what need. It is based on Scott's sample schema, its EMP table that contains the HIREDATE column which will be joined to a CTE named months; it utilizes hierarchical query to create "calendar" of 12 months (that's what the CONNECT BY clause does). It will have to be changed in your case, I presume.

Current data:

```<code>SQL> select empno, ename, hiredate
  2  from emp
  3  order by hiredate;

     EMPNO ENAME      HIREDATE
---------- ---------- ----------
      7369 SMITH      17.12.1980
      7499 ALLEN      20.02.1981
      7521 WARD       22.02.1981
      7566 JONES      02.04.1981
      7698 BLAKE      01.05.1981
      7782 CLARK      09.06.1981
      7844 TURNER     08.09.1981
      7654 MARTIN     28.09.1981
      7839 KING       17.11.1981
      7900 JAMES      03.12.1981
      7902 FORD       03.12.1981
      7934 MILLER     23.01.1982
      7788 SCOTT      09.12.1982
      7876 ADAMS      12.01.1983

14 rows selected.

SQL>
</code>```

Query you might need:

```<code>SQL> with months as
  2    (select add_months(date '1980-12-01', level - 1) mon
  3     from dual
  4     connect by level <= 12
  5    )
  6  select to_char(m.mon, 'mm.yyyy') mon,
  7         count(e.empno)
  8  from months m left join emp e on m.mon = trunc(e.hiredate, 'mm')
  9  group by m.mon
 10  order by m.mon;

MON     COUNT(E.EMPNO)
------- --------------
12.1980              1   --> Smith
01.1981              0
02.1981              2   --> Allen, Ward
03.1981              0
04.1981              1   --> Jones
05.1981              1   --> Blake
06.1981              1   --> Clark
07.1981              0
08.1981              0
09.1981              2   --> Turner, Martin
10.1981              0
11.1981              1   --> King

12 rows selected.

SQL>
</code>```

Title: Loop SQL by month

Body:
Here's an example which might help you do what need. It is based on Scott's sample schema, its EMP table that contains the HIREDATE column which will be joined to a CTE named months; it utilizes hierarchical query to create "calendar" of 12 months (that's what the CONNECT BY clause does). It will have to be changed in your case, I presume.

Current data:

SQL> select empno, ename, hiredate
  2  from emp
  3  order by hiredate;

     EMPNO ENAME      HIREDATE
---------- ---------- ----------
      7369 SMITH      17.12.1980
      7499 ALLEN      20.02.1981
      7521 WARD       22.02.1981
      7566 JONES      02.04.1981
      7698 BLAKE      01.05.1981
      7782 CLARK      09.06.1981
      7844 TURNER     08.09.1981
      7654 MARTIN     28.09.1981
      7839 KING       17.11.1981
      7900 JAMES      03.12.1981
      7902 FORD       03.12.1981
      7934 MILLER     23.01.1982
      7788 SCOTT      09.12.1982
      7876 ADAMS      12.01.1983

14 rows selected.

SQL>

Query you might need:

SQL> with months as
  2    (select add_months(date '1980-12-01', level - 1) mon
  3     from dual
  4     connect by level <= 12
  5    )
  6  select to_char(m.mon, 'mm.yyyy') mon,
  7         count(e.empno)
  8  from months m left join emp e on m.mon = trunc(e.hiredate, 'mm')
  9  group by m.mon
 10  order by m.mon;

MON     COUNT(E.EMPNO)
------- --------------
12.1980              1   --> Smith
01.1981              0
02.1981              2   --> Allen, Ward
03.1981              0
04.1981              1   --> Jones
05.1981              1   --> Blake
06.1981              1   --> Clark
07.1981              0
08.1981              0
09.1981              2   --> Turner, Martin
10.1981              0
11.1981              1   --> King

12 rows selected.

SQL>


问:
How do i find out the Structure of a Java Object?
I am working with the HttpExchange class, and want to use the getAttribute function to get the POST parameters. If i just call the function and print the results it works. But there has to be some better way to access the returned object and get the contained data.

The Manual is here: http://download.oracle.com/javase/6/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/HttpExchange.html#getAttribute%28java.lang.String%29

How can i access the Object? Which methods does it have?

答:
The HttpExchange returns you the type Object for the given attribute name, It is assumed that the one who try to retrieve the attribute knows the type of the attribute and can downcast the Object to appropriate class. E.g. -

```<code>String attrValue = (String) httpExchangeObject.getAttribute("nameOfTheAttribute");
</code>```

you don't need to use reflection on the returned object to find out the structre.. I feel simple down-casting should solve the purpose.

ContentLicense: CC BY-SA 3.0

Body:
The HttpExchange returns you the type Object for the given attribute name, It is assumed that the one who try to retrieve the attribute knows the type of the attribute and can downcast the Object to appropriate class. E.g. -

String attrValue = (String) httpExchangeObject.getAttribute("nameOfTheAttribute");

you don't need to use reflection on the returned object to find out the structre.. I feel simple down-casting should solve the purpose.


问:
PHP MVC - One view class for all controllers vs a view class for each controller
I am creating an MVC inspired PHP framework, mainly for learning purposes.
I basically have the framework created and am building an app on it and improving the framework as i go along.

I am still confused/not sure about certain aspects of this sort of architecture, and at the moment i am questioning my implementation of the View part.

How i have set up my framework:

Its a very simple set up, for example: you go to the url /post/post_id, this will load index.php which will instantiate the router. The router will then check the url and instantiate the correct controller and method based on the url. In this case it would be PostController, and the method would be a default method that would use the post_id to get the posts data from the relevant model. Next the controller would set up a "data" variable that will hold the data to pass on to the View, and this is where i am confused - should it send to its own View object (a view class file dedicated to the PostController), or to a generally used View class that is used by all controllers to load an html file?

At the moment my controller is sending data to the View class, this data includes what template file should be included/shown, and the actual data for the page (what we got from the Model through the controller).

My question is this:

Should this type of system have one View object that renders all of the views (html files) based on what data is given to the "render" method, or, should each controller that eventually sends data to the View have its own View object/class?

Meaning, should PostController send a request to the general view class, the same one that is used by all controllers to renders pages, or should the PostController send to a dedicated View Class (call it PostView if it makes it clearer), and this class will then render the specific html file?

Basically if it should be one View class for all controllers that will render what ever html file the controller tells it to, or if there should be many View classes, one for each page load.

NOTE:
I know a lot of questions have already been asked about MVC in PHP, but i could not find an answer to my question in any of the answers.

答:
The best way, IMO, is to have this View or Template class do all the work related to views with just one simple method: render(string $templateName, array $context = []).

This allows for easy extension or creation of adapters. You should make your controllers use this method. If you use a DI Container in your framework, you could do a TemplatingAwareInterface and implement that with a trait that allows setter injection. That will inject the templating service on fetching from the service container. That way, you can use $this->templating->render() in your controller, without having to either make it global, nor constructing the templating service inside the controller, nor injecting the container into the controller.

Having one view class for each type of controller is cumbersome, harder to maintain and I don't really see a reason for it.


问:
Pandas: flatten data from inconsistent rows
I have an input Excel spreadsheet like this:

```<code>key  | value | other data
------------------------- ...
k1   | v1    | d1
     | v2    |
     | v3    |
k2   | v2    | d2
     | v5    |
k3   | v1    | d3
</code>```

Values are stored in an empty, except for the value column, row directly below the row with the matching key and there can be arbitrary number of values bound to the key, however highly unlikely more than three. All keys are unique, 'other data' may be missing or be repeated, there is around a dozen of values and thousands of data rows.

I need to convert the input table to the following format:

```<code>k1   | v1,v2,v3 | d1 | ...
k2   | v2,v5    | d2 | ...
k3   | v1       | d3 | ...
</code>```

I have solved this problem with openpyxl and a trivial iterative algorithm and I was wondering if there's a more elegant way to do this using Pandas' DataFrame manipulation facilities? I searched for Pandas data manipulation tutorials, but most of what I could find use groupby() and agg() which is seemingly not my case, since I have no column I can aggregate on and can only depend on the key being consistently unique.

Head-on solution, I used for now:

import openpyxl
wb = openpyxl.load_workbook('in.xlsx')
ws = wb['Sheet1']

row_data = None
out_list = list()
i = 2
while i < ws.max_row + 1:
    if ws[i][0].value is not None:
        if row_data is not None:
            out_list += [row_data]
        row_data = list(ws[i])
    else:
        row_data[1].value = f'{row_data[1].value}' + f',{ws[i][1].value}'
    i += 1

out_list += [list(ws[ws.max_row])]   # append the last row to the output

wb_out = openpyxl.Workbook()
ws_out = wb_out.active

for row in out_list:
    ws_out.append([cell.value for cell in row])

wb_out.save('out.xlsx')
```

答:
The pandas way of doing this considering the excel looks like below:

```<code>df= pd.read_excel(r'C:\path\excelfile.xlsx',sheet_name='Sheet_Name')
df=(df.groupby(df.key.ffill()).agg({'value':lambda x: ','.join(x),'other data':'first'})
                                                                .reset_index())
</code>```

```<code>  key     value other data
0  k1  v1,v2,v3         d1
1  k2     v2,v5         d2
2  k3        v1         d3
</code>```

Body:
I have an input Excel spreadsheet like this:

key  | value | other data
------------------------- ...
k1   | v1    | d1
     | v2    |
     | v3    |
k2   | v2    | d2
     | v5    |
k3   | v1    | d3

Values are stored in an empty, except for the value column, row directly below the row with the matching key and there can be arbitrary number of values bound to the key, however highly unlikely more than three. All keys are unique, 'other data' may be missing or be repeated, there is around a dozen of values and thousands of data rows.

I need to convert the input table to the following format:

k1   | v1,v2,v3 | d1 | ...
k2   | v2,v5    | d2 | ...
k3   | v1       | d3 | ...

I have solved this problem with openpyxl and a trivial iterative algorithm and I was wondering if there's a more elegant way to do this using Pandas' DataFrame manipulation facilities? I searched for Pandas data manipulation tutorials, but most of what I could find use groupby() and agg() which is seemingly not my case, since I have no column I can aggregate on and can only depend on the key being consistently unique.

Head-on solution, I used for now:

import openpyxl
wb = openpyxl.load_workbook('in.xlsx')
ws = wb['Sheet1']

row_data = None
out_list = list()
i = 2
while i < ws.max_row + 1:
    if ws[i][0].value is not None:
        if row_data is not None:
            out_list += [row_data]
        row_data = list(ws[i])
    else:
        row_data[1].value = f'{row_data[1].value}' + f',{ws[i][1].value}'
    i += 1

out_list += [list(ws[ws.max_row])]   # append the last row to the output

wb_out = openpyxl.Workbook()
ws_out = wb_out.active

for row in out_list:
    ws_out.append([cell.value for cell in row])

wb_out.save('out.xlsx')

Body:
The pandas way of doing this considering the excel looks like below:

df= pd.read_excel(r'C:\path\excelfile.xlsx',sheet_name='Sheet_Name')
df=(df.groupby(df.key.ffill()).agg({'value':lambda x: ','.join(x),'other data':'first'})
                                                                .reset_index())

  key     value other data
0  k1  v1,v2,v3         d1
1  k2     v2,v5         d2
2  k3        v1         d3


问:
Does Python support multithreading? Can it speed up execution time?
I'm slightly confused about whether multithreading works in Python or not.

I know there has been a lot of questions about this and I've read many of them, but I'm still confused. I know from my own experience and have seen others post their own answers and examples here on StackOverflow that multithreading is indeed possible in Python. So why is it that everyone keep saying that Python is locked by the GIL and that only one thread can run at a time? It clearly does work. Or is there some distinction I'm not getting here?

Many posters/respondents also keep mentioning that threading is limited because it does not make use of multiple cores. But I would say they are still useful because they do work simultaneously and thus get the combined workload done faster. I mean why would there even be a Python thread module otherwise?

Update:

Thanks for all the answers so far. The way I understand it is that multithreading will only run in parallel for some IO tasks, but can only run one at a time for CPU-bound multiple core tasks.

I'm not entirely sure what this means for me in practical terms, so I'll just give an example of the kind of task I'd like to multithread. For instance, let's say I want to loop through a very long list of strings and I want to do some basic string operations on each list item. If I split up the list, send each sublist to be processed by my loop/string code in a new thread, and send the results back in a queue, will these workloads run roughly at the same time? Most importantly will this theoretically speed up the time it takes to run the script?

Another example might be if I can render and save four different pictures using PIL in four different threads, and have this be faster than processing the pictures one by one after each other? I guess this speed-component is what I'm really wondering about rather than what the correct terminology is.

I also know about the multiprocessing module but my main interest right now is for small-to-medium task loads (10-30 secs) and so I think multithreading will be more appropriate because subprocesses can be slow to initiate.

答:
Threading is Allowed in Python, the only problem is that the GIL will make sure that just one thread is executed at a time (no parallelism).

So basically if you want to multi-thread the code to speed up calculation it won't speed it up as just one thread is executed at a time, but if you use it to interact with a database for example it will.


问:
Grouping and ordering using ActiveRecord Query interface
I have a model, ConnectedUser, which belongs to 2 other models User and Station.

It is a simple model with just those relationships and a boolean active.

The results of the query I'm aiming for would be only each most recent ConnectedUser record for each User (where the Station is a specific id).

For example, if my ConnectedUser table looked like this...

```<code>+----+---------+------------+--------+------------+
| id | user_id | station_id | active | created_at |
+----+---------+------------+--------+------------+
|  1 |       1 |          1 | true   | 20 June    |
|  2 |       1 |          1 | false  | 19 June    |
|  3 |       1 |          2 | false  | 20 June    |
|  4 |       2 |          1 | false  | 18 June    |
|  5 |       2 |          1 | false  | 21 June    |
+----+---------+------------+--------+------------+
</code>```

And the station was the one with id 1 then I'd like the query to return...

```<code>[
<ConnectedUser id: 1, user_id: 1, station_id: 1, active: true, created_at: "2019-06-20">,
<ConnectedUser id: 5, user_id: 2, station_id: 1, active: false, created_at: "2019-06-21">
]
</code>```

To achieve this I've been trying to use group to and order

```<code>ConnectedUser.where(station: station).select(:user_id).group(:user_id).order(:created_at)
</code>```

but have kept getting errors like this:

ActiveRecord::StatementInvalid (PG::GroupingError: ERROR:  column
  "connected_users.created_at" must appear in the GROUP BY clause or be
  used in an aggregate function)

I am unable to get the specific ConnectedUser id, so feel like I'm missing some important understanding how to work with group and aggregate the results.

Is this possible in one ActiveRecord query?

Many thanks.

答:
Probaly, this would solve it

ConnectedUser.where(active: true).order(user_id: :desc).uniq(&:user_id)

order is used to sort the user_id field in DESC

on this solution, i am using uniq, which is a array solution, and will select just the most recent user_id

edit:

I was wrong, uniq didnt work as expected, but testing here, i discover that:

ConnectedUser.where(active: true).order(created_at: :desc).group(:user_id)

seems much like yours, but, when you use select, it does select just the field user_id, so, you can't order by created_at

Should work

Body:
I have a model, ConnectedUser, which belongs to 2 other models User and Station.

It is a simple model with just those relationships and a boolean active.

The results of the query I'm aiming for would be only each most recent ConnectedUser record for each User (where the Station is a specific id).

For example, if my ConnectedUser table looked like this...

+----+---------+------------+--------+------------+
| id | user_id | station_id | active | created_at |
+----+---------+------------+--------+------------+
|  1 |       1 |          1 | true   | 20 June    |
|  2 |       1 |          1 | false  | 19 June    |
|  3 |       1 |          2 | false  | 20 June    |
|  4 |       2 |          1 | false  | 18 June    |
|  5 |       2 |          1 | false  | 21 June    |
+----+---------+------------+--------+------------+

And the station was the one with id 1 then I'd like the query to return...

[
<ConnectedUser id: 1, user_id: 1, station_id: 1, active: true, created_at: "2019-06-20">,
<ConnectedUser id: 5, user_id: 2, station_id: 1, active: false, created_at: "2019-06-21">
]

To achieve this I've been trying to use group to and order

ConnectedUser.where(station: station).select(:user_id).group(:user_id).order(:created_at)

but have kept getting errors like this:

ActiveRecord::StatementInvalid (PG::GroupingError: ERROR:  column
  "connected_users.created_at" must appear in the GROUP BY clause or be
  used in an aggregate function)

I am unable to get the specific ConnectedUser id, so feel like I'm missing some important understanding how to work with group and aggregate the results.

Is this possible in one ActiveRecord query?

Many thanks.


问:
Why I get different length of vectors using gensim LSI model?
I'm trying to cluster some descriptions using LSI. As the dataset that I have is too long, I'm clustering based on the vectors obtained from the models instead of using the similarity matrix, which requires too much memory, and if I pick a sample, the matrix generated doesn't correspond to a square (this precludes the use of MDS).

However, after running the model and looking for the vectors I'm getting different vector's lengths in the descriptions. Most of them have a length of 300 (the num_topics argument in the model), but some few, with the same description, present a length of 299.

Why is this happening? Is there a way to correct it?

```<code>dictionary = gensim.corpora.Dictionary(totalvocab_lemmatized)
dictionary.compactify()

corpus = [dictionary.doc2bow(text) for text in totalvocab_lemmatized]

###tfidf model
tfidf = gensim.models.TfidfModel(corpus, normalize = True)
corpus_tfidf = tfidf[corpus]

###LSI model
lsi = gensim.models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=300)
vectors =[]
for n in lemmatized[:100]:
    vec_bow = dictionary.doc2bow(n)
    vec_lsi = lsi[vec_bow]
    print(len(vec_lsi))
</code>```

答:
Explicit zeros are omitted, which is why some vectors appear shorter.
Source: https://github.com/RaRe-Technologies/gensim/issues/2501</p>

Body:
I'm trying to cluster some descriptions using LSI. As the dataset that I have is too long, I'm clustering based on the vectors obtained from the models instead of using the similarity matrix, which requires too much memory, and if I pick a sample, the matrix generated doesn't correspond to a square (this precludes the use of MDS).

However, after running the model and looking for the vectors I'm getting different vector's lengths in the descriptions. Most of them have a length of 300 (the num_topics argument in the model), but some few, with the same description, present a length of 299.

Why is this happening? Is there a way to correct it?

dictionary = gensim.corpora.Dictionary(totalvocab_lemmatized)
dictionary.compactify()

corpus = [dictionary.doc2bow(text) for text in totalvocab_lemmatized]

###tfidf model
tfidf = gensim.models.TfidfModel(corpus, normalize = True)
corpus_tfidf = tfidf[corpus]

###LSI model
lsi = gensim.models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=300)
vectors =[]
for n in lemmatized[:100]:
    vec_bow = dictionary.doc2bow(n)
    vec_lsi = lsi[vec_bow]
    print(len(vec_lsi))


问:
Can numerical values be assigned to alphabetic elements of a list and then added using the sum() function?
I am  trying the following problem and I don't know what's wrong. Can somebody help me through it?

```<code>java=10
python=10
sql=5
unix=5
javascript=5
framework=10
i=eval(input("Enter courses done in a list"))
if sum(i)>=30:
    print("eligible since the score is", sum(i))
else:
    print("Not eligible since the score is",sum(i))
</code>```

But I am getting the following error,

```<code>Traceback (most recent call last):
  File "E:/Python Notes/Python Programs/Eligible for placement.py", line 8, in <module>
    if sum(i)>=30:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code>```

Thanks in advance!!

答:
you can try with setting a string as a variable name

```<code>java=10
python=10
sql=5
unix=5
javascript=5
framework=10
i=input("Enter courses done in a list:").split() # ['python', 'java', 'sql']
sum_ = 0

for item in i:
    sum_ += int(vars()[item]) # "use string like a variable"

if sum_>=30:
    print("eligible since the score is ", sum_)
else:
    print("Not eligible since the score is ",sum_)
</code>```

output:

```<code>Enter courses done in a list:python java sql
Not eligible since the score is  25
</code>```

Body:
I am  trying the following problem and I don't know what's wrong. Can somebody help me through it?

java=10
python=10
sql=5
unix=5
javascript=5
framework=10
i=eval(input("Enter courses done in a list"))
if sum(i)>=30:
    print("eligible since the score is", sum(i))
else:
    print("Not eligible since the score is",sum(i))

But I am getting the following error,

Traceback (most recent call last):
  File "E:/Python Notes/Python Programs/Eligible for placement.py", line 8, in <module>
    if sum(i)>=30:
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Thanks in advance!!

Body:
you can try with setting a string as a variable name

java=10
python=10
sql=5
unix=5
javascript=5
framework=10
i=input("Enter courses done in a list:").split() # ['python', 'java', 'sql']
sum_ = 0

for item in i:
    sum_ += int(vars()[item]) # "use string like a variable"

if sum_>=30:
    print("eligible since the score is ", sum_)
else:
    print("Not eligible since the score is ",sum_)

output:

Enter courses done in a list:python java sql
Not eligible since the score is  25


问:
SliverAppBar only push up after some scrolling
I have a SliverAppBar (floating: true, pinned: false).

I want to achieve that the user has to scroll 200 pixels (or some other amount) before the SliverAppBar starts to compress/slide-up.

答:
The problem here is that pinned value is not supposed to be changed. If you try to change it after scrolling 200 pixels, the SliverAppBar would shrink suddenly.

You can check this out by running the code below:

class Buster extends StatefulWidget {
  @override
  _BusterState createState() => _BusterState();
}

class _BusterState extends State<Buster> {
  ScrollController controller;
  bool isAppBarPinned;

  @override
  void initState() {
    super.initState();
    controller = ScrollController()..addListener(onScroll);
    isAppBarPinned = true;
  }

  void onScroll() {
    if (controller.position.pixels > 200) {
      if (isAppBarPinned) {
        setState(() => isAppBarPinned = false);
      }
    } else {
      if (!isAppBarPinned) {
        setState(() => isAppBarPinned = true);
      }
    }
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        controller: controller,
        slivers: [
          SliverAppBar(
            title: Text('Buster'),
            floating: true,
            pinned: isAppBarPinned,
          ),
          SliverFixedExtentList(
            itemExtent: 150,
            delegate: SliverChildListDelegate(
              [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
                  .map((int index) => Center(child: Text('Item #$index')))
                  .toList(),
            ),
          )
        ],
      ),
    );
  }
}
```

So I think the best option you got here is using a regular AppBar and animate it manually with a Transform.

Body:
The problem here is that pinned value is not supposed to be changed. If you try to change it after scrolling 200 pixels, the SliverAppBar would shrink suddenly.

You can check this out by running the code below:

class Buster extends StatefulWidget {
  @override
  _BusterState createState() => _BusterState();
}

class _BusterState extends State<Buster> {
  ScrollController controller;
  bool isAppBarPinned;

  @override
  void initState() {
    super.initState();
    controller = ScrollController()..addListener(onScroll);
    isAppBarPinned = true;
  }

  void onScroll() {
    if (controller.position.pixels > 200) {
      if (isAppBarPinned) {
        setState(() => isAppBarPinned = false);
      }
    } else {
      if (!isAppBarPinned) {
        setState(() => isAppBarPinned = true);
      }
    }
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        controller: controller,
        slivers: [
          SliverAppBar(
            title: Text('Buster'),
            floating: true,
            pinned: isAppBarPinned,
          ),
          SliverFixedExtentList(
            itemExtent: 150,
            delegate: SliverChildListDelegate(
              [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
                  .map((int index) => Center(child: Text('Item #$index')))
                  .toList(),
            ),
          )
        ],
      ),
    );
  }
}

So I think the best option you got here is using a regular AppBar and animate it manually with a Transform.


问:
C# Generic Copy Constructor
I have an interface, and two classes that implements the interface.  The classes have generic types.  I would like to clone from an instance of one class to the other.

```<code>interface IFoo
{
    // stuff
}

class Foo<T> : IFoo
{
    // foo stuff
    // ifoo implementation
}

class Bar<T> : IFoo
{
    // bar stuff
    // ifoo implementation
}
</code>```

I have a Foo and would like a Bar.  Bar has a copy constructor taking a parameter of IFoo.
I created an extension method to implement the clone:

```<code>public static Bar<T> Clone<T>(this IFoo foo)
{
    return new Bar<T>(foo);
}
</code>```

Calling the method requires the type:

```<code>someFoo.Clone<T> ...
</code>```

Is there a way to omit declaring the type when calling the method by modifying the extension method, or any other way, to allow the the instance to just be passed in without caring about its underlying type?

Update
Here is how this is being used to better illustrate the situation.

In a method I iterate a collection and return an enumeration of IFoo.  In the method I look at an attribute of the source collection and determine the type of the Foo.

```<code>IFoo foo = null;

string type = element.Attribute("Type").Value;
switch (type)
{
    case "int":
        foo = new Foo<int>();
        break;

    case "string":
        foo = new Foo<string>();
        break;

    // etc
}
// other stuff

yield return foo;
</code>```

The calling method has a List.  Later I select individual items from this list for use, at which point I would like a Bar instead of a Foo.  When selecting from the list the instances are of type IFoo, as in they only see the extension methods for "this IFoo foo".  I do not want to cast the IFoo to a Foo, that would require re-declaring the type of T.  I would just like to have Foo tell Bar what it is.  Is this possible?

答:
Will this help for inspiration?: How would you improve this shallow copying class?

Essentially it's a generic reflection-based property copying method. Try it out.

OwnerDisplayName: blu

ContentLicense: CC BY-SA 2.5

Title: C# Generic Copy Constructor

Body:
I have an interface, and two classes that implements the interface.  The classes have generic types.  I would like to clone from an instance of one class to the other.

interface IFoo
{
    // stuff
}

class Foo<T> : IFoo
{
    // foo stuff
    // ifoo implementation
}

class Bar<T> : IFoo
{
    // bar stuff
    // ifoo implementation
}

I have a Foo and would like a Bar.  Bar has a copy constructor taking a parameter of IFoo.
I created an extension method to implement the clone:

public static Bar<T> Clone<T>(this IFoo foo)
{
    return new Bar<T>(foo);
}

Calling the method requires the type:

someFoo.Clone<T> ...

Is there a way to omit declaring the type when calling the method by modifying the extension method, or any other way, to allow the the instance to just be passed in without caring about its underlying type?

Update
Here is how this is being used to better illustrate the situation.

In a method I iterate a collection and return an enumeration of IFoo.  In the method I look at an attribute of the source collection and determine the type of the Foo.

IFoo foo = null;

string type = element.Attribute("Type").Value;
switch (type)
{
    case "int":
        foo = new Foo<int>();
        break;

    case "string":
        foo = new Foo<string>();
        break;

    // etc
}
// other stuff

yield return foo;

The calling method has a List.  Later I select individual items from this list for use, at which point I would like a Bar instead of a Foo.  When selecting from the list the instances are of type IFoo, as in they only see the extension methods for "this IFoo foo".  I do not want to cast the IFoo to a Foo, that would require re-declaring the type of T.  I would just like to have Foo tell Bar what it is.  Is this possible?

LastEditorDisplayName: blu

OwnerDisplayName: Neil Barnwell


问:
Calling a child object in the parent object
I want to know if I can create a child object in a parent object an use it...

I mean is it posible?

Is it a good    idea?

What do I have to care if I do    so?

I am using the child classes on their own and i want to use them in a private function of the parent class as well.

thanks

here some source to imagine what I am meaning:

```<code>class A{
    private $child_class1;
    private $child_class2;

    private function somefunction(){
        $this->child_class1 = new B();
        $this->child_class1->do_something();

        $this->child_class2 = new C();
        $this->child_class2->do_something();
    }
}

class B extends A{
    public function do_something(){
...
    }
}

class C extends A{
    public function do_something(){
...
    }
}
</code>```

答:
This seems to be like a bad idea IMHO - it's going to require high maintenance and you are creating some tight couplings between classes.

i would recommend creating an abstract function in the parent that each of the children will implement with it's own logic.

[EDIT] since you are trying to iterate over all child objects i would recommend to create a base class that handles all the logic that needs to be implemented to all children, and override it in each of the child classes that need additional logic, and call the parent function inside it.

Body:
I want to know if I can create a child object in a parent object an use it...

I mean is it posible?

Is it a good    idea?

What do I have to care if I do    so?

I am using the child classes on their own and i want to use them in a private function of the parent class as well.

thanks

here some source to imagine what I am meaning:

class A{
    private $child_class1;
    private $child_class2;

    private function somefunction(){
        $this->child_class1 = new B();
        $this->child_class1->do_something();

        $this->child_class2 = new C();
        $this->child_class2->do_something();
    }
}

class B extends A{
    public function do_something(){
...
    }
}

class C extends A{
    public function do_something(){
...
    }
}


问:
why long text appears below name?

I want the message begin at the right from the name and continue below if its too long

.. like the second text but its short ..

php ;

```<code>        echo'
            <div class="chatpos">
              <div class="namec">'.$resnamec['username'].'</div>
              <div class="msgc">'.$reschat['message'].'</div>
            </div>';
        }
</code>```

css ;

```<code>  .chatpos {
    position: relative;
    width: 90%;
    min-height: 30px;
    float: right;
}

.namec {
    display: inline-block;
    position: relative;
    text-align: center;
    color: #9aefd8;
    text-decoration: none;
    font-size: 12px;
    font-weight: 600;
    padding-left: 2px;
    padding-right: 2px;
    transition: all 0.3s ease-in-out;
    letter-spacing: 0px;
}

.msgc {
    display: inline-block;
    word-wrap: break-word;
    position: relative;
}
</code>```

答:
The msgc class is set to display: inline-block. Instead, it should be set to display: inline. Like so:

```<code>.msgc {
  display: inline;
}
</code>```

Check this fiddle to see if this is what you desired.

In hindsight, I believe a more reliable approach would be to set both msgc and namec to display: block. Additionally, you may set namec to float: left, like this:

```<code>.namec {
    display: block;
    float: left;
    margin-right: 5px;
    color: blue;
}

.msgc {
    display: block;
    text-align: justify;
}
</code>```

Check this updated fiddle.

Title: why long text appears below name?

Body:
I want the message begin at the right from the name and continue below if its too long

.. like the second text but its short ..

php ;

        echo'

'.$resnamec['username'].'

'.$reschat['message'].'

';
        }

css ;

  .chatpos {
    position: relative;
    width: 90%;
    min-height: 30px;
    float: right;
}

.namec {
    display: inline-block;
    position: relative;
    text-align: center;
    color: #9aefd8;
    text-decoration: none;
    font-size: 12px;
    font-weight: 600;
    padding-left: 2px;
    padding-right: 2px;
    transition: all 0.3s ease-in-out;
    letter-spacing: 0px;
}

.msgc {
    display: inline-block;
    word-wrap: break-word;
    position: relative;
}

Body:
The msgc class is set to display: inline-block. Instead, it should be set to display: inline. Like so:

.msgc {
  display: inline;
}

Check this fiddle to see if this is what you desired.

In hindsight, I believe a more reliable approach would be to set both msgc and namec to display: block. Additionally, you may set namec to float: left, like this:

.namec {
    display: block;
    float: left;
    margin-right: 5px;
    color: blue;
}

.msgc {
    display: block;
    text-align: justify;
}

Check this updated fiddle.


问:
What does the BLE-status code "-402" mean?
I have a GarminIQ-project. Therefore I make a request. Since yesterday I get the error code -402.

According to https://developer.garmin.com/downloads/connect-iq/monkey-c/doc/Toybox/Communications/OAuthMessage.html#responseCode-instance_method negative values stand for BLE-responses, positive are the http-requestCode. Does anybody know what -402 stands for?

I am using the Connect IQ SDK 3.0.10.

I tried to find out, what the error code is meaning. But I haven't found a list with code "-402" or "402"

Down below are the two code snippets that are used for the request. The argument url is our api-url. This works fine in a browser.

```<code>//This function makes the request
function makeRequest(url) {
        jsonFile = Communications.makeJsonRequest(url, {}, {}, method(:onReceive));
    }

//This is the callback method that is called, when data have arrived
function onReceive(responseCode, data){

        if (responseCode == 200) {
            notify.invoke(1, data);
        }else {
            System.println(responseCode);
            notify.invoke(0, "Failed to load\nError: "+responseCode.toString());
        }
    }
</code>```

答:
If you look at the API docs for the Communications module, you will see that -402 is the error code returned when the results sent back from your request were too large.

NETWORK_RESPONSE_TOO_LARGE = -402

Most devices have a very limited amount of memory and so you may need to run your request through some sort of proxy server to make the request and then trim down the results to only what you require back before sending the data to your device.

Body:
I have a GarminIQ-project. Therefore I make a request. Since yesterday I get the error code -402.

According to https://developer.garmin.com/downloads/connect-iq/monkey-c/doc/Toybox/Communications/OAuthMessage.html#responseCode-instance_method negative values stand for BLE-responses, positive are the http-requestCode. Does anybody know what -402 stands for?

I am using the Connect IQ SDK 3.0.10.

I tried to find out, what the error code is meaning. But I haven't found a list with code "-402" or "402"

Down below are the two code snippets that are used for the request. The argument url is our api-url. This works fine in a browser.

//This function makes the request
function makeRequest(url) {
        jsonFile = Communications.makeJsonRequest(url, {}, {}, method(:onReceive));
    }

//This is the callback method that is called, when data have arrived
function onReceive(responseCode, data){

        if (responseCode == 200) {
            notify.invoke(1, data);
        }else {
            System.println(responseCode);
            notify.invoke(0, "Failed to load\nError: "+responseCode.toString());
        }
    }


问:
How to send a pdf file from node/express app to Flutter app?
I have a nodejs code where I can download a pdf file since browser when I send 2 arguments in post request: fname and lname.

I am using express and pdfmake package in the backend.

```<code>const express = require('express');
const router = express.Router();

const pdfMake = require('../pdfmake/pdfmake');
const vfsFonts = require('../pdfmake/vfs_fonts');

pdfMake.vfs = vfsFonts.pdfMake.vfs;
router.post('/pdf', (req, res, next) => {
    //res.send('PDF');

    const fname = req.body.fname;
    const lname = req.body.lname;

    var documentDefinition = {
        content: [{
                image: 'data:image/png;base64 more code',
                width: 200,
                alignment: 'center'
            },
            { text: '\nGrupo de inspecciones predictivas', style: 'header', alignment: 'center' },
            { text: 'Reporte de inspección\n\n', style: 'subheader', alignment: 'center' },
            'El siguiente reporte tiene como objetivo describir los resultados encontrados a partir de la inspección en la fecha específica.',
            { text: 'Resumen del reporte', style: 'subheader' },
            {
                style: 'tableExample',
                table: {
                    widths: ['*', 'auto'],
                    body: [
                        ['Inspector:', { text: `${ fname }`, noWrap: true }],
                        ['Flota:', { text: '', noWrap: true }],
                        ['Número de flota:', { text: '', noWrap: true }],
                        ['Técnica:', { text: '', noWrap: true }],
                        ['Fecha de inicio:', { text: '', noWrap: true }],
                    ]
                }
            },
        ],
        styles: {
            header: {
                fontSize: 18,
                bold: true,
                margin: [0, 0, 0, 10]
            },
            subheader: {
                fontSize: 16,
                bold: true,
                margin: [0, 10, 0, 5]
            },
            tableExample: {
                margin: [0, 5, 0, 15]
            },
            tableHeader: {
                bold: true,
                fontSize: 13,
                color: 'black'
            }
        },
        defaultStyle: {
            // alignment: 'justify'
        }
    };

    const pdfDoc = pdfMake.createPdf(documentDefinition);
    pdfDoc.getBase64((data) => {
        res.writeHead(200, {
            'Content-Type': 'application/pdf',
            'Content-Disposition': 'attachment;filename="filename.pdf"'
        });

        const download = Buffer.from(data.toString('utf-8'), 'base64');
        res.end(download);
    });

});
</code>```

However, as I mentioned above, this code apparently only return de pdf to browsers.

I need to download the pdf file to the Android/IOS storage in the Flutter app.

答:
I have used google cloud platform to store the pdf generated by nodeJS. You can do it following the next articles: https://mzmuse.com/blog/how-to-upload-to-firebase-storage-in-node
https://github.com/googleapis/google-cloud-node/issues/2334

```<code>
    pdfDoc.getBase64((data) => {
        const keyFilename = "./myGoogleKey.json";
        const projectId = "my-name-project";
        const bucketName = `${projectId}.appspot.com`;
        var GoogleCloudStorage = require('@google-cloud/storage');

        const gcs = GoogleCloudStorage({
            projectId,
            keyFilename
        });

        const bucket = gcs.bucket(bucketName);
        const gcsname = 'reporte.pdf';
        const file = bucket.file(gcsname);
        var buff = Buffer.from(data.toString('utf-8'), 'base64');

        const stream = file.createWriteStream({
            metadata: {
                contentType: 'application/pdf'
            }
        });
        stream.on('error', (err) => {
            console.log(err);
        });
        stream.on('finish', () => {
            console.log(gcsname);
        });
        stream.end(buff);

        res.status(200).send('Succesfully.');
    });
});

</code>```

This will generate a URL and you can follow the last answer given by Esh above.

Body:
I have a nodejs code where I can download a pdf file since browser when I send 2 arguments in post request: fname and lname.

I am using express and pdfmake package in the backend.

const express = require('express');
const router = express.Router();

const pdfMake = require('../pdfmake/pdfmake');
const vfsFonts = require('../pdfmake/vfs_fonts');

pdfMake.vfs = vfsFonts.pdfMake.vfs;
router.post('/pdf', (req, res, next) => {
    //res.send('PDF');

    const fname = req.body.fname;
    const lname = req.body.lname;

    var documentDefinition = {
        content: [{
                image: 'data:image/png;base64 more code',
                width: 200,
                alignment: 'center'
            },
            { text: '\nGrupo de inspecciones predictivas', style: 'header', alignment: 'center' },
            { text: 'Reporte de inspección\n\n', style: 'subheader', alignment: 'center' },
            'El siguiente reporte tiene como objetivo describir los resultados encontrados a partir de la inspección en la fecha específica.',
            { text: 'Resumen del reporte', style: 'subheader' },
            {
                style: 'tableExample',
                table: {
                    widths: ['*', 'auto'],
                    body: [
                        ['Inspector:', { text: `${ fname }`, noWrap: true }],
                        ['Flota:', { text: '', noWrap: true }],
                        ['Número de flota:', { text: '', noWrap: true }],
                        ['Técnica:', { text: '', noWrap: true }],
                        ['Fecha de inicio:', { text: '', noWrap: true }],
                    ]
                }
            },
        ],
        styles: {
            header: {
                fontSize: 18,
                bold: true,
                margin: [0, 0, 0, 10]
            },
            subheader: {
                fontSize: 16,
                bold: true,
                margin: [0, 10, 0, 5]
            },
            tableExample: {
                margin: [0, 5, 0, 15]
            },
            tableHeader: {
                bold: true,
                fontSize: 13,
                color: 'black'
            }
        },
        defaultStyle: {
            // alignment: 'justify'
        }
    };

    const pdfDoc = pdfMake.createPdf(documentDefinition);
    pdfDoc.getBase64((data) => {
        res.writeHead(200, {
            'Content-Type': 'application/pdf',
            'Content-Disposition': 'attachment;filename="filename.pdf"'
        });

        const download = Buffer.from(data.toString('utf-8'), 'base64');
        res.end(download);
    });

});

However, as I mentioned above, this code apparently only return de pdf to browsers.

I need to download the pdf file to the Android/IOS storage in the Flutter app.

Body:
I have used google cloud platform to store the pdf generated by nodeJS. You can do it following the next articles: https://mzmuse.com/blog/how-to-upload-to-firebase-storage-in-node
https://github.com/googleapis/google-cloud-node/issues/2334

    pdfDoc.getBase64((data) => {
        const keyFilename = "./myGoogleKey.json";
        const projectId = "my-name-project";
        const bucketName = `${projectId}.appspot.com`;
        var GoogleCloudStorage = require('@google-cloud/storage');

        const gcs = GoogleCloudStorage({
            projectId,
            keyFilename
        });

        const bucket = gcs.bucket(bucketName);
        const gcsname = 'reporte.pdf';
        const file = bucket.file(gcsname);
        var buff = Buffer.from(data.toString('utf-8'), 'base64');

        const stream = file.createWriteStream({
            metadata: {
                contentType: 'application/pdf'
            }
        });
        stream.on('error', (err) => {
            console.log(err);
        });
        stream.on('finish', () => {
            console.log(gcsname);
        });
        stream.end(buff);

        res.status(200).send('Succesfully.');
    });
});

This will generate a URL and you can follow the last answer given by Esh above.


问:
Moment date format changing from Node to MongoDB
I am creating an app in node js and saving date to Mongo DB, the datatype of Mongoose, I used to save is Date.

```<code>  moment.locale("pt");
  today= moment().startOf("day").format();
</code>```

The date is printing like 2019-05-27T00:00:00-03:00

But when it is saving and I am trying to retrieve the date it is coming from mongo db like 2019-05-27T03:00:00.000Z

Now the comparison didn't work. So I am finding data based on this date and it is not working.

I am using locale for Brazil.I am keeping the user details day wise from 00:00 to next 24 hours and doing a luck draw of users. So I have huge database and want to filter data based on today date. So I need date should be saved in local timezone i.e. Brazil.

Any help would be appreciated.

答:
I suggest moving to UTC, then changing the locale, then mutating the date to match the day's beginning and then storing as ms:

const d = moment
          .utc() // Get the UTC time
          .locale('pt_BR') // Change locale to Brazil
          .startOf('day') // Go back in time to current date @ 00:00:00
          .valueOf() // Get ms value

// store d in the database

```

Body:
I am creating an app in node js and saving date to Mongo DB, the datatype of Mongoose, I used to save is Date.

  moment.locale("pt");
  today= moment().startOf("day").format();

The date is printing like 2019-05-27T00:00:00-03:00

But when it is saving and I am trying to retrieve the date it is coming from mongo db like 2019-05-27T03:00:00.000Z

Now the comparison didn't work. So I am finding data based on this date and it is not working.

I am using locale for Brazil.I am keeping the user details day wise from 00:00 to next 24 hours and doing a luck draw of users. So I have huge database and want to filter data based on today date. So I need date should be saved in local timezone i.e. Brazil.

Any help would be appreciated.


问:
Trouble passing int data from one view controller to another (segue)
I would like to pass an int data from one view controller to another one.

The problem is that the int data received in the second view controller doesn't match the first view controller's int data.

View controller 1:

```<code>import UIKit
class levelsSelector: UIViewController {
    var levelSelected: Int = 0
    var gameWanted: Int = 0

    @IBAction func level1Tapped(_ sender: Any) {
        gameWanted = 1
        performSegue(withIdentifier: "gameOn", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "gameOne" {
            let levelsSelector = segue.destination as! game
            levelsSelector.finalGame = levelSelected
            let levelsSelector2 = segue.destination as! game
            levelsSelector2.finalLevel = gameWanted
        }
    }
}
</code>```

View controller 2:

```<code>import UIKit
class game: UIViewController {
    var finalLevel: Int = 0
    var finalGame: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        print(finalLevel)
        print(finalGame)
    }
}
</code>```

答:
```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? game {
        destination.finalGame = levelSelected
        destination.finalLevel = gameWanted
    }
</code>```

Also, check: your seque identifier on a storyboard should match a string in: perform segue method

Body:
I would like to pass an int data from one view controller to another one.

The problem is that the int data received in the second view controller doesn't match the first view controller's int data.

View controller 1:

import UIKit
class levelsSelector: UIViewController {
    var levelSelected: Int = 0
    var gameWanted: Int = 0

    @IBAction func level1Tapped(_ sender: Any) {
        gameWanted = 1
        performSegue(withIdentifier: "gameOn", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "gameOne" {
            let levelsSelector = segue.destination as! game
            levelsSelector.finalGame = levelSelected
            let levelsSelector2 = segue.destination as! game
            levelsSelector2.finalLevel = gameWanted
        }
    }
}

View controller 2:

import UIKit
class game: UIViewController {
    var finalLevel: Int = 0
    var finalGame: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        print(finalLevel)
        print(finalGame)
    }
}

Body:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? game {
        destination.finalGame = levelSelected
        destination.finalLevel = gameWanted
    }

Also, check: your seque identifier on a storyboard should match a string in: perform segue method


问:
Image gets clipped while changing orientation using Qt
HI all,

I wnt to develop an ImageViewer using qt. I m trying to resize big images by scaling them. My problem is , when i change the screen orientation some part of the image gets clipped and also if i open the image in landscape mode, by default the size of image remains small even when i change back to portrait mode. What am i Doin wrong?

Please help me out. Heres the code dat i hv written

ImageViewer::ImageViewer()
{
    setAttribute(Qt::WA_DeleteOnClose);
    QAction *back = new QAction(this);
    back->setText(QString("Back"));
    connect(back,SIGNAL(triggered()),this,SLOT(close()));
    back->setSoftKeyRole(QAction::PositiveSoftKey);
    addAction(back);

```<code>imageLabel = new QLabel();
imageLabel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
imageLabel->setAlignment(/*Qt::AlignLeft|*/Qt::AlignCenter);
QWidget *widget = new QWidget;
layout=new QStackedLayout();
layout->addWidget(imageLabel);
widget->setLayout(layout);
setCentralWidget(widget);
</code>```

}

void ImageViewer::showImage(QString filePath)
 {
     QImageReader reader;
     reader.setFileName(filePath);
     QSize imageSize = reader.size();
     imageSize.scale(size(), Qt::KeepAspectRatio);
     reader.setScaledSize(imageSize);
     QImage image = reader.read();
     imageLabel->setPixmap(QPixmap::fromImage(image));
     imageLabel->adjustSize();
  }

答:
You should re-implement QLabel's resizeEvent or install event filter to it and handle QResizeEvent there
The content of showImage method should go to handler of a resize event.
Currently you are using size() of ImageViewer widget (which seems to be derived from QMainWindow), it's better to use imageLabel.size(); or the best QResizeEvent::size() as this will prevent a problem if you will change UI layout in future.</p>

Body:
HI all,

I wnt to develop an ImageViewer using qt. I m trying to resize big images by scaling them. My problem is , when i change the screen orientation some part of the image gets clipped and also if i open the image in landscape mode, by default the size of image remains small even when i change back to portrait mode. What am i Doin wrong?

Please help me out. Heres the code dat i hv written

ImageViewer::ImageViewer()
{
    setAttribute(Qt::WA_DeleteOnClose);
    QAction *back = new QAction(this);
    back->setText(QString("Back"));
    connect(back,SIGNAL(triggered()),this,SLOT(close()));
    back->setSoftKeyRole(QAction::PositiveSoftKey);
    addAction(back);

imageLabel = new QLabel();
imageLabel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
imageLabel->setAlignment(/*Qt::AlignLeft|*/Qt::AlignCenter);
QWidget *widget = new QWidget;
layout=new QStackedLayout();
layout->addWidget(imageLabel);
widget->setLayout(layout);
setCentralWidget(widget);

}

void ImageViewer::showImage(QString filePath)
 {
     QImageReader reader;
     reader.setFileName(filePath);
     QSize imageSize = reader.size();
     imageSize.scale(size(), Qt::KeepAspectRatio);
     reader.setScaledSize(imageSize);
     QImage image = reader.read();
     imageLabel->setPixmap(QPixmap::fromImage(image));
     imageLabel->adjustSize();
  }


问:
Error on the stan file compilation using R 3.6.0. and Win 10
```<code>Error in compileCode(f, code, language = language, verbose = verbose) :
  Compilation ERROR, function(s)/method(s) not created! Error in .shlib_internal(commandArgs(TRUE)) :
  C++14 standard requested but CXX14 is not defined
Calls: <Anonymous> -> .shlib_internal
Execution halted
In addition: Warning message:
In system(cmd, intern = !verbose) :
  running command 'C:/PROGRA~1/R/R-36~1.0/bin/x64/R CMD SHLIB file1a1860a0379.cpp 2> file1a1860a0379.cpp.err.txt' had status 1
Error in sink(type = "output") : invalid connection
</code>```

Some non-English page said that we can overcome by executing the following R script, but it did not work in my case:

```<code>dotR <- file.path(Sys.getenv("HOME"), ".R")
if (!file.exists(dotR))
  dir.create(dotR)
M <- file.path(dotR, "Makevars")
if (!file.exists(M))
  file.create(M)
cat("\nCXX14FLAGS=-O3 -Wno-unused-variable -Wno-unused-function",
    "CXX14 = g++ -std=c++1y",
    file = M, sep = "\n", append = TRUE)
</code>```

The above R script is same as in the following page:

https://github.com/stan-dev/rstan/issues/569

I tried to uninstall and install according to the following page, but the above error  occurred.

Rstan installation:   https://github.com/stan-dev/rstan/wiki/RStan-Getting-Started

REF; https://github.com/stan-dev/stan/issues/1613

ref: https://github.com/stan-dev/rstan/issues/633

答:
For me, the issue has been solved by adding manually the following line into the file .R/Makevars.win.</p>

```<code>CXX14 = "C:\Rtools\mingw_64\bin\g++.exe"
</code>```

Body:
Error in compileCode(f, code, language = language, verbose = verbose) :
  Compilation ERROR, function(s)/method(s) not created! Error in .shlib_internal(commandArgs(TRUE)) :
  C++14 standard requested but CXX14 is not defined
Calls: <Anonymous> -> .shlib_internal
Execution halted
In addition: Warning message:
In system(cmd, intern = !verbose) :
  running command 'C:/PROGRA~1/R/R-36~1.0/bin/x64/R CMD SHLIB file1a1860a0379.cpp 2> file1a1860a0379.cpp.err.txt' had status 1
Error in sink(type = "output") : invalid connection

Some non-English page said that we can overcome by executing the following R script, but it did not work in my case:

dotR <- file.path(Sys.getenv("HOME"), ".R")
if (!file.exists(dotR))
  dir.create(dotR)
M <- file.path(dotR, "Makevars")
if (!file.exists(M))
  file.create(M)
cat("\nCXX14FLAGS=-O3 -Wno-unused-variable -Wno-unused-function",
    "CXX14 = g++ -std=c++1y",
    file = M, sep = "\n", append = TRUE)

The above R script is same as in the following page:

https://github.com/stan-dev/rstan/issues/569

I tried to uninstall and install according to the following page, but the above error  occurred.

Rstan installation:   https://github.com/stan-dev/rstan/wiki/RStan-Getting-Started

REF; https://github.com/stan-dev/stan/issues/1613

ref: https://github.com/stan-dev/rstan/issues/633

Body:
For me, the issue has been solved by adding manually the following line into the file .R/Makevars.win.

CXX14 = "C:\Rtools\mingw_64\bin\g++.exe"


问:
the zone does not have enough resources available to fulfil the request/ the resource is not ready
the zone does not have enough resources available to fulfil the request/ the resource is not ready

I failed to start my instance (through the web browser), it gave me the error:

"The zone 'projects/XXXXX/zones/europe-west2-c' does not have enough resources available to fulfill the request. Try a different zone, or try again later."

I thought it might be the quota problem at first, after checking my quota, it showed all good. Actually, I listed the available zones, europe-west2-c was available, but I still gave a shot to move the zone. Then I tried  "gcloud compute instances move XXXX --zone europe-west2-c --destination-zone europe-west2-c", however, it still failed, popped up the error:

"ERROR: (gcloud.compute.instances.move) Instance cannot be moved while in state: TERMINATED"

Okay, terminated... then I tried to restart it by "gcloud compute instances reset XXX", the error showed in the way:

ERROR: (gcloud.compute.instances.reset) Could not fetch resource: - The resource 'projects/XXXXX/zones/europe-west2-c/instances/XXX' is not ready

I searched the error, some people solved this problem by deleting the disk. While I don't want to wipe the memory, how could I solve this problem?

BTW, I only have one instance, with one persistent disk attached.

答:
Its recommended to deploy and balance your workload across multiple zones or regions1 to reduce the likelihood of an outage, by building resilient and scalable architectures.

If you want an immediate solution, create a snapshot 2, then create an instance from the snapshot with different zone or region 3.

After migrating it you are still experiencing the same issue, I suggest to contact GCP support4.


问:
c# linq if item is in list and get matching items from list
If my list contains: english cat, french cat, japanese dog, spanish dog

and I have an item: dog

Not only do I want to see if the list contains my item, but return the items that match, so I would expect: japanese dog, spanish dog

I have got as far as seeing if the item is in the list using the following code:

```<code>if (myList.Any(myItem.ToLower().Contains)) { }
</code>```

答:
```<code>var myList = new List<string>() { " japanese dog", "spanish dog", "english cat", "french cat" };
var dog = "Dog";

if (myList.Any(t=>t.Contains(dog.ToLower()))) {
    var result = myList.Where(t => t.Contains(dog.ToLower())).ToList();
}
</code>```

Body:
If my list contains: english cat, french cat, japanese dog, spanish dog

and I have an item: dog

Not only do I want to see if the list contains my item, but return the items that match, so I would expect: japanese dog, spanish dog

I have got as far as seeing if the item is in the list using the following code:

if (myList.Any(myItem.ToLower().Contains)) { }


问:
How to search for the number of times that keywords will appear in several text between two tables
I have 2 tables and the they have the following columns.

```<code>articles: id (PK), article (longtext), date (date)

keywords: id (PK), keyword (varchar)
</code>```

For the moment I can only do that, search for a hard keyword and display the text where the word appears the most times :

```<code>SELECT * , MATCH (article) AGAINST ("keyword*" IN BOOLEAN MODE) AS relevance
FROM `articles`
WHERE MATCH (article) AGAINST ("keyword*" IN BOOLEAN MODE) ORDER BY relevance DESC LIMIT 10
</code>```

How can I search for the number of times each keyword (Table : keywords) appears in each text (Table : articles) ?

I have try that (I do not know if it's possible?) but I get "Invalid argument at AGAINST":

```<code>SELECT keyword
FROM keywords
CROSS JOIN articles
WHERE MATCH (keywords.keyword)
        AGAINST (articles.article IN NATURAL LANGUAGE MODE)
</code>```

EDIT FOR Gordon Linoff :

```<code>Table : Keywords

Id     Keyword

1      first
2      second
3      text
4      keyword
</code>```

-

```<code>Table : Articles

Id     Article

1      the first text
2      the second text
3      text text text
</code>```

Desired results :

```<code>Keyword     score

text        5
first       1
second      1
keyword     0
</code>```

答:
Storing keywords in delimited strings is just the wrong way to store them.  You should have a junction/associate table with one row per keyword in each article.

That said, sometimes we are stuck with other people's really, really, really bad data models.  If this is your data model, you should spend your effort fixing it rather than using it.

But, you can do this, with some string manipulations:

```<code>select kw.motcle,
       sum( (length(d.articles) -
             length(replace(d.articles, mc.motcle, '')
            ) / length(d.articles)
          ) as cnt
from test_motcle mc left join
     articles a
     on fin_in_set(mc.motcle, replace(d.articles, ' ', ',') > 0
group by mc.motcle
order by cnt desc;
</code>```

Body:
I have 2 tables and the they have the following columns.

articles: id (PK), article (longtext), date (date)

keywords: id (PK), keyword (varchar)

For the moment I can only do that, search for a hard keyword and display the text where the word appears the most times :

SELECT * , MATCH (article) AGAINST ("keyword*" IN BOOLEAN MODE) AS relevance
FROM `articles`
WHERE MATCH (article) AGAINST ("keyword*" IN BOOLEAN MODE) ORDER BY relevance DESC LIMIT 10

How can I search for the number of times each keyword (Table : keywords) appears in each text (Table : articles) ?

I have try that (I do not know if it's possible?) but I get "Invalid argument at AGAINST":

SELECT keyword
FROM keywords
CROSS JOIN articles
WHERE MATCH (keywords.keyword)
        AGAINST (articles.article IN NATURAL LANGUAGE MODE)

EDIT FOR Gordon Linoff :

Table : Keywords

Id     Keyword

1      first
2      second
3      text
4      keyword

-

Table : Articles

Id     Article

1      the first text
2      the second text
3      text text text

Desired results :

Keyword     score

text        5
first       1
second      1
keyword     0

Body:
Storing keywords in delimited strings is just the wrong way to store them.  You should have a junction/associate table with one row per keyword in each article.

That said, sometimes we are stuck with other people's really, really, really bad data models.  If this is your data model, you should spend your effort fixing it rather than using it.

But, you can do this, with some string manipulations:

select kw.motcle,
       sum( (length(d.articles) -
             length(replace(d.articles, mc.motcle, '')
            ) / length(d.articles)
          ) as cnt
from test_motcle mc left join
     articles a
     on fin_in_set(mc.motcle, replace(d.articles, ' ', ',') > 0
group by mc.motcle
order by cnt desc;


问:
Angular Date Pipe Printing Wrong Date After Transforming Original Date Value
I am using Angular's date pipe in my Angular 2 app in order to format the dates in a more human-friendly format. I am able to pull in dates from the API, and edit and save those dates to the API successfully. However, I'm running into an issue where the date pipe is transforming the date incorrectly - in terms of what actually gets displayed.

To clarify, if I print the raw date to the screen, it's correct. And when I edit the value that's been passed through the date pipe, the correct date gets saved. However, right after I make the edit, the transformed date value changes again (not in terms of what gets saved, just in terms of what's shown in the view) -- and it ends up being slightly off, usually by one day or so. So if I edit the value to be 09/25/2010, that'll get saved to the database, but what shows in the view is 09/24/2010. So it looks like maybe some sort of default as to timezone is causing an issue?

Here's what my view code looks like (I'll first list the date value passed through the date pipe, and then the same value, but not passed through the date pipe) for dob - date of birth:

```<code><!-- DATE PASSED THROUGH DATE PIPE -->
    <input class="app-input" [ngModel]="member.dob | date:'MM/dd/yyyy'"
        (ngModelChange)="member.dob=$event" name="inputField" type="text" />

<!-- RAW VALUE PRINTED TO SCREEN -->
    <input class="app-input" [ngModel]="member.dob"
        (ngModelChange)="member.dob=$event" name="inputField" type="text" />
</code>```

This is what ends up being printed to the screen for the code above:

So you'll notice the transformed value is off by one day. What can I add here to ensure the correct transformed value gets printed to the screen after being passed through the date pipe?

答:
When you print your date it displays 2019-01-17T00:00:00Z

Z - here implies timezone. Try avoiding this before date Pipe gets executed.

```<code>{{ getFormattedDate(originalDate) | date }}
getFormattedDate(originalDate) {
    return originalDate.toISOString().substring(0, originalDate.toISOString().length - 1);
}
</code>```

Body:
I am using Angular's date pipe in my Angular 2 app in order to format the dates in a more human-friendly format. I am able to pull in dates from the API, and edit and save those dates to the API successfully. However, I'm running into an issue where the date pipe is transforming the date incorrectly - in terms of what actually gets displayed.

To clarify, if I print the raw date to the screen, it's correct. And when I edit the value that's been passed through the date pipe, the correct date gets saved. However, right after I make the edit, the transformed date value changes again (not in terms of what gets saved, just in terms of what's shown in the view) -- and it ends up being slightly off, usually by one day or so. So if I edit the value to be 09/25/2010, that'll get saved to the database, but what shows in the view is 09/24/2010. So it looks like maybe some sort of default as to timezone is causing an issue?

Here's what my view code looks like (I'll first list the date value passed through the date pipe, and then the same value, but not passed through the date pipe) for dob - date of birth:

    <input class="app-input" [ngModel]="member.dob | date:'MM/dd/yyyy'"
        (ngModelChange)="member.dob=$event" name="inputField" type="text" />

    <input class="app-input" [ngModel]="member.dob"
        (ngModelChange)="member.dob=$event" name="inputField" type="text" />

This is what ends up being printed to the screen for the code above:

So you'll notice the transformed value is off by one day. What can I add here to ensure the correct transformed value gets printed to the screen after being passed through the date pipe?

Body:
When you print your date it displays 2019-01-17T00:00:00Z

Z - here implies timezone. Try avoiding this before date Pipe gets executed.

{{ getFormattedDate(originalDate) | date }}
getFormattedDate(originalDate) {
    return originalDate.toISOString().substring(0, originalDate.toISOString().length - 1);
}


问:
How to insert a numbered bullet list in richtextbox
I am trying to insert a numbered bullet list when a user selects the button it will increment the counter

I have searched questions online and different types of loop condition statements

```<code>Private Sub ToolStripButton16_Click(sender As Object, e As EventArgs) Handles ToolStripButton16.Click
    ToolStripButton16.CheckOnClick = False
    Dim i As Integer
    i = 0
    Dim numbList As String
    Dim buttonClickCount As Integer
    buttonClickCount = 0
    Do While (i = buttonClickCount)
        i += 1
        numbList = "            " & i & "." & vbCrLf
        RichTextBox1.AppendText(numbList)
    Loop
    buttonClickCount += 1
End Sub
</code>```

Expected result:

```<code>1.
2.
3.
4.
</code>```

答:
Probably not the most elegant solution but it should put you in the right direction.</p>

```<code>'Using a class variable here allows you to keep an "application state".
Dim buttonClickCount as Integer = 0

Private Sub ToolStripButton16_Click(sender As Object, e As EventArgs) Handles ToolStripButton16.Click

    ToolStripButton16.CheckOnClick = False

    buttonClickCount += 1
    Dim newValue As String = "            " & buttonClickCount  & "." & vbCrLf

    RichTextBox1.AppendText(newValue)
End Sub
</code>```

Body:
I am trying to insert a numbered bullet list when a user selects the button it will increment the counter

I have searched questions online and different types of loop condition statements

Private Sub ToolStripButton16_Click(sender As Object, e As EventArgs) Handles ToolStripButton16.Click
    ToolStripButton16.CheckOnClick = False
    Dim i As Integer
    i = 0
    Dim numbList As String
    Dim buttonClickCount As Integer
    buttonClickCount = 0
    Do While (i = buttonClickCount)
        i += 1
        numbList = "            " & i & "." & vbCrLf
        RichTextBox1.AppendText(numbList)
    Loop
    buttonClickCount += 1
End Sub

Expected result:

1.
2.
3.
4.

Body:
Probably not the most elegant solution but it should put you in the right direction.

'Using a class variable here allows you to keep an "application state".
Dim buttonClickCount as Integer = 0

Private Sub ToolStripButton16_Click(sender As Object, e As EventArgs) Handles ToolStripButton16.Click

    ToolStripButton16.CheckOnClick = False

    buttonClickCount += 1
    Dim newValue As String = "            " & buttonClickCount  & "." & vbCrLf

    RichTextBox1.AppendText(newValue)
End Sub


问:
Create flag indicating if year variable is in the range of start:end variables in data.table
I have a data.table with 3 date variables: year, start, end.

```<code>test <- data.table(year=2001:2003,start=c(2003,2002,2000),end=c(2003,2004,2002),x_desired=c(F,T,F))
</code>```

O want to create a new variable x, indicating, for each row, if year is in the range defined by start and end. The correct desired result is in the variable x_desired.

I imagined this could be done with:

```<code>test[,x:=(year %in% start:end)]
</code>```

but the result is clearly not correct. I wanted the ranges to be defined row-by-row, but don't know how to express that.

答:
An option is between

```<code>test[, x := between(year, start, end), 1:nrow(test)]
test
#   year start  end x_desired     x
#1: 2001  2003 2003     FALSE FALSE
#2: 2002  2002 2004      TRUE  TRUE
#3: 2003  2000 2002     FALSE FALSE
</code>```

```<code>test[, x := year >= start & year <= end]
</code>```

Or another option is Map

```<code>test[, x := unlist(do.call(Map, c(f = between, unname(.SD)))), .SDcols = year:end]
</code>```

Or with pmap from purrr

```<code>library(purrr)
test[, x := pmap_lgl(.SD[, .(x = year, left = start, right = end)], between)]
</code>```

Benchmarks

Added benchmarks on the new option (using the same dataset as @Wimpel's big data)

```<code>microbenchmark(

 wimpel = {
    DT <- copy(dt)
    DT[, x := FALSE ]
    DT[ year %between% list(start,end), x := TRUE]
    },

    akrun = {
    DT <- copy(dt)
    DT[, x := year >= start & year <= end]
    }, times = 3)
# Unit: milliseconds
#   expr      min       lq     mean   median       uq      max neval
# wimpel 23.25196 40.72112 49.29130 58.19027 62.31098 66.43168     3
#  akrun 19.56071 22.04272 22.96553 24.52473 24.66793 24.81114     3
</code>```

Body:
I have a data.table with 3 date variables: year, start, end.

test <- data.table(year=2001:2003,start=c(2003,2002,2000),end=c(2003,2004,2002),x_desired=c(F,T,F))

O want to create a new variable x, indicating, for each row, if year is in the range defined by start and end. The correct desired result is in the variable x_desired.

I imagined this could be done with:

test[,x:=(year %in% start:end)]

but the result is clearly not correct. I wanted the ranges to be defined row-by-row, but don't know how to express that.

Body:
An option is between

test[, x := between(year, start, end), 1:nrow(test)]
test
#   year start  end x_desired     x
#1: 2001  2003 2003     FALSE FALSE
#2: 2002  2002 2004      TRUE  TRUE
#3: 2003  2000 2002     FALSE FALSE

test[, x := year >= start & year <= end]

Or another option is Map

test[, x := unlist(do.call(Map, c(f = between, unname(.SD)))), .SDcols = year:end]

Or with pmap from purrr

library(purrr)
test[, x := pmap_lgl(.SD[, .(x = year, left = start, right = end)], between)]

Benchmarks

Added benchmarks on the new option (using the same dataset as @Wimpel's big data)

microbenchmark(

 wimpel = {
    DT <- copy(dt)
    DT[, x := FALSE ]
    DT[ year %between% list(start,end), x := TRUE]
    },

    akrun = {
    DT <- copy(dt)
    DT[, x := year >= start & year <= end]
    }, times = 3)
# Unit: milliseconds
#   expr      min       lq     mean   median       uq      max neval
# wimpel 23.25196 40.72112 49.29130 58.19027 62.31098 66.43168     3
#  akrun 19.56071 22.04272 22.96553 24.52473 24.66793 24.81114     3


答:
I think the big question should be why you would want it. I cannot come up with a solid design that would have a class extending something (the default example could be furniture, so for instance GardenChair extending Chair) be available in the parent class.

The whole idea is that it should be the other way around.

If you want to call the 'do_something', you should make an instance of the child, and let it call itself. If you need to enforce the do_something, try it like this:

```<code>public abstract class A{
    public abstract funcion do_something();

    public function __constructor(){
        $this->do_something();
    }

}

public class B extends A{
    public funcion do_something(){
        ...
    }
}

public class C extends A{
    public funcion do_something(){
        ...
    }
}
</code>```

Title: Calling a child object in the parent object

Body:
I want to know if I can create a child object in a parent object an use it...

I mean is it posible?

Is it a good    idea?

What do I have to care if I do    so?

I am using the child classes on their own and i want to use them in a private function of the parent class as well.

thanks

here some source to imagine what I am meaning:

class A{
    private $child_class1;
    private $child_class2;

    private function somefunction(){
        $this->child_class1 = new B();
        $this->child_class1->do_something();

        $this->child_class2 = new C();
        $this->child_class2->do_something();
    }
}

class B extends A{
    public function do_something(){
...
    }
}

class C extends A{
    public function do_something(){
...
    }
}

Body:
I think the big question should be why you would want it. I cannot come up with a solid design that would have a class extending something (the default example could be furniture, so for instance GardenChair extending Chair) be available in the parent class.

The whole idea is that it should be the other way around.

If you want to call the 'do_something', you should make an instance of the child, and let it call itself. If you need to enforce the do_something, try it like this:

public abstract class A{
    public abstract funcion do_something();

    public function __constructor(){
        $this->do_something();
    }

}

public class B extends A{
    public funcion do_something(){
        ...
    }
}

public class C extends A{
    public funcion do_something(){
        ...
    }
}


问:
Push 1st array in object to itself
I'm trying to repeat the first array in an array of arrays using:

```<code>  var scribble = [1,2,3,4]
  scribble = [scribble]

  for (var i = 0; i<3; i++){
    scribble.push(scribble[0]);
  }
</code>```

The desired result would be:
[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]

But it just pushes in [] each time. Am I missing something?

答:
You code should work. Alternatively you can make a copy of the first element from the original array and push it

var scribble = [1, 2, 3, 4];
scribble = [scribble];

for (var i = 0; i < 3; i++) {
  scribble.push([...scribble[0]]);
}

console.log(scribble)```

Title: Push 1st array in object to itself

Body:
I'm trying to repeat the first array in an array of arrays using:

  var scribble = [1,2,3,4]
  scribble = [scribble]

  for (var i = 0; i<3; i++){
    scribble.push(scribble[0]);
  }

The desired result would be:
[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]

But it just pushes in [] each time. Am I missing something?