问:
Koa-Bodyparser error when sending POST request "invalid JSON, only supports object and array"
I'm trying to send an Ajax POST request with some parameters to my koa app, but I keep getting this weird error from koa-bodyparser each time I perform the request:

Error: invalid JSON, only supports object and array
        at parse (/home/denis/WEB/nodejs/kinfs/node_modules/co-body/lib/json.js:55:13)
        at /home/denis/WEB/nodejs/kinfs/node_modules/co-body/lib/json.js:41:16
        at process._tickCallback (internal/process/next_tick.js:103:7)

and on the client side I get this error printed to the browser console:

jquery-1.12.3.js:10261 POST http://localhost:3000/api/v1/books 400
  (Bad Request)

I send the usual jquery ajax request like this:

```<code>$.ajax({
  url: '/api/v1/books',
  data: {test: 'test-data'},
  dataType: 'json',
  contentType:  'application/json',
  type: 'POST'
});
</code>```

and the code that processes the request is below:

```<code>const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const router = require('koa-router')();
const api = require('koa-router')({
    prefix: '/api/v1'
});
// I require 'koa-router' twice because
// 'api' and 'router' objects are originally located
// in different files, but here I've put them all
// together for conciseness.

router
    .get('home', '/', async (ctx, next) => { //...// })
    .get('test', '/test', async (ctx, next) => { //...// });

const app = new Koa();

api
    .get('/books', async (ctx, next) => {
        const books = await executePLSQL();
        const data = {
            data: prepareData(books)
        };
        ctx.body = JSON.stringify(data);
    })
    .post('/books', async (ctx, next) => {
        console.log('Test POST request:');
        console.log(ctx.request.body);
        console.log(ctx.params);

        ctx.status = 201;
    });

app
    .use(bodyParser())
    .use(router.routes())
    .use(api.routes())
    .use(api.allowedMethods())
    .use(router.allowedMethods());

app.listen(3000);
</code>```

Sending GET requests works fine, but when I try to send a POST request, I get the error described above.

And here's another thing:

When I do not specify content-type in my Ajax request, the error does not appear. Insted, I get this printed to the node.js console (note the console.log calls in api.post(...)):

```<code>Test POST request:
{ undefined: '' }
{}
</code>```

I don't seem to understand what is going on here and why such error is appearing.

Could you please explain why such error is appearing and help me to resolve that issue?

答:
Not sure if it'll help anyone I was trying to send a string in the data to Google Cloud Task so changing to sending to object.

```<code>await client.createTask(
            { internalId: payload.internalId },
            payload.delayInSeconds,
            {
                headers: {
                    Authorization: `Bearer ${process.env.AUTH_TOKEN}1`,
                    "Content-Type": "application/json",
                },
            },
        );
</code>```

Something like this.
The thing to learn here is not to send string in body instead of an valid object.
Would have been a comment but it won't get a much attention.

Body:
I'm trying to send an Ajax POST request with some parameters to my koa app, but I keep getting this weird error from koa-bodyparser each time I perform the request:

Error: invalid JSON, only supports object and array
        at parse (/home/denis/WEB/nodejs/kinfs/node_modules/co-body/lib/json.js:55:13)
        at /home/denis/WEB/nodejs/kinfs/node_modules/co-body/lib/json.js:41:16
        at process._tickCallback (internal/process/next_tick.js:103:7)

and on the client side I get this error printed to the browser console:

jquery-1.12.3.js:10261 POST http://localhost:3000/api/v1/books 400
  (Bad Request)

I send the usual jquery ajax request like this:

$.ajax({
  url: '/api/v1/books',
  data: {test: 'test-data'},
  dataType: 'json',
  contentType:  'application/json',
  type: 'POST'
});

and the code that processes the request is below:

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const router = require('koa-router')();
const api = require('koa-router')({
    prefix: '/api/v1'
});
// I require 'koa-router' twice because
// 'api' and 'router' objects are originally located
// in different files, but here I've put them all
// together for conciseness.

router
    .get('home', '/', async (ctx, next) => { //...// })
    .get('test', '/test', async (ctx, next) => { //...// });

const app = new Koa();

api
    .get('/books', async (ctx, next) => {
        const books = await executePLSQL();
        const data = {
            data: prepareData(books)
        };
        ctx.body = JSON.stringify(data);
    })
    .post('/books', async (ctx, next) => {
        console.log('Test POST request:');
        console.log(ctx.request.body);
        console.log(ctx.params);

        ctx.status = 201;
    });

app
    .use(bodyParser())
    .use(router.routes())
    .use(api.routes())
    .use(api.allowedMethods())
    .use(router.allowedMethods());

app.listen(3000);

Sending GET requests works fine, but when I try to send a POST request, I get the error described above.

And here's another thing:

When I do not specify content-type in my Ajax request, the error does not appear. Insted, I get this printed to the node.js console (note the console.log calls in api.post(...)):

Test POST request:
{ undefined: '' }
{}

I don't seem to understand what is going on here and why such error is appearing.

Could you please explain why such error is appearing and help me to resolve that issue?

Body:
Not sure if it'll help anyone I was trying to send a string in the data to Google Cloud Task so changing to sending to object.

await client.createTask(
            { internalId: payload.internalId },
            payload.delayInSeconds,
            {
                headers: {
                    Authorization: `Bearer ${process.env.AUTH_TOKEN}1`,
                    "Content-Type": "application/json",
                },
            },
        );

Something like this.
The thing to learn here is not to send string in body instead of an valid object.
Would have been a comment but it won't get a much attention.


来源: stackexchange

问:
make site available only from given ip
Is it possible to set my entaire web application available only from given ip address ? Can I use global.asax or something to place the code only in one place and be able to remove this freely ?

Thanks for any hints

答:
If you do not have access to iis, or you need to control it from asp.net, you can check on BeginRequest the REMOTE_HOST or the REMOTE_ADDR

```<code>protected void Application_BeginRequest(Object sender, EventArgs e)
{
    HttpApplication app = (HttpApplication)sender;

    if(app.Request.ServerVariables["REMOTE_ADDR"] != "1.1.1.1")
    {
        HttpContext.Current.Response.End();
        return
    }
}
</code>```

but you must think also about Ip spoofing

Ps:REMOTE_HOST and REMOTE_ADDR return to me always the IP only, probably because iis need some extra setup for get the address on the host parametre

ContentLicense: CC BY-SA 3.0

Title: make site available only from given ip

Body:
If you do not have access to iis, or you need to control it from asp.net, you can check on BeginRequest the REMOTE_HOST or the REMOTE_ADDR

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    HttpApplication app = (HttpApplication)sender;

    if(app.Request.ServerVariables["REMOTE_ADDR"] != "1.1.1.1")
    {
        HttpContext.Current.Response.End();
        return
    }
}

but you must think also about Ip spoofing

Ps:REMOTE_HOST and REMOTE_ADDR return to me always the IP only, probably because iis need some extra setup for get the address on the host parametre


问:
Create all subsets from string- recursively
I am trying to create all subset of a given string recursively.
Given string = 'aab', we generate all subsets for the characters being distinct.
The answer is: ["", "b", "a", "ab", "ba", "a", "ab", "ba", "aa", "aa", "aab", "aab", "aba", "aba", "baa", "baa"].
I have been looking at several solutions  such as this one
but I am trying to make the function accept a single variable- only the string and work with that, and can't figure out how.
I have been also looking at this solution of a similar problem, but as it deals with lists and not strings I seem to have some trouble transforming that to accept and generate strings.
Here is my code, in this example I can't connect the str to the list. Hence my question.
I edited the input and the output.

```<code>def gen_all_strings(word):

    if len(word) == 0:
        return ''

    rest = gen_all_strings(word[1:])

    return  rest + [[ + word[0]] + dummy for dummy in rest]
</code>```

答:
```<code>from itertools import *

def recursive_product(s,r=None,i=0):
    if r is None:
        r = []
    if i>len(s):
        return r
    for c in product(s, repeat=i):
        r.append("".join(c))
    return recursive_product(s,r,i+1)

print(recursive_product('ab'))
print(recursive_product('abc'))
</code>```

Output:

['', 'a', 'b', 'aa', 'ab', 'ba', 'bb']

['', 'a', 'b', 'c', 'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc', 'aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa', 'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab', 'cac', 'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc']

To be honest it feels really forced to use recursion in this case, a much simpler version that has the same results:

```<code>nonrecursive_product = lambda s: [''.join(c)for i in range(len(s)+1) for c in product(s,repeat=i)]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create all subset of a given string recursively.
Given string = 'aab', we generate all subsets for the characters being distinct.
The answer is: ["", "b", "a", "ab", "ba", "a", "ab", "ba", "aa", "aa", "aab", "aab", "aba", "aba", "baa", "baa"].
I have been looking at several solutions  such as this one
but I am trying to make the function accept a single variable- only the string and work with that, and can't figure out how.
I have been also looking at this solution of a similar problem, but as it deals with lists and not strings I seem to have some trouble transforming that to accept and generate strings.
Here is my code, in this example I can't connect the str to the list. Hence my question.
I edited the input and the output.

def gen_all_strings(word):

    if len(word) == 0:
        return ''

    rest = gen_all_strings(word[1:])

    return  rest + [[ + word[0]] + dummy for dummy in rest]

Body:
from itertools import *

def recursive_product(s,r=None,i=0):
    if r is None:
        r = []
    if i>len(s):
        return r
    for c in product(s, repeat=i):
        r.append("".join(c))
    return recursive_product(s,r,i+1)

print(recursive_product('ab'))
print(recursive_product('abc'))

Output:

['', 'a', 'b', 'aa', 'ab', 'ba', 'bb']

['', 'a', 'b', 'c', 'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc', 'aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa', 'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab', 'cac', 'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc']

To be honest it feels really forced to use recursion in this case, a much simpler version that has the same results:

nonrecursive_product = lambda s: [''.join(c)for i in range(len(s)+1) for c in product(s,repeat=i)]


问:
How to execute a method with a button click
How can I add a function to a button that will run a method I've created. I want to write out an array into a message dialog box with a press of a button, but I don't seem to be getting anywhere so i turned to stackoverflow for some help, since googling didn't really help me with my problem.

```<code> static void Tractors(Tractor[] tractors)
    {

        for (int i = 0; i < tractors.Length; i++)
        {
            Console.WriteLine((i + 1) + ", " + tractors[i].ToString());
        }
    }
</code>```

This is my function that writes out the table of "Tractors".

```<code> private void button1_Click(object sender, EventArgs e)
        {

        }
</code>```

What should I write into the button1_click method so that it would work?

答:
You would call Tractor() the exactly same way you call Console.WriteLine(). Both are static functions.

However the function is utterly messed up and propably not salvageable. The proper name would be printTractorsToConsole(). As it contains the Console.WriteLine() call, it is strongly tied to Console Applications - avoid tying functions to one Display Technology like that.

You need a more general function that creates and returns a string. You can then send that string to WriteLine(), assign it to Label.Text or wherever else you want the string to be.  Strings primarily exist for intput from or output towards the user - and there is too many ways to get it to them.

```<code>//Not tested against a compiler, may contain syntax errors
static string TractorArrayToString(Tractor[] tractors){
    string output = "";

    for (int i = 0; i < tractors.Length; i++)
    {
        output += (i + 1) + ", " + tractors[i].ToString()) + Environment.NewLine;
    }

    return output;
}
</code>```

But even function might be a bad idea, as that function would tie all representations to a single format. Generally you would write that loop directly into the Click Event. But this function looks like it is for printing for debug purposes, so it might work.

Body:
How can I add a function to a button that will run a method I've created. I want to write out an array into a message dialog box with a press of a button, but I don't seem to be getting anywhere so i turned to stackoverflow for some help, since googling didn't really help me with my problem.

 static void Tractors(Tractor[] tractors)
    {

        for (int i = 0; i < tractors.Length; i++)
        {
            Console.WriteLine((i + 1) + ", " + tractors[i].ToString());
        }
    }

This is my function that writes out the table of "Tractors".

 private void button1_Click(object sender, EventArgs e)
        {

        }

What should I write into the button1_click method so that it would work?

Body:
You would call Tractor() the exactly same way you call Console.WriteLine(). Both are static functions.

However the function is utterly messed up and propably not salvageable. The proper name would be printTractorsToConsole(). As it contains the Console.WriteLine() call, it is strongly tied to Console Applications - avoid tying functions to one Display Technology like that.

You need a more general function that creates and returns a string. You can then send that string to WriteLine(), assign it to Label.Text or wherever else you want the string to be.  Strings primarily exist for intput from or output towards the user - and there is too many ways to get it to them.

//Not tested against a compiler, may contain syntax errors
static string TractorArrayToString(Tractor[] tractors){
    string output = "";

    for (int i = 0; i < tractors.Length; i++)
    {
        output += (i + 1) + ", " + tractors[i].ToString()) + Environment.NewLine;
    }

    return output;
}

But even function might be a bad idea, as that function would tie all representations to a single format. Generally you would write that loop directly into the Click Event. But this function looks like it is for printing for debug purposes, so it might work.


问:
varA = varA + varB doesn't work in typescript
I'm making a running total calculator method for my angular project in ts,

```<code>Total(){
let t: any;
for (let n = 0; n < this.checkoutItems.length; n++) {
  let key = this.checkoutItems[n].item_id ;
  this.itemsService.getCheckoutItem(key, 2).subscribe((response: any) => {
  this.checkoutItem = response;
  let y = localStorage.getItem(key);
  console.log("y:");
  console.log(y);
  let x=+y;
  console.log("x:");
  console.log(x);
  let a= +this.checkoutItems[n].price;
  console.log("a:");
  console.log(a);
  let b = a*x;
  console.log("b:");
  console.log(b);
   t +=b;
  console.log("t:");
  console.log(t);
  })
}
}
</code>```

Everything works fine upto the console log of b, they print the desired output on my console but for some reason the console log of t returns NaN ? why does that happen? I'm sorry I'm new to typescript.

答:
Your problem can really be demonstrated in just two lines:

let t: any;
t + 42
//=> NaN
```

<p>The reason you get <code>NaN</code> is that uninitialized variables evaluate to <code>undefined</code> and <code>undefined</code> is converted to <code>NaN</code> in a numeric context and <code>NaN + anything</code> is <code>NaN</code>.</p>

<p>The reason why TypeScript was not able to help you and point out your mistake is that by explicitly typing <code>t</code> as <code>any</code>, you have essentially told TypeScript: "I have no idea what this is, you have no idea what this is, so let's just pretend everything is fine, okay?" In other words, you have told TypeScript to not help you.</p>

<p>If you had typed it as a <code>number</code>, for example, this would have happened:</p>

<pre class="lang-js prettyprint-override"><code>let t: number;
t + 42
// ERROR: Variable 't' is used before being assigned.
</code>```

The correct way would be to initialize t to the identity value of the operation you are performing. (For addition, the identity is 0.)

let t: number = 0; // Or just `let t = 0` and the type will be inferred correctly
t + 42
//=> 42
```

The really correct solution solution would probably be some form of a reduce over this.checkoutItems.

Body:
I'm making a running total calculator method for my angular project in ts,

Total(){
let t: any;
for (let n = 0; n < this.checkoutItems.length; n++) {
  let key = this.checkoutItems[n].item_id ;
  this.itemsService.getCheckoutItem(key, 2).subscribe((response: any) => {
  this.checkoutItem = response;
  let y = localStorage.getItem(key);
  console.log("y:");
  console.log(y);
  let x=+y;
  console.log("x:");
  console.log(x);
  let a= +this.checkoutItems[n].price;
  console.log("a:");
  console.log(a);
  let b = a*x;
  console.log("b:");
  console.log(b);
   t +=b;
  console.log("t:");
  console.log(t);
  })
}
}

Everything works fine upto the console log of b, they print the desired output on my console but for some reason the console log of t returns NaN ? why does that happen? I'm sorry I'm new to typescript.

Body:
Your problem can really be demonstrated in just two lines:

let t: any;
t + 42
//=> NaN

The reason you get NaN is that uninitialized variables evaluate to undefined and undefined is converted to NaN in a numeric context and NaN + anything is NaN.

The reason why TypeScript was not able to help you and point out your mistake is that by explicitly typing t as any, you have essentially told TypeScript: "I have no idea what this is, you have no idea what this is, so let's just pretend everything is fine, okay?" In other words, you have told TypeScript to not help you.

If you had typed it as a number, for example, this would have happened:

let t: number;
t + 42
// ERROR: Variable 't' is used before being assigned.

The correct way would be to initialize t to the identity value of the operation you are performing. (For addition, the identity is 0.)

let t: number = 0; // Or just `let t = 0` and the type will be inferred correctly
t + 42
//=> 42

The really correct solution solution would probably be some form of a reduce over this.checkoutItems.


问:
Selecting two highest values from a list, whilst keeping a record of their index positions?
I am trying to get the highest and the second highest values from list a. I also need to keep track of what the index value was for each of these values.

For example:

```<code>a = [1,2,7,9,3,4]
</code>```

Desired output:

```<code>maxVal = 9
secondMax = 7

index_max = 3
index_secondMax = 2
</code>```

Does any one have any suggestions for how to approach this, can't seem to figure out a way of doing it.

答:
Numpy is quite god for things like this</p>

```<code>import numpy as np

a = [1,2,7,9,3,4]

b = np.sort([(v, i) for i, v in enumerate(a)])

maxVal = b[-1, 0]
index_max = b[-1, 1]

secondMax = b[-2, 0]
index_sec_max = b[-2, 1]

print(maxVal)
print(secondMax)

print(index_max)
print(index_sec_max)
</code>```

Body:
I am trying to get the highest and the second highest values from list a. I also need to keep track of what the index value was for each of these values.

For example:

a = [1,2,7,9,3,4]

Desired output:

maxVal = 9
secondMax = 7

index_max = 3
index_secondMax = 2

Does any one have any suggestions for how to approach this, can't seem to figure out a way of doing it.

Body:
Numpy is quite god for things like this

import numpy as np

a = [1,2,7,9,3,4]

b = np.sort([(v, i) for i, v in enumerate(a)])

maxVal = b[-1, 0]
index_max = b[-1, 1]

secondMax = b[-2, 0]
index_sec_max = b[-2, 1]

print(maxVal)
print(secondMax)

print(index_max)
print(index_sec_max)


问:
Force a new database name on import with mysql and php
I have a large database dump.sql file I am importing from the command line in linux. The .sql dump creates a database named "database_name". I want to import the database from this .sql file but I want to force it to a database with a different name, as the script currently overwrites "database_name" and "database_name" already exists and has data I can't overwrite.

Is the best option to find and replace within the .sql file?  What is the best method for that since the file is 50mb.  I can't simply file_get_contents() on that shiz?  Can I?

Below are the lines I would have to replace in the .sql file:

```<code>CREATE DATABASE /*!32312 IF NOT EXISTS*/ `database_name` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `database_name`;
</code>```

答:
You have to replace the database_name in the .sql file.

You can do that from the shell with sed 's/database_name/new_database_name/' dumpFile.sql > newDumpFile.sql

this is the correct answer to my question but was provided by 'fab' in the comments of another answer.

NOTE: As @Diego pointed out in the comments, if the string 'database_name' shows up anywhere else in this .sql dump, it will be replaced there as well. You may want to view the contents of the .sql file using less file_name.sql and then be more explicit with your find/replace.

Body:
I have a large database dump.sql file I am importing from the command line in linux. The .sql dump creates a database named "database_name". I want to import the database from this .sql file but I want to force it to a database with a different name, as the script currently overwrites "database_name" and "database_name" already exists and has data I can't overwrite.

Is the best option to find and replace within the .sql file?  What is the best method for that since the file is 50mb.  I can't simply file_get_contents() on that shiz?  Can I?

Below are the lines I would have to replace in the .sql file:

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `database_name` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `database_name`;


问:
Entity Framework database creation C#
I'm having a bit of trouble getting my code to create a database using Entity Framework. Not sure how or why, but I think I'm missing something.

SecurityDataLayer.cs

```<code>namespace SecurityDoorDatabase.DBConnection
{
    class SecurityDataLayer
    {
        public class SecurityDoorDBContext : DbContext
        {
            public DbSet<Person> Perons { get; set; }
            public DbSet<Employee> Employees { get; set; }
            public DbSet<Door> Doors { get; set; }
            public DbSet<DoorSecurity> DoorSecurities { get; set; }
            public DbSet<SecurityInput> SecurityInputs { get; set; }
            public DbSet<SecurityLevel> SecurityLevels { get; set; }
            public DbSet<SecurityCards> SecurityCard { get; set; }
            public DbSet<FingerPrints> FingerPrint { get; set; }
        }
    }
}
</code>```

Example of one of the many CS files I'm using.

```<code>class SecurityCards
{
    int securityCardID;
    int securityCardScan;

    public int SecurityCardID { get => securityCardID; set => securityCardID = value; }
    public int SecurityCardScan { get => securityCardScan; set => securityCardScan = value; }

    public SecurityCards(int securityCardID, int securityCardScan)
    {
        SecurityCardID = securityCardID;
        SecurityCardScan = securityCardScan;
    }
}
</code>```

The usings for every CS file.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data.Common;
using System.Collections.ObjectModel;
</code>```

Program.CS

```<code>class Program
{
    static void Main(string[] args)
    {
        Employee dingleberrySmith = new Employee(0, "Dingleberry", "Smithson", "Smith", 0, "IT Tech",
            new FingerPrints(0,134), new SecurityCards(0,134), new SecurityLevel(4, 7));
        Employee narsetSarkhan = new Employee(0, "Narset", "", "Sarkhan", 0, "Secretary",
            new FingerPrints(0, 0), new SecurityCards(0, 0), new SecurityLevel(1, 1));

        Door door597 = new Door(598, 597, "Fifth Floor", 598, 7, 7, "Door Code", "Security Card", "Finger Print");
        Door door227 = new Door(228, 227, "Second Floor", 228, 2, 2, "Door Code", "Security Card", "Finger Print");
        Door doorEntrance = new Door(0, 0, "Lobby", 0, 0, 0, "", "", "");
        CanEmployeeGoThroughDoor(dingleberrySmith, door227);
        CanEmployeeGoThroughDoor(dingleberrySmith, door597);
        CanEmployeeGoThroughDoor(narsetSarkhan, door597);
        CanEmployeeGoThroughDoor(narsetSarkhan, doorEntrance);

        Console.ReadLine();
    }

    public static void CanEmployeeGoThroughDoor(Employee employee, Door door)
    {
        if ((employee.EmployeeSecurityLevel.SecurityLevelID >= door.SecurityLevelID) ||(employee.EmployeeSecurityLevel.SecurityLevelID >= door.SecurityLevelID && employee.EmployeeFingerPrint.FingerPrintScan > 0 && door.SecurityInputTertiary == "Finger Print" && employee.EmployeeSecurityCard.SecurityCardScan > 0 && door.SecurityInputSecondary == "Security Card") || (employee.EmployeeSecurityLevel.SecurityLevelID >= door.SecurityLevelID&& employee.EmployeeSecurityCard.SecurityCardScan > 0 && door.SecurityInputSecondary == "Security Card") || (employee.EmployeeSecurityLevel.SecurityLevelID >= door.SecurityLevelID && employee.EmployeeFingerPrint.FingerPrintScan > 0 && door.SecurityInputTertiary == "Finger Print"))
        {
            Console.WriteLine("Access Granted");
        }
        else
        {
            Console.WriteLine("Access Denied");
        }
    }
}
</code>```

If someone could help me figure out how to make the database connections and where to put them, that'd be most appreciated.

答:
You should add connection string to app.config file or web.config file. I will explain for app.config file and for EF code first.

Add this into <configuration> on app.config file.

```<code><connectionStrings>
        <add name="ConnectionStringName" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=DbName; Integrated Security=True; MultipleActiveResultSets=True;" providerName="System.Data.SqlClient"/>
</connectionStrings>
</code>```

And your SecurityDataLayer.cs should be like:

```<code>namespace SecurityDoorDatabase.DBConnection
{
    class SecurityDataLayer
    {
        public class SecurityDoorDBContext : DbContext
        {
            public SecurityDoorDBContext() : base("name=ConnectionStringName")
            {
            }

            public DbSet<Person> Perons { get; set; }
            public DbSet<Employee> Employees { get; set; }
            public DbSet<Door> Doors { get; set; }
            public DbSet<DoorSecurity> DoorSecurities { get; set; }
            public DbSet<SecurityInput> SecurityInputs { get; set; }
            public DbSet<SecurityLevel> SecurityLevels { get; set; }
            public DbSet<SecurityCards> SecurityCard { get; set; }
            public DbSet<FingerPrints> FingerPrint { get; set; }
        }
    }
}
</code>```

Title: Entity Framework database creation C#

Body:
I'm having a bit of trouble getting my code to create a database using Entity Framework. Not sure how or why, but I think I'm missing something.

SecurityDataLayer.cs

namespace SecurityDoorDatabase.DBConnection
{
    class SecurityDataLayer
    {
        public class SecurityDoorDBContext : DbContext
        {
            public DbSet<Person> Perons { get; set; }
            public DbSet<Employee> Employees { get; set; }
            public DbSet<Door> Doors { get; set; }
            public DbSet<DoorSecurity> DoorSecurities { get; set; }
            public DbSet<SecurityInput> SecurityInputs { get; set; }
            public DbSet<SecurityLevel> SecurityLevels { get; set; }
            public DbSet<SecurityCards> SecurityCard { get; set; }
            public DbSet<FingerPrints> FingerPrint { get; set; }
        }
    }
}

Example of one of the many CS files I'm using.

class SecurityCards
{
    int securityCardID;
    int securityCardScan;

    public int SecurityCardID { get => securityCardID; set => securityCardID = value; }
    public int SecurityCardScan { get => securityCardScan; set => securityCardScan = value; }

    public SecurityCards(int securityCardID, int securityCardScan)
    {
        SecurityCardID = securityCardID;
        SecurityCardScan = securityCardScan;
    }
}

The usings for every CS file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data.Common;
using System.Collections.ObjectModel;

Program.CS

class Program
{
    static void Main(string[] args)
    {
        Employee dingleberrySmith = new Employee(0, "Dingleberry", "Smithson", "Smith", 0, "IT Tech",
            new FingerPrints(0,134), new SecurityCards(0,134), new SecurityLevel(4, 7));
        Employee narsetSarkhan = new Employee(0, "Narset", "", "Sarkhan", 0, "Secretary",
            new FingerPrints(0, 0), new SecurityCards(0, 0), new SecurityLevel(1, 1));

        Door door597 = new Door(598, 597, "Fifth Floor", 598, 7, 7, "Door Code", "Security Card", "Finger Print");
        Door door227 = new Door(228, 227, "Second Floor", 228, 2, 2, "Door Code", "Security Card", "Finger Print");
        Door doorEntrance = new Door(0, 0, "Lobby", 0, 0, 0, "", "", "");
        CanEmployeeGoThroughDoor(dingleberrySmith, door227);
        CanEmployeeGoThroughDoor(dingleberrySmith, door597);
        CanEmployeeGoThroughDoor(narsetSarkhan, door597);
        CanEmployeeGoThroughDoor(narsetSarkhan, doorEntrance);

        Console.ReadLine();
    }

    public static void CanEmployeeGoThroughDoor(Employee employee, Door door)
    {
        if ((employee.EmployeeSecurityLevel.SecurityLevelID >= door.SecurityLevelID) ||(employee.EmployeeSecurityLevel.SecurityLevelID >= door.SecurityLevelID && employee.EmployeeFingerPrint.FingerPrintScan > 0 && door.SecurityInputTertiary == "Finger Print" && employee.EmployeeSecurityCard.SecurityCardScan > 0 && door.SecurityInputSecondary == "Security Card") || (employee.EmployeeSecurityLevel.SecurityLevelID >= door.SecurityLevelID&& employee.EmployeeSecurityCard.SecurityCardScan > 0 && door.SecurityInputSecondary == "Security Card") || (employee.EmployeeSecurityLevel.SecurityLevelID >= door.SecurityLevelID && employee.EmployeeFingerPrint.FingerPrintScan > 0 && door.SecurityInputTertiary == "Finger Print"))
        {
            Console.WriteLine("Access Granted");
        }
        else
        {
            Console.WriteLine("Access Denied");
        }
    }
}

If someone could help me figure out how to make the database connections and where to put them, that'd be most appreciated.

Body:
You should add connection string to app.config file or web.config file. I will explain for app.config file and for EF code first.

Add this into <configuration> on app.config file.

<connectionStrings>
        <add name="ConnectionStringName" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=DbName; Integrated Security=True; MultipleActiveResultSets=True;" providerName="System.Data.SqlClient"/>
</connectionStrings>

And your SecurityDataLayer.cs should be like:

namespace SecurityDoorDatabase.DBConnection
{
    class SecurityDataLayer
    {
        public class SecurityDoorDBContext : DbContext
        {
            public SecurityDoorDBContext() : base("name=ConnectionStringName")
            {
            }

            public DbSet<Person> Perons { get; set; }
            public DbSet<Employee> Employees { get; set; }
            public DbSet<Door> Doors { get; set; }
            public DbSet<DoorSecurity> DoorSecurities { get; set; }
            public DbSet<SecurityInput> SecurityInputs { get; set; }
            public DbSet<SecurityLevel> SecurityLevels { get; set; }
            public DbSet<SecurityCards> SecurityCard { get; set; }
            public DbSet<FingerPrints> FingerPrint { get; set; }
        }
    }
}


问:
Return all dates between two dates as a list in flutter date range picker
I got only two dates form flutter date_range_picker but I want a list of date between two selected dates. Thanks for your answers </p>

答:
I always do like this:</p>

```<code>final today = DateTime.now();
final monthAgo = DateTime(today.year, today.month - 1, today.day);

final List<DateTime> days = [];
for (int i = 0; i <= today.difference(monthAgo).inDays; i++) {
  days.add(monthAgo.add(Duration(days: i)));
}
</code>```

Body:
I always do like this:

final today = DateTime.now();
final monthAgo = DateTime(today.year, today.month - 1, today.day);

final List<DateTime> days = [];
for (int i = 0; i <= today.difference(monthAgo).inDays; i++) {
  days.add(monthAgo.add(Duration(days: i)));
}


问:
Why does running `flask run` on Windows result in "flask is not recognized as an internal or external command, operable program or batch file"
I needed to setup Flask for windows, so I ran the following commands:

```<code>set FLASK_APP=application.py
set FLASK_DEBUG=1
set DATABASE_URL='postgres.......' =>(the credential given by the Heroku account)
flask run
</code>```

But when I hit enter on the flask run, I get an error that says -

flask is not recognized as an internal or external command, operable program or batch file

Why is this not working? I've been trying to work on it but I'm still having the same error message.

What could be the issue?

答:
I faced the same issue. Perhaps you missed the message you received while installing 'flask'. While running pip install flask I received

WARNING: The script flask.exe is installed in
  'C:\Users\ankur.kulshrestha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\Scripts'
  which is not on PATH.   Consider adding this directory to PATH or, if
  you prefer to suppress this warning, use --no-warn-script-location.

Either set the path in your PATH env variable or use the complete path while running flask run.

Body:
I needed to setup Flask for windows, so I ran the following commands:

set FLASK_APP=application.py
set FLASK_DEBUG=1
set DATABASE_URL='postgres.......' =>(the credential given by the Heroku account)
flask run

But when I hit enter on the flask run, I get an error that says -

flask is not recognized as an internal or external command, operable program or batch file

Why is this not working? I've been trying to work on it but I'm still having the same error message.

What could be the issue?


问:
Can we serialize the updated object in Scala?
I am trying to serialize the updated values for an object in Scala. Although the serialized file shows the updated string but when I deserialize it I am getting the initial values not the updated one.

```<code>import java.io._
object AnObject extends Serializable
{
    var x = 2.0
    var s = "Here's a string"

} // AnObject object

object ObjectSerialization extends App
{
    AnObject.s = "This is an updated string"
    val oos = new ObjectOutputStream (new FileOutputStream ("src/AnObject.ser"))
    oos.writeObject (AnObject)
    oos.close ()
} // ObjectDeserialization object

object ObjectDeserialization extends App {
    val ois = new ObjectInputStream(new FileInputStream("src/AnObject.ser"))
    val obj = ois.readObject.asInstanceOf[AnObject.type]
    ois.close

    println(obj.s)
}
</code>```

I am expecting output "This is an updated string". Kindly let me know if you have any idea. Thanks

答: object creates a singleton, you can't simply serialize and deserialize multiple instances of a singleton. Try the same with a class instead of object, this should work

Body:
I am trying to serialize the updated values for an object in Scala. Although the serialized file shows the updated string but when I deserialize it I am getting the initial values not the updated one.

import java.io._
object AnObject extends Serializable
{
    var x = 2.0
    var s = "Here's a string"

} // AnObject object

object ObjectSerialization extends App
{
    AnObject.s = "This is an updated string"
    val oos = new ObjectOutputStream (new FileOutputStream ("src/AnObject.ser"))
    oos.writeObject (AnObject)
    oos.close ()
} // ObjectDeserialization object

object ObjectDeserialization extends App {
    val ois = new ObjectInputStream(new FileInputStream("src/AnObject.ser"))
    val obj = ois.readObject.asInstanceOf[AnObject.type]
    ois.close

    println(obj.s)
}

I am expecting output "This is an updated string". Kindly let me know if you have any idea. Thanks


问:
how to sort array object based on another object
it possible to sort and rearrange an array that looks like this:

```<code>items:[{
     id: '5',
     name: 'wa'
     },{
     id: '3',
     name: 'ads'
     },{
     id: '1',
     name: 'fdf'
     }]
</code>```

to match the arrangement of this object:

```<code> Item_sequence: {
        "5": {index: 1},
        "1": { index: 0 }
      }
</code>```

Here is the output I’m looking for:

```<code> items:[{
     id: '1',
     name: 'fdf'
     },{
     id: '5',
     name: 'wa'
     },{
     id: '3',
     name: 'ads'
     }]
</code>```

答:
JavaScript specifically, First you have to apply loop to your array "items":

```<code>`
 let newArr = [];
 items.map(obj=>{

//obj will be the element of items array, here it is an object.

 if(Item_sequence.obj[id] !== undefined) {
   /*this condition will be satisfied when id from items array will be present as a
   key in Item_sequence array*/

   insertAt(newArr, Item_sequence.obj[id] , obj)
  }
 else{
   newArr.push(obj);
 }
})
//After checking on whole array here you assign a newArr value to items array.
items=newArr;
</code>```

Hope that it will help you.

Body:
it possible to sort and rearrange an array that looks like this:

items:[{
     id: '5',
     name: 'wa'
     },{
     id: '3',
     name: 'ads'
     },{
     id: '1',
     name: 'fdf'
     }]

to match the arrangement of this object:

 Item_sequence: {
        "5": {index: 1},
        "1": { index: 0 }
      }

Here is the output I’m looking for:

 items:[{
     id: '1',
     name: 'fdf'
     },{
     id: '5',
     name: 'wa'
     },{
     id: '3',
     name: 'ads'
     }]

Body:
JavaScript specifically, First you have to apply loop to your array "items":

`
 let newArr = [];
 items.map(obj=>{

//obj will be the element of items array, here it is an object.

 if(Item_sequence.obj[id] !== undefined) {
   /*this condition will be satisfied when id from items array will be present as a
   key in Item_sequence array*/

   insertAt(newArr, Item_sequence.obj[id] , obj)
  }
 else{
   newArr.push(obj);
 }
})
//After checking on whole array here you assign a newArr value to items array.
items=newArr;

Hope that it will help you.


问:
Vscode errors using the debugger
When trying to debug c++ with VSCODE, I get the following error:

```<code>> Executing task: /usr/bin/g++ -g /home/sa/Genesis/Dev/TcpSocketClassTester/.vscode/launch.json -o /home/sa/Genesis/Dev/TcpSocketClassTester/.vscode/launch <

/usr/bin/ld:/home/sa/Genesis/Dev/TcpSocketClassTester/.vscode/launch.json: file format not recognized; treating as linker script
/usr/bin/ld:/home/sa/Genesis/Dev/TcpSocketClassTester/.vscode/launch.json:1: syntax error
collect2: error: ld returned 1 exit status
The terminal process terminated with exit code: 1

Terminal will be reused by tasks, press any key to close it.
</code>```

launch.json

```<code>{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "g++ build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "g++ build active file",
            "miDebuggerPath": "/usr/bin/gdb"
        }
    ]
}
</code>```

tasks.json

```<code>{
    "tasks": [
        {
            "type": "shell",
            "label": "g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "/usr/bin"
            }
        },
        {
            "type": "shell",
            "label": "g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "/usr/bin"
            },
            "problemMatcher": [
                "$gcc"
            ]
        }
    ],
    "version": "2.0.0"
}
</code>```

答:
As answered by darcy it is trying to compile the wrong file.

In your tasks.json you can see in the args array this line: "${file}", what it does is to fill the full path of the file you are trying to compile.

The value for this line changes for the document on focus on your vscode. Therefore it is safe to assume you are trying to run the task while having the task.json file on focus, just change it to the .cpp file you want to compile, hit F5 or click the play button in the debug tab and it should work fine.

Title: Vscode errors using the debugger

Body:
When trying to debug c++ with VSCODE, I get the following error:

> Executing task: /usr/bin/g++ -g /home/sa/Genesis/Dev/TcpSocketClassTester/.vscode/launch.json -o /home/sa/Genesis/Dev/TcpSocketClassTester/.vscode/launch <

/usr/bin/ld:/home/sa/Genesis/Dev/TcpSocketClassTester/.vscode/launch.json: file format not recognized; treating as linker script
/usr/bin/ld:/home/sa/Genesis/Dev/TcpSocketClassTester/.vscode/launch.json:1: syntax error
collect2: error: ld returned 1 exit status
The terminal process terminated with exit code: 1

Terminal will be reused by tasks, press any key to close it.

launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "g++ build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "g++ build active file",
            "miDebuggerPath": "/usr/bin/gdb"
        }
    ]
}

tasks.json

{
    "tasks": [
        {
            "type": "shell",
            "label": "g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "/usr/bin"
            }
        },
        {
            "type": "shell",
            "label": "g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "/usr/bin"
            },
            "problemMatcher": [
                "$gcc"
            ]
        }
    ],
    "version": "2.0.0"
}


问:
Index was out of range on an ADOQuery - Very Random
I am getting Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index randomly emailed through to me on my website. I cannot reproduce this error either by force or general testing and it is somewhat confusing.

From what I can see in the stack trace, it happens randomly when opening a dataset and trying to get a value. The stack trace showed I got the error when calling this function:

```<code>function TDB.FGetLastInsertID: Integer;
const
  selSQL = 'select scope_identity() as LastID';
var
  selCursor: TDataSet;
begin
  selCursor := Cursor(selSQL); //Returns a DataSet from a TADOQuery
  try
     Result := selCursor.FieldByName('LASTID').AsInteger;
  finally
     selCursor.Close;
     selCursor.Free;
  end;
end;
</code>```

As I said, I cannot get this to reproduce the error and it seems to happen randomly on any query I run. I have tried closing the connection, setting it to inactive ect to reproduce the error but cannot.

Has anyone got any ideas?

EDIT: It seems its the close causing issues after examining the stack trace more closely:

```<code>Stack Trace: at
System.Collections.ArrayList.get_Item(Int32 index) at
Borland.Vcl.TList.Delete(Int32 Index) at Borland.Vcl.TList.Remove(Object Item) at
Borland.Vcl.TDBBufferList.FreeHGlobal(IntPtr Ptr) at
Borland.Vcl.TCustomADODataSet.FreeRecordBuffer(IntPtr& Buffer) at
Borland.Vcl.TDataSet.SetBufListSize(Int32 Value) at
Borland.Vcl.TDataSet.CloseCursor() at
Borland.Vcl.TDataSet.SetActive(Boolean Value) at Borland.Vcl.TDataSet.Close()
</code>```

EDIT2: I have put a check in the code to make sure the selCursor.Active before selCursor.Close. The stack trace suggests there is nothing to close.

答:
What happens if the Cursor returns an empty Dataset ?

You try to Access the selCursor.FieldByName ... without a record, I think.

Body:
I am getting Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index randomly emailed through to me on my website. I cannot reproduce this error either by force or general testing and it is somewhat confusing.

From what I can see in the stack trace, it happens randomly when opening a dataset and trying to get a value. The stack trace showed I got the error when calling this function:

function TDB.FGetLastInsertID: Integer;
const
  selSQL = 'select scope_identity() as LastID';
var
  selCursor: TDataSet;
begin
  selCursor := Cursor(selSQL); //Returns a DataSet from a TADOQuery
  try
     Result := selCursor.FieldByName('LASTID').AsInteger;
  finally
     selCursor.Close;
     selCursor.Free;
  end;
end;

As I said, I cannot get this to reproduce the error and it seems to happen randomly on any query I run. I have tried closing the connection, setting it to inactive ect to reproduce the error but cannot.

Has anyone got any ideas?

EDIT: It seems its the close causing issues after examining the stack trace more closely:

Stack Trace: at
System.Collections.ArrayList.get_Item(Int32 index) at
Borland.Vcl.TList.Delete(Int32 Index) at Borland.Vcl.TList.Remove(Object Item) at
Borland.Vcl.TDBBufferList.FreeHGlobal(IntPtr Ptr) at
Borland.Vcl.TCustomADODataSet.FreeRecordBuffer(IntPtr& Buffer) at
Borland.Vcl.TDataSet.SetBufListSize(Int32 Value) at
Borland.Vcl.TDataSet.CloseCursor() at
Borland.Vcl.TDataSet.SetActive(Boolean Value) at Borland.Vcl.TDataSet.Close()

EDIT2: I have put a check in the code to make sure the selCursor.Active before selCursor.Close. The stack trace suggests there is nothing to close.


答:
You can use enumerate to pair the values with their indices, sort using the second value (the value, not it's index) and keep the last ones

```<code>from operator import itemgetter
a = [1,2,7,9,3,4]
res = list(sorted(enumerate(a), key=itemgetter(1)))[-2:]

print(res) # [(2, 7), (3, 9)]
print("1st Max", res[-1][1], "at", res[-1][0])  # 1st Max 9 at 3
print("2nd Max", res[-2][1], "at", res[-2][0])  # 2nd Max 7 at 2
</code>```

Title: Selecting two highest values from a list, whilst keeping a record of their index positions?

Body:
You can use enumerate to pair the values with their indices, sort using the second value (the value, not it's index) and keep the last ones

from operator import itemgetter
a = [1,2,7,9,3,4]
res = list(sorted(enumerate(a), key=itemgetter(1)))[-2:]

print(res) # [(2, 7), (3, 9)]
print("1st Max", res[-1][1], "at", res[-1][0])  # 1st Max 9 at 3
print("2nd Max", res[-2][1], "at", res[-2][0])  # 2nd Max 7 at 2


问:
Why doesn't firestore onWrite trigger get invoked on firebase cloud functions emulator?
I have a firestore with a collection called "chats"; I use the firestore emulator to insert a new document and I am expecting the onWrite trigger to get called while I am running index.js locally on my firebase cloud functions emulator (by running firebase emulators:start), but it never does.

I know that the emulator is connected to the right firestore emulator since I can read the data (see below), I just can't get the trigger to be invoked.

```<code>// My setup:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

// We are able to fetch a document correctly, meaning at least my
// cloud functions emulator is hooked up to the firestore emulator!
admin.firestore().collection("chats").doc("eApXKLLXA4X6tIJtYpOx").get()
  .then(doc => {
      if (doc.exists) {
         console.log("Document data:", doc.data()); // <- this works!!
      } else {
         throw new Error("No sender document!");
      }
   })

// This never gets called when I insert a new document through the emulator UI!
exports.myFunction = functions.firestore
  .document('chats/{chat-id}')
  .onWrite((change, context) => { console.log("on write") });
</code>```

答:
Try to change the document selector from chats/{chat-id} to chats/{chatId}. Looks like - symbol is forbidden here. If I use it, I get the following error in firebase-debug.log:

[debug] [2020-06-01T12:17:29.924Z] Jun 01, 2020 3:17:29 PM com.google.cloud.datastore.emulator.impl.util.WrappedStreamObserver onError
  INFO: operation failed: Invalid pattern. Reason: [69:-] Expected '}' at end of capture expression.

Another reason might be using a wrong project id, but it seems it's not your case.
See: Firestore triggers of cloud functions in emulator are ignored

Body:
I have a firestore with a collection called "chats"; I use the firestore emulator to insert a new document and I am expecting the onWrite trigger to get called while I am running index.js locally on my firebase cloud functions emulator (by running firebase emulators:start), but it never does.

I know that the emulator is connected to the right firestore emulator since I can read the data (see below), I just can't get the trigger to be invoked.

// My setup:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

// We are able to fetch a document correctly, meaning at least my
// cloud functions emulator is hooked up to the firestore emulator!
admin.firestore().collection("chats").doc("eApXKLLXA4X6tIJtYpOx").get()
  .then(doc => {
      if (doc.exists) {
         console.log("Document data:", doc.data()); // <- this works!!
      } else {
         throw new Error("No sender document!");
      }
   })

// This never gets called when I insert a new document through the emulator UI!
exports.myFunction = functions.firestore
  .document('chats/{chat-id}')
  .onWrite((change, context) => { console.log("on write") });


问:
Mutable state update in react
For example, we have a state defined like this which is having some todos and we want to change done of that todo if they are completed

```<code>this.state = {
  // store an array of todo objects
  todos: [
    { task: 'do the dishes', done: false, id: 1 },
    { task: 'vacuum the floor', done: true, id: 2 }
  ]
};
</code>```

For that, we can do this away.

```<code>  const theTodo = this.state.todos.find(t => t.id === id);
  theTodo.done = true; // NOOOOO

  this.setState({
    todos: this.state.todos
  });
</code>```

}

But I am a little confused that find method on the array will return us the element which matches the condition inside it and we store it in a different variable and then access done to change it to true.
But still, we haven't changed the original state value as this was a copy one.

Then how come we can use this to save it?

```<code> this.setState({
    todos: this.state.todos // bad
  });
</code>```

答:
Just spread everything

this.setState(oldState => {
  const todos = oldState.todos;
  const todoIndex = todos.findIndex(pr => pr.id === id);
  const todo = todos[todoIndex];
  const newTodos = [...todos.slice(0, todoIndex), {...todo, done: true}, ...todos.slice(todoIndex + 1)]

  return {
    ...oldState,
    todos
  }
});
```

Title: Mutable state update in react

Body:
For example, we have a state defined like this which is having some todos and we want to change done of that todo if they are completed

this.state = {
  // store an array of todo objects
  todos: [
    { task: 'do the dishes', done: false, id: 1 },
    { task: 'vacuum the floor', done: true, id: 2 }
  ]
};

For that, we can do this away.

  const theTodo = this.state.todos.find(t => t.id === id);
  theTodo.done = true; // NOOOOO

  this.setState({
    todos: this.state.todos
  });

}

But I am a little confused that find method on the array will return us the element which matches the condition inside it and we store it in a different variable and then access done to change it to true.
But still, we haven't changed the original state value as this was a copy one.

Then how come we can use this to save it?

 this.setState({
    todos: this.state.todos // bad
  });


问:
If you overwrite a field in a subclass of a class, the subclass has two fields with the same name(and different type)?
I have 3 classes:

```<code>public class Alpha {
    public Number number;
}

public class Beta extends Alpha {
    public String number;
}

public class Gama extends Beta {
    public int number;
}
</code>```

Why does the following code compile? And, why does the test pass without any runtime errors?

```<code>@Test
public void test() {
    final Beta a = new Gama();
    a.number = "its a string";
    ((Alpha) a).number = 13;
    ((Gama) a).number = 42;

    assertEquals("its a string", a.number);
    assertEquals(13, ((Alpha) a).number);
    assertEquals(42, ((Gama) a).number);
}
</code>```

答:
Java Hiding a field

When successor has a field with the same name as a superclass's field it is called - Hiding a field

Java's field does not support polymorphism and does not take a field's type into account

```<code>class A {
    String field = "A: field";

    String foo() {
        return "A: foo()";
    }
}

class B extends A {
    //B's field hides A's field
    String field = "B: field";

    String foo() {
        return "B: foo()";
    }
}

@Test
public void testPoly() {
    A a = new A();
    assertEquals("A: field", a.field);
    assertEquals("A: foo()", a.foo());

    B b = new B();
    assertEquals("B: field", b.field);
    assertEquals("B: foo()", b.foo());

    //B cast to A
    assertEquals("A: field", ((A)b).field);  //<--
    assertEquals("B: foo()", ((A)b).foo());
}
</code>```

[Swift override property]

Body:
I have 3 classes:

public class Alpha {
    public Number number;
}

public class Beta extends Alpha {
    public String number;
}

public class Gama extends Beta {
    public int number;
}

Why does the following code compile? And, why does the test pass without any runtime errors?

@Test
public void test() {
    final Beta a = new Gama();
    a.number = "its a string";
    ((Alpha) a).number = 13;
    ((Gama) a).number = 42;

    assertEquals("its a string", a.number);
    assertEquals(13, ((Alpha) a).number);
    assertEquals(42, ((Gama) a).number);
}

Body:
Java Hiding a field

When successor has a field with the same name as a superclass's field it is called - Hiding a field

Java's field does not support polymorphism and does not take a field's type into account

class A {
    String field = "A: field";

    String foo() {
        return "A: foo()";
    }
}

class B extends A {
    //B's field hides A's field
    String field = "B: field";

    String foo() {
        return "B: foo()";
    }
}

@Test
public void testPoly() {
    A a = new A();
    assertEquals("A: field", a.field);
    assertEquals("A: foo()", a.foo());

    B b = new B();
    assertEquals("B: field", b.field);
    assertEquals("B: foo()", b.foo());

    //B cast to A
    assertEquals("A: field", ((A)b).field);  //<--
    assertEquals("B: foo()", ((A)b).foo());
}

[Swift override property]


问:
Passing reference to class constructor, "provides no initializer for"
I'm trying to pass a class reference to a field, but I get the error "'mazeGenerator::maze' references must be initialized".

I tried initializing 'maze' above the class constructor.

Why is this happening?

```<code>class mazeGenerator {
public:
    Maze& maze;

    mazeGenerator(Maze& mazeObj) {
        maze=mazeObj;
    }
}

</code>```

答:
You must initialize data members of reference type with a member initializer list, like this:

```<code>mazeGenerator(Maze& mazeObj) : maze(mazeObj) {}
</code>```

This is also the case with const data members.

Note that putting the declaration of the data member above the constructor doesn't actually make any difference; it could be declared below as well.

Also, your data members (whether they are of reference type or not), should be private to the class.

Body:
I'm trying to pass a class reference to a field, but I get the error "'mazeGenerator::maze' references must be initialized".

I tried initializing 'maze' above the class constructor.

Why is this happening?

class mazeGenerator {
public:
    Maze& maze;

    mazeGenerator(Maze& mazeObj) {
        maze=mazeObj;
    }
}

Body:
You must initialize data members of reference type with a member initializer list, like this:

mazeGenerator(Maze& mazeObj) : maze(mazeObj) {}

This is also the case with const data members.

Note that putting the declaration of the data member above the constructor doesn't actually make any difference; it could be declared below as well.

Also, your data members (whether they are of reference type or not), should be private to the class.


问:
Why does using an Underscore character in a LIKE filter give me all the results?
I wrote the below SQL query with a LIKE condition:

```<code>SELECT * FROM Manager
WHERE managerid LIKE '_%'
AND managername LIKE '%_%'
</code>```

In the LIKE I want to search for any underscores %_%, but I know that my columns' data has no underscore characters.

Why does the query give me all the records from the table?

Sample data:

```<code>create table Manager(
    id int
    ,managerid varchar(3)
    ,managername varchar(50)
    );

insert into Manager(id,managerid,managername)values(1,'A1','Mangesh');
insert into Manager(id,managerid,managername)values(2,'A2','Sagar');
insert into Manager(id,managerid,managername)values(3,'C3','Ahmad');
insert into Manager(id,managerid,managername)values(4,'A4','Mango');
insert into Manager(id,managerid,managername)values(5,'B5','Sandesh');
</code>```

Sql-Fiddle

答:
You can write the query as below:

SELECT * FROM Manager
WHERE managerid LIKE '\_%' escape '\'
AND managername LIKE '%\_%' escape '\';
```

it will solve your problem.

Body:
I wrote the below SQL query with a LIKE condition:

SELECT * FROM Manager
WHERE managerid LIKE '_%'
AND managername LIKE '%_%'

In the LIKE I want to search for any underscores %_%, but I know that my columns' data has no underscore characters.

Why does the query give me all the records from the table?

Sample data:

create table Manager(
    id int
    ,managerid varchar(3)
    ,managername varchar(50)
    );

insert into Manager(id,managerid,managername)values(1,'A1','Mangesh');
insert into Manager(id,managerid,managername)values(2,'A2','Sagar');
insert into Manager(id,managerid,managername)values(3,'C3','Ahmad');
insert into Manager(id,managerid,managername)values(4,'A4','Mango');
insert into Manager(id,managerid,managername)values(5,'B5','Sandesh');

Sql-Fiddle

Body:
You can write the query as below:

SELECT * FROM Manager
WHERE managerid LIKE '\_%' escape '\'
AND managername LIKE '%\_%' escape '\';

it will solve your problem.


问:
How to make Inno Setup RunList checklist box transparent?
My installer has a custom finish page with an image on it. I referred this Custom Welcome and Finished page with stretched image in Inno Setup solution for it. But the issue is with the check box at finish page, it is coming on top of the finish page image with a white background. If I removed postinstall flag, then it will automatically launch my app. But I want the user to be able to choose like how checkbox does. So is there any way to transparent the check box launch message on top of my image? Would TNewCheckBox help here?

```<code>[Run]
Filename: "app\My program.exe"; Description: "{cm:LaunchProgram}"; #
    Flags: nowait postinstall skipifsilent
</code>```

答:
In standard Inno Setup, I do not think you can make WizardForm.RunList (TNewCheckListBox) transparent. But as the simple TNewCheckListBox is transparent, you can replace the WizardForm.RunList with TNewCheckListBox.

[Code]
procedure RunCheckBoxClick(Sender: TObject);
begin
  WizardForm.RunList.Checked[0] := TNewCheckBox(Sender).Checked;
end;

procedure CurPageChanged(CurPageID: Integer);
var
  RunCheckBox: TNewCheckBox;
begin
  if CurPageID = wpFinished then
  begin
    if (not WizardForm.RunList.Visible) or
       (WizardForm.RunList.Items.Count < 1) then
    begin
      Log('No items to run');
    end
      else
    if WizardForm.RunList.Items.Count > 1 then
    begin
      Log('More than one item to run, keeping the standard non-transparent run list');
    end
      else
    begin
      Log('Replacing the one item in the run list with a simple transparent checkbox');
      RunCheckBox := TNewCheckBox.Create(WizardForm);
      RunCheckBox.Parent := WizardForm.RunList.Parent;
      RunCheckBox.Left := WizardForm.RunList.Left + ScaleX(4);
      RunCheckBox.Top := WizardForm.RunList.Top + ScaleY(4);
      RunCheckBox.Width := WizardForm.RunList.Width;
      RunCheckBox.Height := ScaleY(RunCheckBox.Height);
      RunCheckBox.Checked := WizardForm.RunList.Checked[0];
      RunCheckBox.Caption := WizardForm.RunList.ItemCaption[0];
      RunCheckBox.OnClick := @RunCheckBoxClick;
      WizardForm.RunList.Visible := False;
    end
  end;
end;
```

Body:
My installer has a custom finish page with an image on it. I referred this Custom Welcome and Finished page with stretched image in Inno Setup solution for it. But the issue is with the check box at finish page, it is coming on top of the finish page image with a white background. If I removed postinstall flag, then it will automatically launch my app. But I want the user to be able to choose like how checkbox does. So is there any way to transparent the check box launch message on top of my image? Would TNewCheckBox help here?

[Run]
Filename: "app\My program.exe"; Description: "{cm:LaunchProgram}"; #
    Flags: nowait postinstall skipifsilent


问:
Modularity in Caliburn micro
I have main project(wpf app) and "child" project(user control class library). I am trying to use user control from child project inside MainView of my main project:

MainView.xaml:

```<code>        <ContentControl  x:Name="ActiveItem" Grid.Column="1">

        </ContentControl>
</code>```

MainViewModel:

```<code>        public void LoadAgenda()
        {
            ActivateItem(new InstanceOfViewModelFromChildProject());
        }
</code>```

And I get error

"Cannot find view for InstanceOfViewModelFromChildProject".

I think I get this error because it tries to find view inside my main project and not in child project where this viewmodel and view are located. Is there anyway to fix this or another way to do it?

答:
Override the SelectAssemblies() method of the bootstrapper to return the assembly in which the views are defined.

From the docs:

By default, the base class returns the assembly that your Application exists in:

```<code>protected override IEnumerable<Assembly> SelectAssemblies()
{
    return new[] {
        Assembly.GetExecutingAssembly()
    };
}
</code>```

Title: Modularity in Caliburn micro

Body:
I have main project(wpf app) and "child" project(user control class library). I am trying to use user control from child project inside MainView of my main project:

MainView.xaml:

        <ContentControl  x:Name="ActiveItem" Grid.Column="1">

        </ContentControl>

MainViewModel:

        public void LoadAgenda()
        {
            ActivateItem(new InstanceOfViewModelFromChildProject());
        }

And I get error

"Cannot find view for InstanceOfViewModelFromChildProject".

I think I get this error because it tries to find view inside my main project and not in child project where this viewmodel and view are located. Is there anyway to fix this or another way to do it?

Body:
Override the SelectAssemblies() method of the bootstrapper to return the assembly in which the views are defined.

From the docs:

By default, the base class returns the assembly that your Application exists in:

protected override IEnumerable<Assembly> SelectAssemblies()
{
    return new[] {
        Assembly.GetExecutingAssembly()
    };
}


问:
finding semantic similarity between 2 statements
I am currently working with small application in python and my application has search functionality (currently using difflib) but I want to create Semantic Search which can give top 5 or 10 results from my database, based on user inputted text. It is same as google search engine works. I found some solutions Here.

But the problem is, below two statements from one of solution are semantically incorrect. And I don't care about this. because they are making things too hard which I don't want And also solution will be some pretrained neural network model or library from which I can implement easily.

Pete and Rob have found a dog near the station.

Pete and Rob have never found a dog near the station

And also I found some solutions which are showing using gensim and Glove embeddings and finding similarity between words and not sentences.

What I wanted ?

Suppose my db has statement display classes and user inputs show, showed, displayed, displayed class, show types etc are same. And if above 2 statements are given as same then also I don't care. displayed and displayed class already showing in difflib.

Points to be noted

Find from fixed set of statements but user inputted statements can differ

Must work for statements

答:
Hey you can use spacy

This answer is from https://medium.com/better-programming/the-beginners-guide-to-similarity-matching-using-spacy-782fc2922f7c

import spacy

nlp =  spacy.load("en_core_web_lg")

doc1 = nlp("display classes")
doc2 = nlp("show types")
print(doc1.similarity(doc2))
```

<h1>Output</h1>

<pre class="lang-sh prettyprint-override"><code>0.6277548513279427
</code>```

Edit

Run following command, which will download model.

!python -m spacy download en_core_web_lg
```

Body:
Hey you can use spacy

This answer is from https://medium.com/better-programming/the-beginners-guide-to-similarity-matching-using-spacy-782fc2922f7c

import spacy

nlp =  spacy.load("en_core_web_lg")

doc1 = nlp("display classes")
doc2 = nlp("show types")
print(doc1.similarity(doc2))

Output

0.6277548513279427

Edit

Run following command, which will download model.

!python -m spacy download en_core_web_lg


问:
Selecting two highest values from a list, whilst keeping a record of their index positions?
I am trying to get the highest and the second highest values from list a. I also need to keep track of what the index value was for each of these values.

For example:

```<code>a = [1,2,7,9,3,4]
</code>```

Desired output:

```<code>maxVal = 9
secondMax = 7

index_max = 3
index_secondMax = 2
</code>```

Does any one have any suggestions for how to approach this, can't seem to figure out a way of doing it.

答:
```<code>secondMax, Max  = sorted(a)[-2:]
index_max = a.index(Max)
index_secondMax = a.index(secondMax)
</code>```

Body:
I am trying to get the highest and the second highest values from list a. I also need to keep track of what the index value was for each of these values.

For example:

a = [1,2,7,9,3,4]

Desired output:

maxVal = 9
secondMax = 7

index_max = 3
index_secondMax = 2

Does any one have any suggestions for how to approach this, can't seem to figure out a way of doing it.


问:
Change font size relative to previous class
I have this component that accepts any classname. To this I wish to add another class what would make the item smaller by a % say 90%. How do I achieve that.

  ```

Problem is my class replaces existing class's font size(which is expected). Instead I want it to take that into account.

I thought of using transform:scale to achieve same but It won't work on inline elements and I cant make it inline-block

答:
I would use the unit em in this situation. em is a relative unit, which 1em means use the current font-size set by my closest parent. You can use this in your component so that the passed in prop acts like a multiplier.

NO JS Solution

I am 30px

I am 20px

I am 10px

I am 5px```
</div>
</div>
</p>
<h2>React Solution</h2>
<ol>
<li>First, set the em value</li>
</ol>
<p>Wrap the html in another div tag and add inline styles forcing its pixel size to 0.1px.</p>
<ol start="2">
<li>Use the prop to set font-size</li>
</ol>
<p>Now in your template, you can pass in props which will be used change the font-size.
(don't forget to set a default value encase you forget to pass in the prop.</p>
<h2>Example</h2>
```export const myTemplate = props => {

const default = "100em"; // sets default font-size to 10px.

const size = {font-size: `${props.size}em`} || default;

return(

 )
}

export const myTemplate
```

Body:
I have this component that accepts any classname. To this I wish to add another class what would make the item smaller by a % say 90%. How do I achieve that.

Problem is my class replaces existing class's font size(which is expected). Instead I want it to take that into account.

I thought of using transform:scale to achieve same but It won't work on inline elements and I cant make it inline-block

Body:
I would use the unit em in this situation. em is a relative unit, which 1em means use the current font-size set by my closest parent. You can use this in your component so that the passed in prop acts like a multiplier.

NO JS Solution

<style>
.specified_class {
font-size: 10px; // Controles the size
}

.sz-default{
  font-size: 1.0em
}

.sz-third{
  font-size: .3em;
}

.sz-half{
  font-size: .5em;
}

.sz-double{
  font-size: 2em;
}

.sz-triple{
  font-size: 3em;
}
</style>
<span class="specified_class sz-triple">I am 30px</span><br>
<span class="specified_class sz-double">I am 20px</span><br>
<span class="specified_class sz-default">I am 10px</span><br>
<span class="specified_class sz-half">I am 5px</span>

React Solution

First, set the em value

Wrap the html in another div tag and add inline styles forcing its pixel size to 0.1px.

Use the prop to set font-size

Now in your template, you can pass in props which will be used change the font-size.
(don't forget to set a default value encase you forget to pass in the prop.

Example

export const myTemplate = props => {

const default = "100em"; // sets default font-size to 10px.

const size = {font-size: `${props.size}em`} || default;

return(
  <div style={{font-size: "0.1px"}}>
    <span class="specified_class" style=size></span>
  </div>
 )
}

export const myTemplate


问:
How to add new class without reseting previous ones in React
I want to add underline to menu item when its active. All works fine, but when I click on an item, its previous classes received from the ReactTransitionGroup add-on component are reset. For example when I click second item the classes will be reset and only active will remain. I want the active class to be insert to existing without cleaning the previous ones.

The .active has ::after pseudo-class

```<code>const NavItems = (props) => {
  const items = ["section1", "section2", "section3", "section4", "section5"];
  const [activeItem, setActive] = useState(0);

  return (
    <>
     <NavItemsOverlay open={props.open} />

     <ScollLinks open={props.open}>
       {items.map((item, index) => {
         return (
          <CSSTransition
            in={props.open}
            key={index}
          timeout={{enter: 100 * index, exit: 0 }}
          classNames="fade ">
            <Link
              className={activeItem === index ? " active" : ""}
              onClick={() => setActive(index)} >
              {item}
            </Link>
          </CSSTransition>
      );
     })}
    </ScollLinks>
   </>
   );
 };
</code>```

答:
You appear to be running into issue #318, which is still open. The person posting the issue thinks it's a bug, and the CSSTransition documentation does say:

A few details to note about how these classes are applied:

They are joined with the ones that are already defined on the child component, so if you want to add some base styles, you can use className without worrying that it will be overridden.

...so yeah, that sounds like a bug.

The best way to solve it would be to fork the project, fix the bug, and send a PR. :-)

A really hacky way to work around it would be to use a data-* attribute instead of a class:

```<code><Link
  data-cls={activeItem === index ? " active" : ""}
  onClick={() => setActive(index)} >
  {item}
</Link>
</code>```

And then in the CSS, instead of:

```<code>.active::after {
    /* ... */
}
</code>```

You'd have

```<code>[data-cls~=active]::after {
    /* ... */
}
</code>```

That uses class-like attribute matching to match that element.

Body:
I want to add underline to menu item when its active. All works fine, but when I click on an item, its previous classes received from the ReactTransitionGroup add-on component are reset. For example when I click second item the classes will be reset and only active will remain. I want the active class to be insert to existing without cleaning the previous ones.

The .active has ::after pseudo-class

const NavItems = (props) => {
  const items = ["section1", "section2", "section3", "section4", "section5"];
  const [activeItem, setActive] = useState(0);

  return (
    <>
     <NavItemsOverlay open={props.open} />

     <ScollLinks open={props.open}>
       {items.map((item, index) => {
         return (
          <CSSTransition
            in={props.open}
            key={index}
          timeout={{enter: 100 * index, exit: 0 }}
          classNames="fade ">
            <Link
              className={activeItem === index ? " active" : ""}
              onClick={() => setActive(index)} >
              {item}
            </Link>
          </CSSTransition>
      );
     })}
    </ScollLinks>
   </>
   );
 };

Body:
You appear to be running into issue #318, which is still open. The person posting the issue thinks it's a bug, and the CSSTransition documentation does say:

A few details to note about how these classes are applied:

They are joined with the ones that are already defined on the child component, so if you want to add some base styles, you can use className without worrying that it will be overridden.

...so yeah, that sounds like a bug.

The best way to solve it would be to fork the project, fix the bug, and send a PR. :-)

A really hacky way to work around it would be to use a data-* attribute instead of a class:

<Link
  data-cls={activeItem === index ? " active" : ""}
  onClick={() => setActive(index)} >
  {item}
</Link>

And then in the CSS, instead of:

.active::after {
    /* ... */
}

You'd have

[data-cls~=active]::after {
    /* ... */
}

That uses class-like attribute matching to match that element.


问:
How to read the first row of a Dataframe as data row and not header
I'm trying to read the data out of pdf using Tabula-Py but facing a small issue:

The library reads the data like this:

```<code>  F 01/02/1994 01/12/1994 ac $123
0 M 01/03/1994 01/10/1992 ad $133
1 M 01/04/1994 01/09/1992 ae $133
2 M 01/05/1994 01/08/1992 aa $133
</code>```

When I give them column names: The issue is that the first row is automatically being treated as Header and not the data while being Read by Tabula-PDF, so the output becomes:

```<code>  Gender  D.O.B       D.O.P      Plan  Price
0 M      01/03/1994  01/10/1992  ad    $133
1 M      01/04/1994  01/09/1992  ae    $133
2 M      01/05/1994  01/08/1992  aa    $133
</code>```

which is incorrect. It drops the first row

The correct Output required is Below:

```<code> Gender D.O.B       D.O.P      Plan Price
0 F     01/02/1994  01/12/1994 cc   $123
1 M     01/03/1994  01/10/1992 aa   $133
2 M     01/04/1994  01/09/1992 aa   $133
3 M     01/05/1994  01/08/1992 aa   $133
</code>```

The code that i'm using is :

```<code>def table_type_2(path):
    df = read_pdf(path,guess = True, multiple_tables=True)
    head = ['Gender', 'Date of Birth', 'Date of', 'Coverage', 'Gross Benefit']

    for i in range (0,len(df)):
        print(len(df[i]))
        dfnew.append(df[i])

    e = pd.DataFrame(dfnew[i],index=None)
    print(e)
    f = pd.DataFrame(e,columns=head)
    g = pd.DataFrame(data = e.values,columns=f.columns)
    print(g)
</code>```

Is there a way so that i don't lose the first row well?

答:
use:

```<code>read_pdf(target_pdf, pandas_options={'header': None})
</code>```

from the docs: using pandas options in read_pdf

Body:
I'm trying to read the data out of pdf using Tabula-Py but facing a small issue:

The library reads the data like this:

  F 01/02/1994 01/12/1994 ac $123
0 M 01/03/1994 01/10/1992 ad $133
1 M 01/04/1994 01/09/1992 ae $133
2 M 01/05/1994 01/08/1992 aa $133

When I give them column names: The issue is that the first row is automatically being treated as Header and not the data while being Read by Tabula-PDF, so the output becomes:

  Gender  D.O.B       D.O.P      Plan  Price
0 M      01/03/1994  01/10/1992  ad    $133
1 M      01/04/1994  01/09/1992  ae    $133
2 M      01/05/1994  01/08/1992  aa    $133

which is incorrect. It drops the first row

The correct Output required is Below:

 Gender D.O.B       D.O.P      Plan Price
0 F     01/02/1994  01/12/1994 cc   $123
1 M     01/03/1994  01/10/1992 aa   $133
2 M     01/04/1994  01/09/1992 aa   $133
3 M     01/05/1994  01/08/1992 aa   $133

The code that i'm using is :

def table_type_2(path):
    df = read_pdf(path,guess = True, multiple_tables=True)
    head = ['Gender', 'Date of Birth', 'Date of', 'Coverage', 'Gross Benefit']

    for i in range (0,len(df)):
        print(len(df[i]))
        dfnew.append(df[i])

    e = pd.DataFrame(dfnew[i],index=None)
    print(e)
    f = pd.DataFrame(e,columns=head)
    g = pd.DataFrame(data = e.values,columns=f.columns)
    print(g)

Is there a way so that i don't lose the first row well?

Body:
use:

read_pdf(target_pdf, pandas_options={'header': None})

from the docs: using pandas options in read_pdf


问:
Export two excel data into single excel sheet by adding heading and some calculated data
I am using react-data-export to export the excel sheet in my react project. I need to export two excel data in single file. Example

If not possible the above module please suggest me a new way to do so.

答:
I have published a simple proof of concept that it should be useful to understand how it is possible to satisfy the needs in the question to export two excel data in single file.

In the  ExcelSheet components it is possible to pass a dataSet that allows any number of data tables and other features such as column headers and the offset in rows and columns between a data table and the subsequent one.

The data attribute of ExcelSheet is for one data table.

The dataSet attribute of ExcelSheet is for one or more data table

In the react-data-export git repo there is also an example simple_excel_export_02 but I have not been able to make it work, also there is a open issue with some suggestions I've learned for my POC.


问:
How to work on array of bitmaps without '['
I wrote a program which checks parity of 32-bit integer without bitwise operators. I can't also use ] sign apart from declaration. My program is already good, but I don't know how can I make it work without [ sign. I tried many ways but my program doesn't want to compile. Here is my program:

```<code>#ifndef bit_set
#define bit_set
struct bit{
    unsigned b0 : 1;
    unsigned b1 : 1;
    unsigned b2 : 1;
    unsigned b3 : 1;
    unsigned b4 : 1;
    unsigned b5 : 1;
    unsigned b6 : 1;
    unsigned b7 : 1;
};
union bit_set
{
    unsigned int x;
    struct bit foo[4];
}word;
#endif

</code>```

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "bit_set.h"

int main(void) {
    printf("Input number: ");
    if (scanf("%u", &word.x) == 0) {
        printf("Incorrect input");
        return 1;
    }
    int sum = 0;
    for (int i = 0; i < 4; i++) {
        sum += word.foo[i].b0 + word.foo[i].b1 + word.foo[i].b2 + word.foo[i].b3 + word.foo[i].b4 + word.foo[i].b5 + word.foo[i].b6 + word.foo[i].b7;
    }
    sum % 2 ? printf("NO") : printf("YES");
    return 0;
}
</code>```

答:
I wanted the code to not have so long printf and bitmap which is looking not good, so I implemented arrays. Unfortunately without [ sign it is impossible to do the task properly. Now I managed to do the task in an ugly way:

```<code>#ifndef bit_set
#define bit_set
struct bit{
    unsigned b0 : 1;
    unsigned b1 : 1;
    unsigned b2 : 1;
    unsigned b3 : 1;
    unsigned b4 : 1;
    unsigned b5 : 1;
    unsigned b6 : 1;
    unsigned b7 : 1;
    unsigned b02 : 1;
    unsigned b12 : 1;
    unsigned b22 : 1;
    unsigned b32 : 1;
    unsigned b42 : 1;
    unsigned b52 : 1;
    unsigned b62 : 1;
    unsigned b72 : 1;
    unsigned b03 : 1;
    unsigned b13 : 1;
    unsigned b23 : 1;
    unsigned b33 : 1;
    unsigned b43 : 1;
    unsigned b53 : 1;
    unsigned b63 : 1;
    unsigned b73 : 1;
    unsigned b04 : 1;
    unsigned b14 : 1;
    unsigned b24 : 1;
    unsigned b34 : 1;
    unsigned b44 : 1;
    unsigned b54 : 1;
    unsigned b64 : 1;
    unsigned b74 : 1;
};
union bit_set
{
    unsigned int x;
    struct bit foo;
}word;
#endif
</code>```

```<code>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "bit_set.h"

int main(void) {
    printf("Input number: ");
    if (scanf("%u", &word.x) == 0) {
        printf("Incorrect input");
        return 1;
    }
    int sum = 0;
    sum += word.foo.b7+ word.foo.b6 +word.foo.b5 + word.foo.b4 + word.foo.b3 + word.foo.b2 + word.foo.b1 + word.foo.b0 + word.foo.b72 + word.foo.b62 + word.foo.b52 + word.foo.b42 + word.foo.b32 + word.foo.b22 + word.foo.b12 + word.foo.b02 + word.foo.b73 + word.foo.b63 + word.foo.b53 + word.foo.b43 + word.foo.b33 + word.foo.b23 + word.foo.b13 + word.foo.b03 + word.foo.b74 + word.foo.b64 + word.foo.b54 + word.foo.b44 + word.foo.b34 + word.foo.b24 + word.foo.b14 + word.foo.b04;
    sum % 2 ? printf("NO") : printf("YES");
    return 0;
}

</code>```

Body:
I wrote a program which checks parity of 32-bit integer without bitwise operators. I can't also use ] sign apart from declaration. My program is already good, but I don't know how can I make it work without [ sign. I tried many ways but my program doesn't want to compile. Here is my program:

#ifndef bit_set
#define bit_set
struct bit{
    unsigned b0 : 1;
    unsigned b1 : 1;
    unsigned b2 : 1;
    unsigned b3 : 1;
    unsigned b4 : 1;
    unsigned b5 : 1;
    unsigned b6 : 1;
    unsigned b7 : 1;
};
union bit_set
{
    unsigned int x;
    struct bit foo[4];
}word;
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "bit_set.h"

int main(void) {
    printf("Input number: ");
    if (scanf("%u", &word.x) == 0) {
        printf("Incorrect input");
        return 1;
    }
    int sum = 0;
    for (int i = 0; i < 4; i++) {
        sum += word.foo[i].b0 + word.foo[i].b1 + word.foo[i].b2 + word.foo[i].b3 + word.foo[i].b4 + word.foo[i].b5 + word.foo[i].b6 + word.foo[i].b7;
    }
    sum % 2 ? printf("NO") : printf("YES");
    return 0;
}

Body:
I wanted the code to not have so long printf and bitmap which is looking not good, so I implemented arrays. Unfortunately without [ sign it is impossible to do the task properly. Now I managed to do the task in an ugly way:

#ifndef bit_set
#define bit_set
struct bit{
    unsigned b0 : 1;
    unsigned b1 : 1;
    unsigned b2 : 1;
    unsigned b3 : 1;
    unsigned b4 : 1;
    unsigned b5 : 1;
    unsigned b6 : 1;
    unsigned b7 : 1;
    unsigned b02 : 1;
    unsigned b12 : 1;
    unsigned b22 : 1;
    unsigned b32 : 1;
    unsigned b42 : 1;
    unsigned b52 : 1;
    unsigned b62 : 1;
    unsigned b72 : 1;
    unsigned b03 : 1;
    unsigned b13 : 1;
    unsigned b23 : 1;
    unsigned b33 : 1;
    unsigned b43 : 1;
    unsigned b53 : 1;
    unsigned b63 : 1;
    unsigned b73 : 1;
    unsigned b04 : 1;
    unsigned b14 : 1;
    unsigned b24 : 1;
    unsigned b34 : 1;
    unsigned b44 : 1;
    unsigned b54 : 1;
    unsigned b64 : 1;
    unsigned b74 : 1;
};
union bit_set
{
    unsigned int x;
    struct bit foo;
}word;
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "bit_set.h"

int main(void) {
    printf("Input number: ");
    if (scanf("%u", &word.x) == 0) {
        printf("Incorrect input");
        return 1;
    }
    int sum = 0;
    sum += word.foo.b7+ word.foo.b6 +word.foo.b5 + word.foo.b4 + word.foo.b3 + word.foo.b2 + word.foo.b1 + word.foo.b0 + word.foo.b72 + word.foo.b62 + word.foo.b52 + word.foo.b42 + word.foo.b32 + word.foo.b22 + word.foo.b12 + word.foo.b02 + word.foo.b73 + word.foo.b63 + word.foo.b53 + word.foo.b43 + word.foo.b33 + word.foo.b23 + word.foo.b13 + word.foo.b03 + word.foo.b74 + word.foo.b64 + word.foo.b54 + word.foo.b44 + word.foo.b34 + word.foo.b24 + word.foo.b14 + word.foo.b04;
    sum % 2 ? printf("NO") : printf("YES");
    return 0;
}


问:
R: Subset rows from dataframe based on range of given time
Assume I have df1:

```<code>Start_Date    End_Date     Value
2001-01-01    2001-12-31   1
2002-01-01    2002-12-31   2
2003-01-01    2003-12-31   3
2004-01-01    2004-12-31   4
2005-01-01    2005-12-31   5
</code>```

& df2:

```<code>DateTime
2003-01-01
2003-05-09
2004-12-31
2005-01-31
2005-08-13
</code>```

What I would like to do is to import Value from df1 into df2 by checking which DateTime in df2 falls in between Start_Date & End_Date in df1. A view of desired outcome:

```<code>DateTime      Value
2003-01-01    3
2003-05-09    3
2004-12-31    4
2005-01-31    5
2005-08-13    5
</code>```

Please advise

答:
Using dplyr and lubridate gives a solution.

Before we start make sure all dates are formatted in the same way:

df1 <- df1 %>%
  mutate(Start_Date=ymd(Start_Date), End_Date=dmy(End_Date))

df2 <- df2 %>%
  mutate(DateTime=ymd(DateTime))
```
<p>In your case it's only necessary for your column <code>End_Date</code>.</p>
<p>First I crossjoin both data.frames since I don't see any easy solution for combining both dfs.</p>
<pre class="lang-r prettyprint-override"><code>df3 <- merge(df1, df2, all=TRUE)
</code>```

Next using filter and between

df3 %>%
  filter(between(DateTime, Start_Date, End_Date)) %>%
  select(-c(Start_Date, End_Date))
```
<p>gives</p>
<pre class="lang-r prettyprint-override"><code>  Value   DateTime
1     3 2003-01-01
2     3 2003-05-09
3     4 2004-12-31
4     5 2005-01-31
5     5 2005-08-13
</code>```

Another option using package data.table

setDT(df1)
setDT(df2)
df1[df2, on = .(Start_Date <= DateTime, End_Date >= DateTime),
    .(DateTime, Value)]
```
<p>yields</p>
<pre class="lang-r prettyprint-override"><code>     DateTime Value
1: 2003-01-01     3
2: 2003-05-09     3
3: 2004-12-31     4
4: 2005-01-31     5
5: 2005-08-13     5
</code>```

Body:
Assume I have df1:

Start_Date    End_Date     Value
2001-01-01    2001-12-31   1
2002-01-01    2002-12-31   2
2003-01-01    2003-12-31   3
2004-01-01    2004-12-31   4
2005-01-01    2005-12-31   5

& df2:

DateTime
2003-01-01
2003-05-09
2004-12-31
2005-01-31
2005-08-13

What I would like to do is to import Value from df1 into df2 by checking which DateTime in df2 falls in between Start_Date & End_Date in df1. A view of desired outcome:

DateTime      Value
2003-01-01    3
2003-05-09    3
2004-12-31    4
2005-01-31    5
2005-08-13    5

Please advise

Body:
Using dplyr and lubridate gives a solution.

Before we start make sure all dates are formatted in the same way:

df1 <- df1 %>%
  mutate(Start_Date=ymd(Start_Date), End_Date=dmy(End_Date))

df2 <- df2 %>%
  mutate(DateTime=ymd(DateTime))

In your case it's only necessary for your column End_Date.

First I crossjoin both data.frames since I don't see any easy solution for combining both dfs.

df3 <- merge(df1, df2, all=TRUE)

Next using filter and between

df3 %>%
  filter(between(DateTime, Start_Date, End_Date)) %>%
  select(-c(Start_Date, End_Date))

gives

  Value   DateTime
1     3 2003-01-01
2     3 2003-05-09
3     4 2004-12-31
4     5 2005-01-31
5     5 2005-08-13

Another option using package data.table

setDT(df1)
setDT(df2)
df1[df2, on = .(Start_Date <= DateTime, End_Date >= DateTime),
    .(DateTime, Value)]

yields

     DateTime Value
1: 2003-01-01     3
2: 2003-05-09     3
3: 2004-12-31     4
4: 2005-01-31     5
5: 2005-08-13     5


问:
Center a text inside an spinning element
I have a simple loader animation and I want to add a loading text inside the circle.

As I'm spinning the .slide-loader and my text is inside it I've tried to exclude the .loader-text but it still spins?! how can I fix the loader-text inside the circle?

Here is the code:

.slide-loader:not(.loader-text) {
  position: absolute;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  width: 100px;
  height: 100px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;

}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="slide-loader">
    <div class="loader-text">Loading...</div>
  </div></code>```

答:
.slide-loader:not(.loader-text) {
  position: absolute;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  width: 100px;
  height: 100px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;

}
.container {
  display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<div class="container">
  <div class="loader-text">Loading...</div>
  <div class="slide-loader">
  </div>
</div>
</div> </code>```

Body:
I have a simple loader animation and I want to add a loading text inside the circle.

As I'm spinning the .slide-loader and my text is inside it I've tried to exclude the .loader-text but it still spins?! how can I fix the loader-text inside the circle?

Here is the code:

.slide-loader:not(.loader-text) {
  position: absolute;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  width: 100px;
  height: 100px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;

}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

Loading...

Body:
.slide-loader:not(.loader-text) {
  position: absolute;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  width: 100px;
  height: 100px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;

}
.container {
  display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

<div>
<div class="container">
  <div class="loader-text">Loading...</div>
  <div class="slide-loader">
  </div>
</div>
</div>


问:
Using the spread operator on an array with objects
I got a Javascript object which looks like this:

```<code>{
   key1: {
           itemId: "someId",
           myValue: "value"
   },
   key2: {
           itemId: "someId2",
           myValue: "value2"
   }
}
</code>```

I also got an array to which I push items like this:

```<code>myArr.push({[item.itemId] : anotherDefinedObject}); //inside a loop on items
</code>```

I then want to join all the items I pushed to the array to the first object. Meaning that if for example the items ids were "key3" and "key4" I would get this object:

```<code>{
   key1: {
           itemId: "someId",
           myValue: "value"
   },
   key2: {
           itemId: "someId2",
           myValue: "value2"
   },
   key3: { //the object that was added },
   key4: { //the object that was added }
}
</code>```

I tried doing it with the spread operator:

```<code>return {...object, ...myArr}
</code>```

But then instead of getting what I needed, I get "0", "1" and such as the keys in the new object (since 0,1 etc are the keys of the arrays).

How do I concatenate the object and the array the way I want?

答:
rather my myArray create myObject.

```<code>myObject = {}
myObject[item.itemId] = anotherDefinedObject;
</code>```

Then

```<code>return {...object, ...myObject}
</code>```

Body:
I got a Javascript object which looks like this:

{
   key1: {
           itemId: "someId",
           myValue: "value"
   },
   key2: {
           itemId: "someId2",
           myValue: "value2"
   }
}

I also got an array to which I push items like this:

myArr.push({[item.itemId] : anotherDefinedObject}); //inside a loop on items

I then want to join all the items I pushed to the array to the first object. Meaning that if for example the items ids were "key3" and "key4" I would get this object:

{
   key1: {
           itemId: "someId",
           myValue: "value"
   },
   key2: {
           itemId: "someId2",
           myValue: "value2"
   },
   key3: { //the object that was added },
   key4: { //the object that was added }
}

I tried doing it with the spread operator:

return {...object, ...myArr}

But then instead of getting what I needed, I get "0", "1" and such as the keys in the new object (since 0,1 etc are the keys of the arrays).

How do I concatenate the object and the array the way I want?

Body:
rather my myArray create myObject.

myObject = {}
myObject[item.itemId] = anotherDefinedObject;

Then

return {...object, ...myObject}