问:
Making popup windows in pygame with pgu
I'm trying to add some gui elements (dialog boxes with buttons) to a game I'm writing with pygame. I looked around for a decent gui toolkit and ended up with pgu. Anyway, I'm trying to get it to pop up a dialog box, which it does (sort of), but it isn't closing.

Here's a simplified version of my code that just shows the behavior I care about:

```<code>
import pygame, sys
from pgu import gui

screen = None
WIDTH = 640
HEIGHT = 480

def init_pygame():
    global screen
    pygame.display.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.DOUBLEBUF)
    pygame.display.set_caption('Testing PGU')

class SimpleDialog(gui.Dialog):
    def __init__(self):
        title = gui.Label("Spam")
        main = gui.Container(width=20, height=20)
        # I patched PGU to use new style classes.
        super(SimpleDialog, self).__init__(title, main, width=40, height=40)

    def close(self, *args, **kwargs):
        print "closing"
        return super(SimpleDialog, self).close(*args, **kwargs)

def run():
    init_pygame()
    app = gui.App()

    dialog = SimpleDialog()
    app.init(dialog)

    app.paint(screen)
    pygame.display.flip()
    while True:
        app.paint(screen)
        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 3: # right mouse button
                    print "opening"
                    dialog.open()
                else:
                    app.event(event)
            elif event.type == pygame.QUIT:
                sys.exit()
            else:
                app.event(event)

if __name__=='__main__':
    run()
</code>```

The behavior I'm seeing: A window opens with a full screen version of the dialog box. Nothing I do will close it, though right clicking will print "opening" on my console and left clicking the little red circle will get it to print "closing". It looks like the dialog box is using the whole background surface instead of a smaller one just for itself.

The behavior I'd like to see: A big black screen appears (I'll draw on it later) and when I right click on it, a little window opens up. When I left click the close button, the window goes away.

I suspect it has something to do with the fact that I'm not using a Desktop, but I don't want the whole game to live inside a gui.

Now, just to be explicit, the question: How do I modify my code to get from the behavior I'm seeing to the behavior I'd like to see? I'm open to using a different gui library if someone knows of something more recently maintained than pgu.

答:
I had tried something similar to nmicahaels's answer to achieve a stand-alone dialog in my pygame app, but I kept getting a typeerror:

pygame_pgu-0.21-py3.6.egg\pgu\gui\surface.py", line 10, in subsurface
      r = pygame.Rect(r) TypeError: Argument must be rect style object

(r was being passed a None)

Removing the dialog height parameter fixed the issue for me. Here's the adapted code

```<code>import pygame, sys
from pgu import gui

# original author: user nmicahaels https://stackoverflow.com/questions/3302973/making-popup-windows-in-pygame-with-pgu

WIDTH = 640
HEIGHT = 480

def init_pygame():
    pygame.display.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.DOUBLEBUF)
    pygame.display.set_caption('Testing PGU')
    return screen

class SimpleDialog(gui.Dialog):
    def __init__(self):
        title = gui.Label("Spam")
        main = gui.Container(width=20, height=20)
        # passing the 'height' parameter resulting in a typerror when paint was called
        super(SimpleDialog, self).__init__(title, main, width=40)  # , height=40)

    def close(self, *args, **kwargs):
        return super(SimpleDialog, self).close(*args, **kwargs)

def run():
    black = (0, 0, 0)
    screen = init_pygame()  # type: pygame.Surface
    refresh = pygame.display.update
    app = gui.App()

    dialog = SimpleDialog()
    # app.init(dialog)

    empty = gui.Container(width=WIDTH, height=HEIGHT)
    app.init(empty)

    app.paint(screen)
    pygame.display.flip()
    while True:
        screen.fill(black)
        app.paint(screen)
        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 3:  # right mouse button
                    dialog.open()
                else:
                    app.event(event)
            elif event.type == pygame.QUIT:
                sys.exit()
            else:
                app.event(event)
    refresh()

if __name__ == '__main__':
    run()
</code>```

Title: Making popup windows in pygame with pgu

Body:
I'm trying to add some gui elements (dialog boxes with buttons) to a game I'm writing with pygame. I looked around for a decent gui toolkit and ended up with pgu. Anyway, I'm trying to get it to pop up a dialog box, which it does (sort of), but it isn't closing.

Here's a simplified version of my code that just shows the behavior I care about:

import pygame, sys
from pgu import gui

screen = None
WIDTH = 640
HEIGHT = 480

def init_pygame():
    global screen
    pygame.display.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.DOUBLEBUF)
    pygame.display.set_caption('Testing PGU')

class SimpleDialog(gui.Dialog):
    def __init__(self):
        title = gui.Label("Spam")
        main = gui.Container(width=20, height=20)
        # I patched PGU to use new style classes.
        super(SimpleDialog, self).__init__(title, main, width=40, height=40)

    def close(self, *args, **kwargs):
        print "closing"
        return super(SimpleDialog, self).close(*args, **kwargs)

def run():
    init_pygame()
    app = gui.App()

    dialog = SimpleDialog()
    app.init(dialog)

    app.paint(screen)
    pygame.display.flip()
    while True:
        app.paint(screen)
        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 3: # right mouse button
                    print "opening"
                    dialog.open()
                else:
                    app.event(event)
            elif event.type == pygame.QUIT:
                sys.exit()
            else:
                app.event(event)

if __name__=='__main__':
    run()

The behavior I'm seeing: A window opens with a full screen version of the dialog box. Nothing I do will close it, though right clicking will print "opening" on my console and left clicking the little red circle will get it to print "closing". It looks like the dialog box is using the whole background surface instead of a smaller one just for itself.

The behavior I'd like to see: A big black screen appears (I'll draw on it later) and when I right click on it, a little window opens up. When I left click the close button, the window goes away.

I suspect it has something to do with the fact that I'm not using a Desktop, but I don't want the whole game to live inside a gui.

Now, just to be explicit, the question: How do I modify my code to get from the behavior I'm seeing to the behavior I'd like to see? I'm open to using a different gui library if someone knows of something more recently maintained than pgu.

Body:
I had tried something similar to nmicahaels's answer to achieve a stand-alone dialog in my pygame app, but I kept getting a typeerror:

pygame_pgu-0.21-py3.6.egg\pgu\gui\surface.py", line 10, in subsurface
      r = pygame.Rect(r) TypeError: Argument must be rect style object

(r was being passed a None)

Removing the dialog height parameter fixed the issue for me. Here's the adapted code

import pygame, sys
from pgu import gui

# original author: user nmicahaels https://stackoverflow.com/questions/3302973/making-popup-windows-in-pygame-with-pgu

WIDTH = 640
HEIGHT = 480

def init_pygame():
    pygame.display.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.DOUBLEBUF)
    pygame.display.set_caption('Testing PGU')
    return screen

class SimpleDialog(gui.Dialog):
    def __init__(self):
        title = gui.Label("Spam")
        main = gui.Container(width=20, height=20)
        # passing the 'height' parameter resulting in a typerror when paint was called
        super(SimpleDialog, self).__init__(title, main, width=40)  # , height=40)

    def close(self, *args, **kwargs):
        return super(SimpleDialog, self).close(*args, **kwargs)

def run():
    black = (0, 0, 0)
    screen = init_pygame()  # type: pygame.Surface
    refresh = pygame.display.update
    app = gui.App()

    dialog = SimpleDialog()
    # app.init(dialog)

    empty = gui.Container(width=WIDTH, height=HEIGHT)
    app.init(empty)

    app.paint(screen)
    pygame.display.flip()
    while True:
        screen.fill(black)
        app.paint(screen)
        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 3:  # right mouse button
                    dialog.open()
                else:
                    app.event(event)
            elif event.type == pygame.QUIT:
                sys.exit()
            else:
                app.event(event)
    refresh()

if __name__ == '__main__':
    run()


来源: stackexchange

问:
grails rollback db operation on some error

I have a service where to save a lot of data to db.
Using MYSQL
I have used like this

```<code>Domain1.withTransaction {text->
            def domain1=//Create my domain object to save
             if(!domain1.save()){
               domain1.errors.each {
                      println it
               }
               throw new RuntimeException('unable to save domain1')
        }
        Domain2.withTransaction {text->
            def domain2=//Create my domain object to save
             if(!domain2.save()){
               domain2.errors.each {
                      println it
               }
               throw new RuntimeException('unable to save domain2')
        }
</code>```

My problem if there occurred any problem in saving domain2 i need to roll back domain1 save also.

I need to remove domain1 from db.

答:
Try removing the Domain2.withTransaction {text-> part.
You are already inside a transaction with your first call.
If you do further work inside the brackets, you should stay within the same transaction and domain1 should be rolled back if you throw and exception after checking domain2.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a service where to save a lot of data to db.
Using MYSQL
I have used like this

Domain1.withTransaction {text->
            def domain1=//Create my domain object to save
             if(!domain1.save()){
               domain1.errors.each {
                      println it
               }
               throw new RuntimeException('unable to save domain1')
        }
        Domain2.withTransaction {text->
            def domain2=//Create my domain object to save
             if(!domain2.save()){
               domain2.errors.each {
                      println it
               }
               throw new RuntimeException('unable to save domain2')
        }

My problem if there occurred any problem in saving domain2 i need to roll back domain1 save also.

I need to remove domain1 from db.


问:
Trying to use Async and Await from different functions
While I thought I was using Async and Await keywords properly, it appears as though I am doing something wrong.

I am using PouchDB, which is a great Javascript database that syncs with CouchDB. PouchDB uses promises for many of its functions, and has native support for Async and Await.  As an example, to retrieve the basic information about a database, you would use the following code:

```<code>    db.info().then(function (info) {
  console.log(info);
})
</code>```

I understand this, and it works.  But if I try and put this inside a function, and then call that function, things go haywire. And I'm sure it's me and not PouchDB that is the problem...

```<code>function getLocalDBInfo(db){

  try {
    db.info().then(function (info) {
      return info;
    });
  } catch (error) {
    console.log("can't get local DB info: ", error);
  }
}

async function testing(db){
  try {
    var info=await getLocalDBInfo(db);
    await console.log("DB info=", info);
    await console.log("Doc count= ", info.doc_count);
  }
  catch(err){
    console.log("error=",err);
  }

  //info contains...
    //{"doc_count":0,"update_seq":0,"db_name":"kittens"}
}

testing(MY_db);
</code>```

If I log info inside the getLocalDBInfo function, it eventually (ie. after the promise fulfills) logs info to the console.  But, the logs inside the testing function return immediately with undefined.  It makes sense to me that they are returning undefined because they are returning immediately, but I was trying to have them wait for info by using async and await.  Any suggestions as to what I am doing wrong?

答:
getLocalDBInfo generates a promise, attaches a callback to it, then returns undefined. It doesn't return the resolved promise and you can't await on an undefined (well, you can, but it won't do anything).

You neee to change getLocalDBInfo to actually return the promise.

Also, why do you have a then block with the signature info => info? All this will do is unwrap the async value and then wrap it again. You can omit the then callback entirely.

Similarly, are you sure you need to wrap the db.info call in a try/catch? I wonder if you might be intending to use a promise.catch here instead. The try/catch construct only grabs promise rejections when awaiting an expression.

ContentLicense: CC BY-SA 4.0

Body:
While I thought I was using Async and Await keywords properly, it appears as though I am doing something wrong.

I am using PouchDB, which is a great Javascript database that syncs with CouchDB. PouchDB uses promises for many of its functions, and has native support for Async and Await.  As an example, to retrieve the basic information about a database, you would use the following code:

    db.info().then(function (info) {
  console.log(info);
})

I understand this, and it works.  But if I try and put this inside a function, and then call that function, things go haywire. And I'm sure it's me and not PouchDB that is the problem...

function getLocalDBInfo(db){

  try {
    db.info().then(function (info) {
      return info;
    });
  } catch (error) {
    console.log("can't get local DB info: ", error);
  }
}

async function testing(db){
  try {
    var info=await getLocalDBInfo(db);
    await console.log("DB info=", info);
    await console.log("Doc count= ", info.doc_count);
  }
  catch(err){
    console.log("error=",err);
  }

  //info contains...
    //{"doc_count":0,"update_seq":0,"db_name":"kittens"}
}

testing(MY_db);

If I log info inside the getLocalDBInfo function, it eventually (ie. after the promise fulfills) logs info to the console.  But, the logs inside the testing function return immediately with undefined.  It makes sense to me that they are returning undefined because they are returning immediately, but I was trying to have them wait for info by using async and await.  Any suggestions as to what I am doing wrong?


问:
SignalR Core - StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1
I have two projects.

First, WebApi that contains Hub for using SignalR:

```<code>public class NotificationsHub : Hub
{
    public async Task GetUpdateForServer(string call)
    {
        await this.Clients.Caller.SendAsync("ReciveServerUpdate", call);
    }
}
</code>```

I set up that Hub in Startup.cs:

```<code>    public void ConfigureServices(IServiceCollection services)
    {
        // ofc there is other stuff here

        services.AddHttpContextAccessor();
        services.AddSignalR();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseSignalR(routes => routes.MapHub<NotificationsHub>("/Notifications"));
    }
</code>```

I belive that i would make notifications like this in TaskController.cs:

```<code>    [HttpPost]
    public async Task<IActionResult> PostTask([FromBody] TaskManager.Models.Task task)
    {
        if (!this.ModelState.IsValid)
        {
            return this.BadRequest(this.ModelState);
        }

        this.taskService.Add(task);

        //here, after POST i want to notify whole clients
        await this.notificationsHub.Clients.All.SendAsync("NewTask", "New Task in database!");

        return this.Ok(task);
    }
</code>```

The problem starts here.

I have WPF app that contains HubService:

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

    public ObservableCollection<string> Notifications { get; set; }

    public async void Initialized()
    {
        this.Notifications = new ObservableCollection<string>();

        var queryStrings = new Dictionary<string, string>
        {
            { "group", "allUpdates" }
        };

        var hubConnection = new HubConnection("https://localhost:44365/Notifications", queryStrings);
        var hubProxy = hubConnection.CreateHubProxy("NotificationsHub");

        hubProxy.On<string>("ReciveServerUpdate", call =>
        {
            //todo
        });

        await hubConnection.Start();
    }
}
</code>```

And i initialize it in my MainViewModel constructor:

```<code>    public MainWindowViewModel()
    {
        HubService.Instance.Initialized();
    }
</code>```

The problem starts in await hubConnection.Start();. From this line, i get an error:

"StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:  X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcQWRtaW5cc291cmNlXHJlcG9zXFRhc2tNYW5hZ2VyXFRhc2tNYW5hZ2VyLXdlYmFwaVxOb3RpZmljYXRpb25zXHNpZ25hbHJcbmVnb3RpYXRl?=  Date: Tue, 28 May 2019 16:25:13 GMT  Server: Kestrel  X-Powered-By: ASP.NET  Content-Length: 0

My question is, what im doing wrong and how to connect to Hub in my WebApi project?

EDIT

Hub seems to work. I typed into my browser: https://localhost:44365/notifications and i got message:

Connection ID required

EDIT2

WPF project is .NET Framework 4.7.2 and WebApi is Core 2.1.

答:
i found a solution.

Looking for it on the internet i discovered, that reference to Microsoft.AspNet.SignalR wont work with SignalR server based on Core.

I needed to change some things in my WPF project that is .NET Framework 4.7.2. First, delete reference to AspNet.SignalR and change it to Core one. To get this, just install this nugets in your .Net Framework proj:

Then, this service compiles without errors (idk if it works yet, but i get Connected count to 1 on my WebApi with Core SignalR):

```<code>using System.Collections.ObjectModel;
using Microsoft.AspNetCore.SignalR.Client;

public class HubService
{
    public static HubService Instance { get; } = new HubService();

    public ObservableCollection<string> Notifications { get; set; }

    public async void Initialized()
    {
        this.Notifications = new ObservableCollection<string>();

        var hubConnection = new HubConnectionBuilder()
            .WithUrl(UrlBuilder.BuildEndpoint("Notifications"))
            .Build();

        hubConnection.On<string>("ReciveServerUpdate", update =>
        {
            //todo, adding updates tolist for example
        });

        await hubConnection.StartAsync();
    }
}
</code>```

Now my WPF compiles without exception. Im getting notifications from server

Body:
I have two projects.

First, WebApi that contains Hub for using SignalR:

public class NotificationsHub : Hub
{
    public async Task GetUpdateForServer(string call)
    {
        await this.Clients.Caller.SendAsync("ReciveServerUpdate", call);
    }
}

I set up that Hub in Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        // ofc there is other stuff here

        services.AddHttpContextAccessor();
        services.AddSignalR();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseSignalR(routes => routes.MapHub<NotificationsHub>("/Notifications"));
    }

I belive that i would make notifications like this in TaskController.cs:

    [HttpPost]
    public async Task<IActionResult> PostTask([FromBody] TaskManager.Models.Task task)
    {
        if (!this.ModelState.IsValid)
        {
            return this.BadRequest(this.ModelState);
        }

        this.taskService.Add(task);

        //here, after POST i want to notify whole clients
        await this.notificationsHub.Clients.All.SendAsync("NewTask", "New Task in database!");

        return this.Ok(task);
    }

The problem starts here.

I have WPF app that contains HubService:

public class HubService
{
    public static HubService Instance { get; } = new HubService();

    public ObservableCollection<string> Notifications { get; set; }

    public async void Initialized()
    {
        this.Notifications = new ObservableCollection<string>();

        var queryStrings = new Dictionary<string, string>
        {
            { "group", "allUpdates" }
        };

        var hubConnection = new HubConnection("https://localhost:44365/Notifications", queryStrings);
        var hubProxy = hubConnection.CreateHubProxy("NotificationsHub");

        hubProxy.On<string>("ReciveServerUpdate", call =>
        {
            //todo
        });

        await hubConnection.Start();
    }
}

And i initialize it in my MainViewModel constructor:

    public MainWindowViewModel()
    {
        HubService.Instance.Initialized();
    }

The problem starts in await hubConnection.Start();. From this line, i get an error:

"StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:  X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcQWRtaW5cc291cmNlXHJlcG9zXFRhc2tNYW5hZ2VyXFRhc2tNYW5hZ2VyLXdlYmFwaVxOb3RpZmljYXRpb25zXHNpZ25hbHJcbmVnb3RpYXRl?=  Date: Tue, 28 May 2019 16:25:13 GMT  Server: Kestrel  X-Powered-By: ASP.NET  Content-Length: 0

My question is, what im doing wrong and how to connect to Hub in my WebApi project?

EDIT

Hub seems to work. I typed into my browser: https://localhost:44365/notifications and i got message:

Connection ID required

EDIT2

WPF project is .NET Framework 4.7.2 and WebApi is Core 2.1.

Body:
i found a solution.

Looking for it on the internet i discovered, that reference to Microsoft.AspNet.SignalR wont work with SignalR server based on Core.

I needed to change some things in my WPF project that is .NET Framework 4.7.2. First, delete reference to AspNet.SignalR and change it to Core one. To get this, just install this nugets in your .Net Framework proj:

Then, this service compiles without errors (idk if it works yet, but i get Connected count to 1 on my WebApi with Core SignalR):

using System.Collections.ObjectModel;
using Microsoft.AspNetCore.SignalR.Client;

public class HubService
{
    public static HubService Instance { get; } = new HubService();

    public ObservableCollection<string> Notifications { get; set; }

    public async void Initialized()
    {
        this.Notifications = new ObservableCollection<string>();

        var hubConnection = new HubConnectionBuilder()
            .WithUrl(UrlBuilder.BuildEndpoint("Notifications"))
            .Build();

        hubConnection.On<string>("ReciveServerUpdate", update =>
        {
            //todo, adding updates tolist for example
        });

        await hubConnection.StartAsync();
    }
}

Now my WPF compiles without exception. Im getting notifications from server


问:
Non-existence of approximation algorithm for the knapsack problem
I am working on the following exercise: Prove that if $P \neq NP$, there cannot exist an approximation algorithm $A$ for the knapsack problem (KP) such that $\exists k \in \mathhbb{N}, \forall I \in S: OPT(I) - P_A(I) \leq k$ where $OPT(I)$ is the optimal profit on instance $I$ and $P_A(I)$ is the profit calculated by $A$.

I know that there is a FPTAS $A'$ for the KP which guarantees a solution with profit $P_{A'}(I) \geq (1 - \varepsilon)OPT(I)$ on any instance $I$ and $\varepsilon > 0$.

My approach is to create a contradiction. For this I consider $A = A'$ and aim to show that $P_A(I) \geq (1 - \varepsilon)OPT(I) \geq ... \geq OPT(I) - c$ where $c \in (0,1)$ is a constant. This way, for an adequate choice of $\varepsilon$ I would show that we obtain an optimal solution within polynomial time. However, I struggle how to choose $\varepsilon$.

I need some advice on how to proceed. Many thanks in advance!

答:
The contradiction is a bit more subtle.

Consider an instance I' derived from I by increasing all the values of the items in I n-fold. An optimal profit Opt(I') is n-times the optimal profit of Opt(I), and the solution to both problems is comprised by the same set of items (prove it!).

So, if A finds the Opt(I') - k solution, it also finds an Opt(I) - k/n one. Making n large enough, conclude A would solve any instance I better than Opt(I) * (1 - eps) for any given eps.

For the integer values it is enough to take any n > k. For the real values you need some more work, namely to prove that A' is not universal, but must depend on eps.


问:
How do I count the number of records that have one or more associated object?
I have a Property model that has_many :photos. I want to count the number of properties that have one or more photo.

How do I do that?

I have tried the simple:

```<code>> Property.where('properties.photos.count > ?', 0).count

   (3.1ms)  SELECT COUNT(*) FROM "properties" WHERE (properties.photos.count > 1)
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....
                                                  ^
: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos.count > 0)
from /ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....
</code>```

to:

```<code>> Property.joins(:photos).where('photos.count > ?', 0).count

   (3.7ms)  SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
: SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
</code>```

to the more advanced:

```<code>>Property.includes(:photos).group(['property.id', 'photos.id']).order('COUNT(photos.id) DESC').count

(0.6ms)  SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...
                                                             ^
: SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...
</code>```

and a few other variations, and they all produce similar errors.

What am I doing wrong?

Note: All I want is the count of properties that have photos.count > 0. I don't want a hash of all the properties and the count of photos. In other words, if there are 5000 properties in my db, I want to build a scope that returns just the properties that actually have photos.

答:
Since all you want is the Propertys with Photos then an INNER JOIN is all you need.

```<code>Property.joins(:photos)
</code>```

That is it. If you want a scope then

```<code>class Property < ActiveRecord::Base
  scope :with_photos, -> {joins(:photos)}
end
</code>```

To get the count using rails 3.2

```<code>Property.with_photos.count(distinct: true)
</code>```

You could also use: in rails 3.2

```<code>Property.count(joins: :photos, distinct: true)
</code>```

ActiveRecord::Calculations#count Doc

This will execute

```<code>SELECT
  COUNT(DISTINCT properties.id)
FROM
  properties
  INNER JOIN photos ON photos.property_id = properties.id
</code>```

Body:
I have a Property model that has_many :photos. I want to count the number of properties that have one or more photo.

How do I do that?

I have tried the simple:

> Property.where('properties.photos.count > ?', 0).count

   (3.1ms)  SELECT COUNT(*) FROM "properties" WHERE (properties.photos.count > 1)
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....
                                                  ^
: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos.count > 0)
from /ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....

to:

> Property.joins(:photos).where('photos.count > ?', 0).count

   (3.7ms)  SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
: SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...

to the more advanced:

>Property.includes(:photos).group(['property.id', 'photos.id']).order('COUNT(photos.id) DESC').count

(0.6ms)  SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...
                                                             ^
: SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...

and a few other variations, and they all produce similar errors.

What am I doing wrong?

Note: All I want is the count of properties that have photos.count > 0. I don't want a hash of all the properties and the count of photos. In other words, if there are 5000 properties in my db, I want to build a scope that returns just the properties that actually have photos.

Body:
Since all you want is the Propertys with Photos then an INNER JOIN is all you need.

Property.joins(:photos)

That is it. If you want a scope then

class Property < ActiveRecord::Base
  scope :with_photos, -> {joins(:photos)}
end

To get the count using rails 3.2

Property.with_photos.count(distinct: true)

You could also use: in rails 3.2

Property.count(joins: :photos, distinct: true)

ActiveRecord::Calculations#count Doc

This will execute

SELECT
  COUNT(DISTINCT properties.id)
FROM
  properties
  INNER JOIN photos ON photos.property_id = properties.id


问:
SSRS OraOLEDB.Oracle provider is not registered on the local machine
I have been trying to create a Data source in SSRS to the oracle DB. I have already installed Oracle 12.1.0, updated the windows environment variable to the oracle folder and registered the regsvr32.exe to the OraOledb12.dll.

I have also restarted my system several times. I am still getting the error below. Can somebody please help me in that.

答: I found the solution. I had to install Oracle 11 Client_32. Also cross check the environment variables. It worked after that</p>


问:
Is it possible to send a function from server to a client?
By my yet little understanding on how NodeJS/Javascript works, I believe it should be possible. Is it?

I would like to be able to send a function to a client based on http request, something like this (pseudo short code):

```<code>// Server
server.get("/function",()=>{
   return function () => {
     console.log('test)
}

// client
request ("server/function",(res)=>{
     func = res.body
     func()
// # result
// test
</code>```

I have tried to convert to string to send the function from the server and convert back to an object on the client, but it return errors that I couldn't understand why as if I send a simple key value json object it works.

```<code>// server
const http = require('http');
const port = 3000;
const hostname = '127.0.0.1';

const server = http.createServer((req, res) => {
    if (req.url === '/function') {
        res.statusCode = 200;
        function func () {
            console.log('test')
        }
        res.end(func.toString())
    }
});

server.listen(3000)
</code>```

```<code>// client
const http = require('http');

const httpGet = url => {
    return new Promise((resolve, reject) => {
        http.get(url, res => {
            res.setEncoding('utf8');
            let body = '';
            res.on('data', chunk => body += chunk);
            res.on('end', () => resolve(body));
        }).on('error', reject);
    });
};

const call = async () => {
    const body = await httpGet('http://localhost:3000/function')
    console.log(`${body}`)
    func = JSON.parse(body) // try to redefine function based on the response
}

const func = () => {
    console.log('before')
}
func() // run the func defined here

call()

func() // run the function got from the request?

</code>```

The idea is to have a client that will be able to execute almoust any code without the need of updating the client itself.

答:
I'm not sure this is the best idea.

Historically, the client-server relationship you are describing was inversed through remote procedure calls where the client would invoke a specific endpoint on a remote server. It sounds like your biggest draw towards having the client arbitrarily execute the code was the removal of updating the client code. What happens if you want to make backwards-incompatible changes to the server code? I think you will have better success using versioned API endpoints to execute code server-side based on client-side logic, which you will find many RPC and/or REST frameworks for within npm.

The ideia is to have a client that will be able to execute almoust any code without the need of updating the client itself.

One final thing to keep in mind are the security implications of this. What happens if I find your client and substitute in my malicious JavaScript?

Body:
By my yet little understanding on how NodeJS/Javascript works, I believe it should be possible. Is it?

I would like to be able to send a function to a client based on http request, something like this (pseudo short code):

// Server
server.get("/function",()=>{
   return function () => {
     console.log('test)
}

// client
request ("server/function",(res)=>{
     func = res.body
     func()
// # result
// test

I have tried to convert to string to send the function from the server and convert back to an object on the client, but it return errors that I couldn't understand why as if I send a simple key value json object it works.

// server
const http = require('http');
const port = 3000;
const hostname = '127.0.0.1';

const server = http.createServer((req, res) => {
    if (req.url === '/function') {
        res.statusCode = 200;
        function func () {
            console.log('test')
        }
        res.end(func.toString())
    }
});

server.listen(3000)

// client
const http = require('http');

const httpGet = url => {
    return new Promise((resolve, reject) => {
        http.get(url, res => {
            res.setEncoding('utf8');
            let body = '';
            res.on('data', chunk => body += chunk);
            res.on('end', () => resolve(body));
        }).on('error', reject);
    });
};

const call = async () => {
    const body = await httpGet('http://localhost:3000/function')
    console.log(`${body}`)
    func = JSON.parse(body) // try to redefine function based on the response
}

const func = () => {
    console.log('before')
}
func() // run the func defined here

call()

func() // run the function got from the request?

The idea is to have a client that will be able to execute almoust any code without the need of updating the client itself.


问:
echo statement not working? Seems to be formatted correctly
I'm creating a object in javascript echo'd by PHP, the syntax seems to be correct but it is giving me an error.

The variables I am passing to the object are strings and I have tried putting them in quotes, etc. I also tried creating a JS function to do this and it had similar results.

```<code><?PHP

$TEDS = $db->query("
SELECT a.*
FROM TEDS a
");
//Add each TED location into a javascript array.

echo '<script type="text/javascript">';
while($TED = $TEDS->fetch_assoc())
{
   echo 'var pos = {lat: '.$TED['latitude'].', lng: '.$TED['longitude'].'};'; //THIS ECHO STATEMENT IS THE ONE GIVING ME PROBLEMS.
}
echo '</script>';

?>

</code>```

答:
i would try to write the full text, after the loop. This way you can build a full json array:

<?PHP

$TEDS = $db->query("
SELECT a.*
FROM TEDS a
");
//Add each TED location into a javascript array.

echo '';

?>
```

Another way would be to just json_decode($TED).

Body:
I'm creating a object in javascript echo'd by PHP, the syntax seems to be correct but it is giving me an error.

The variables I am passing to the object are strings and I have tried putting them in quotes, etc. I also tried creating a JS function to do this and it had similar results.

<?PHP

$TEDS = $db->query("
SELECT a.*
FROM TEDS a
");
//Add each TED location into a javascript array.

echo '';

?>

Body:
i would try to write the full text, after the loop. This way you can build a full json array:

<?PHP

$TEDS = $db->query("
SELECT a.*
FROM TEDS a
");
//Add each TED location into a javascript array.

echo '<script type="text/javascript">';
$text = 'var positions = [';
while($TED = $TEDS->fetch_assoc()) {
   $text .= '{lat: '.$TED['latitude'].', lng: '.$TED['longitude'].'},';
}
// remove last comma
$text = substr($text,0 , strlen($text)-2);
$text .= '];'
echo $text;
echo '</script>';

?>

Another way would be to just json_decode($TED).


问:
iPad; TableView full of arbitrary number of text fields and buttons in different rows. resignFirstResponder on all textfields when button is pressed?
iPad:

I have a tableView full of an arbitrary number of text fields and buttons in different rows.

When you press a button I a modal popup will popup.  If you press a button while editing a text field (and the keyboard is displayed on the iPad) something hilarious will happen.  The popover will be 75% off the corner of the screen (with a quarter visible in quarter.)

To avoid this bad behavior, how do you resignFirstResponder on all textfields in the table when the button is pressed?

答:
You can implement this method:

```<code>-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
     [textField resignFirstResponder];
     return YES;
}
</code>```

As long as the textfields' delegate are your current view controller, it should work fine :)

Body:
You can implement this method:

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
     [textField resignFirstResponder];
     return YES;
}

As long as the textfields' delegate are your current view controller, it should work fine :)


问:
Where is PIP installed by default with Python 3.7 for Mac?
I am new to Python and looking to use to to create some cool solutions. The documentation says that pip is included by default with Python 3.4+ and I've just installed version 3.7.3 but cannot located pip as I was attempting to use it to install the Requests package for API calls.

```<code>$ python3 --version
Python 3.7.3
$ pip --version
-bash: pip: command not found
</code>```

So I can see in fact that version 3.7.3 of Python is installed, yet pip isn't? I checked both Library/Python/3.7/bin/ and Library/Python/3.7/lib/python/site-packages/ and do not see any reference to pip.

The documentation states that you can use a curl command to get pip and then install it. I am new to the terminal and have never used a curl command. Also, I've read you want to keep your Python3 stuff away from the system Python version, so would I use the following?

```<code>$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
$ python3 get-pip.py
</code>```

答:
The following worked for me:

```<code>$ which pip3.7
</code>```

which returned

```<code>/Library/Frameworks/Python.framework/Versions/3.7/bin/pip3.7
</code>```

The purpose of my question was to find out if pip was installed so i could use it to get another package. It was, so I ended up doing the following with success.

```<code>$ pip3.7 install requests
</code>```

which returned

```<code>Installing collected packages: idna, urllib3, chardet, certifi, requests
Successfully installed certifi-2019.3.9 chardet-3.0.4 idna-2.8 requests-2.22.0 urllib3-1.25.3
</code>```

I'd imagine that since I only installed Python3.7 on my mac and since pip3.7 was included, i could have likely input pip3 install requests although I am not sure if there were other versions of pip installed prior what would happen, maybe someone could clarify in comments about the nuances.

Body:
I am new to Python and looking to use to to create some cool solutions. The documentation says that pip is included by default with Python 3.4+ and I've just installed version 3.7.3 but cannot located pip as I was attempting to use it to install the Requests package for API calls.

$ python3 --version
Python 3.7.3
$ pip --version
-bash: pip: command not found

So I can see in fact that version 3.7.3 of Python is installed, yet pip isn't? I checked both Library/Python/3.7/bin/ and Library/Python/3.7/lib/python/site-packages/ and do not see any reference to pip.

The documentation states that you can use a curl command to get pip and then install it. I am new to the terminal and have never used a curl command. Also, I've read you want to keep your Python3 stuff away from the system Python version, so would I use the following?

$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
$ python3 get-pip.py

Body:
The following worked for me:

$ which pip3.7

which returned

/Library/Frameworks/Python.framework/Versions/3.7/bin/pip3.7

The purpose of my question was to find out if pip was installed so i could use it to get another package. It was, so I ended up doing the following with success.

$ pip3.7 install requests

which returned

Installing collected packages: idna, urllib3, chardet, certifi, requests
Successfully installed certifi-2019.3.9 chardet-3.0.4 idna-2.8 requests-2.22.0 urllib3-1.25.3

I'd imagine that since I only installed Python3.7 on my mac and since pip3.7 was included, i could have likely input pip3 install requests although I am not sure if there were other versions of pip installed prior what would happen, maybe someone could clarify in comments about the nuances.


问:
Making two seaborn countplots that share the same axis
I'm looking to use seaborn countplots to display the frequency distribution of two different lists of data on one axis. The problem I'm having is that both lists contain unique elements, so I can't simply plot one list using the axis of the larger one.

I've tried using python's count objects, but the axis of the graph didn't match up with the counts displayed on the graph since python dictionaries are unordered.

```<code>import seaborn as sns

first_list = ["a", "b", "c", "d", "e", "a", "b", "c", "a", "b","n"]
second_list = ["a","b","c","d", "e", "e","d","c","e","q"]

sns.countplot(first_list, color="blue", alpha=.5)
sns.countplot(second_list, color="red",alpha=.5)

plt.show()
</code>```

The code above should display a graph including the frequencies for the unique values "n", and "q", but displays a graph that's axis only includes the values from the second list.

答:
I think it would be better to combine your data into one dataframe that you pass to seaborn instead of making two plots on top of each other. I called sns.barplot on the counts instead of using sns.countplot on the original raw values.

```<code>#convert the lists to series and get the counts
first_list = pd.Series(
    ["a", "b", "c", "d", "e", "a", "b", "c", "a", "b","n"]
).value_counts()

second_list = pd.Series(
    ["a","b","c","d", "e", "e","d","c","e","q"]
).value_counts()

#get the counts as a dataframe
df=pd.concat([first_list,second_list],axis=1)
df.columns=['first','second']

# melt the data frame so it has a "tidy" data format
df=df.reset_index().melt(id_vars=['index'])
</code>```

```<code>df

   index variable  value
0      a    first    3.0
1      b    first    3.0
2      c    first    2.0
3      d    first    1.0
4      e    first    1.0
5      n    first    1.0
6      q    first    NaN
7      a   second    1.0
8      b   second    1.0
9      c   second    2.0
10     d   second    2.0
11     e   second    3.0
12     n   second    NaN
13     q   second    1.0

</code>```

```<code>#plot a bar graph and assign variable to hue
sns.barplot(
    x='index',
    y='value',
    hue='variable',
    data=df,
    palette=['blue','red'],
    alpha=.5,
    dodge=False,
)

plt.show()
</code>```

Body:
I'm looking to use seaborn countplots to display the frequency distribution of two different lists of data on one axis. The problem I'm having is that both lists contain unique elements, so I can't simply plot one list using the axis of the larger one.

I've tried using python's count objects, but the axis of the graph didn't match up with the counts displayed on the graph since python dictionaries are unordered.

import seaborn as sns

first_list = ["a", "b", "c", "d", "e", "a", "b", "c", "a", "b","n"]
second_list = ["a","b","c","d", "e", "e","d","c","e","q"]

sns.countplot(first_list, color="blue", alpha=.5)
sns.countplot(second_list, color="red",alpha=.5)

plt.show()

The code above should display a graph including the frequencies for the unique values "n", and "q", but displays a graph that's axis only includes the values from the second list.

Body:
I think it would be better to combine your data into one dataframe that you pass to seaborn instead of making two plots on top of each other. I called sns.barplot on the counts instead of using sns.countplot on the original raw values.

#convert the lists to series and get the counts
first_list = pd.Series(
    ["a", "b", "c", "d", "e", "a", "b", "c", "a", "b","n"]
).value_counts()

second_list = pd.Series(
    ["a","b","c","d", "e", "e","d","c","e","q"]
).value_counts()

#get the counts as a dataframe
df=pd.concat([first_list,second_list],axis=1)
df.columns=['first','second']

# melt the data frame so it has a "tidy" data format
df=df.reset_index().melt(id_vars=['index'])

df

   index variable  value
0      a    first    3.0
1      b    first    3.0
2      c    first    2.0
3      d    first    1.0
4      e    first    1.0
5      n    first    1.0
6      q    first    NaN
7      a   second    1.0
8      b   second    1.0
9      c   second    2.0
10     d   second    2.0
11     e   second    3.0
12     n   second    NaN
13     q   second    1.0

#plot a bar graph and assign variable to hue
sns.barplot(
    x='index',
    y='value',
    hue='variable',
    data=df,
    palette=['blue','red'],
    alpha=.5,
    dodge=False,
)

plt.show()


问:
Get Google Sheets into a Pandas Dataframe
I am looking for a code which would help me get an excel printed automatically of a google sheet using Python

I have tried a few codes, but to no success

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/Dummy Dataset.readonly']

# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1NXenqaum6PHsDBXyv-_tGKIL-z4tSaCsZpUT9Q5wpkY'
SAMPLE_RANGE_NAME = 'Sheet1!A1:L'

def main():
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('sheets', 'v4', credentials=creds)

    # Call the Sheets API
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                range=SAMPLE_RANGE_NAME).execute()
    values = result.get('values', [])

    if not values:
        print('No data found.')
    else:

        for row in values:
            # Print columns A and E, which correspond to indices 0 and 4.
            print('%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s' % (row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11]))

if __name__ == '__main__':
main()

```

While I am able to print the google sheet, I am not able to store into a dataframe, such that I can later print it into an excel workbook

答:
This is how I got a working Google Sheets to Pandas dataframe, with help from Google's Python Quickstart page & an article that I found on Medium, and tailored to meet my needs.</p>

```<code># This works in Python 3.6+
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os.path
import pickle
import pandas as pd

SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"]
SPREADSHEET_ID = YOUR_ID_GOES_HERE
RANGE_NAME = YOUR_RANGE_GOES_HERE

def get_google_sheet(spreadsheet_id, range_name):
    """ Retrieve sheet data using OAuth credentials and Google Python API. """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists("token.pickle"):
        with open("token.pickle", "rb") as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open("token.pickle", "wb") as token:
            pickle.dump(creds, token)
    service = build("sheets", "v4", credentials=creds)

    return (
        service.spreadsheets()
        .values()
        .get(spreadsheetId=spreadsheet_id, range=range_name)
        .execute()
    )

def to_dataframe(gsheet):
    """ Converts Google sheet data to a Pandas DataFrame.
    Note: This script assumes that your data contains a header file on the first row!
    Also note that the Google API returns 'none' from empty cells - in order for the code
    below to work, you'll need to make sure your sheet doesn't contain empty cells,
    or update the code to account for such instances.
    """
    return pd.DataFrame(gsheet.get("values")[1:], columns=gsheet.get("values")[0])
</code>```

Body:
I am looking for a code which would help me get an excel printed automatically of a google sheet using Python

I have tried a few codes, but to no success

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/Dummy Dataset.readonly']

# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1NXenqaum6PHsDBXyv-_tGKIL-z4tSaCsZpUT9Q5wpkY'
SAMPLE_RANGE_NAME = 'Sheet1!A1:L'

def main():
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('sheets', 'v4', credentials=creds)

    # Call the Sheets API
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                range=SAMPLE_RANGE_NAME).execute()
    values = result.get('values', [])

    if not values:
        print('No data found.')
    else:

        for row in values:
            # Print columns A and E, which correspond to indices 0 and 4.
            print('%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s' % (row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11]))

if __name__ == '__main__':
main()

While I am able to print the google sheet, I am not able to store into a dataframe, such that I can later print it into an excel workbook

Body:
This is how I got a working Google Sheets to Pandas dataframe, with help from Google's Python Quickstart page & an article that I found on Medium, and tailored to meet my needs.

# This works in Python 3.6+
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os.path
import pickle
import pandas as pd

SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"]
SPREADSHEET_ID = YOUR_ID_GOES_HERE
RANGE_NAME = YOUR_RANGE_GOES_HERE

def get_google_sheet(spreadsheet_id, range_name):
    """ Retrieve sheet data using OAuth credentials and Google Python API. """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists("token.pickle"):
        with open("token.pickle", "rb") as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open("token.pickle", "wb") as token:
            pickle.dump(creds, token)
    service = build("sheets", "v4", credentials=creds)

    return (
        service.spreadsheets()
        .values()
        .get(spreadsheetId=spreadsheet_id, range=range_name)
        .execute()
    )

def to_dataframe(gsheet):
    """ Converts Google sheet data to a Pandas DataFrame.
    Note: This script assumes that your data contains a header file on the first row!
    Also note that the Google API returns 'none' from empty cells - in order for the code
    below to work, you'll need to make sure your sheet doesn't contain empty cells,
    or update the code to account for such instances.
    """
    return pd.DataFrame(gsheet.get("values")[1:], columns=gsheet.get("values")[0])


问:
Merging the output into one list (NOT merging a list of lists)
Okay, I have converted an image to 1's and 0's. I then changed the code so that it would output the 1's and 0's into a list of each row, this way I could reverse the rows to flip the image. Now I am trying to merge those lists back together. At first the output was a list of lists, and I knew how to combine those lists, but when I reversed the order of the lists, it was no longer a list of lists and what I thought would work to combine them didn't.

So here is the code I used to first convert the image and then remove the header and extra 0's that the program put into the code:

```<code>with open("monoT.bmp", "rb") as image:
  f = image.read()
  b = bytearray(f)

c=[(i >> j) & 1 for i in b for j in range(7, -1, -1)]

d=c[483:]
for i in range(0, 69):
    del d[i*(51):i*(51)+13]

e=[]
for i in range(int(len(d)/51)):
    e.append(d[i*(51):(i+1)*51])
print (e)
</code>```

At this point, the output was a list of lists. I then reversed the order of the lists with this code snippet:

```<code>g=[]
for g in reversed(e):
   print(g)
</code>```

After I reversed the order of the lists, they did not appear to be a list of lists anymore. This is my output:

```<code>[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
</code>```

I went ahead and tried to combine the lists using this:

```<code>g=[]
for g in reversed(e):
   reduce(lambda x,y: x+y, g)
   print(g)
</code>```

but it did not change my output.

Because they aren't lists anymore, I'm not sure how to combine them into one.

答:
In your first loop, you append to e and then print(e), showing you the list of lists.

In your second loop, you merely print each line of reversed(e), and throw away the reduction:

g=[]
for g in reversed(e):
   reduce(lambda x,y: x+y, g)
   print(g)
```

<p>You've fooled yourself with <code>g=[]</code> into thinking that you're reducing and assigning to <code>g</code>. In fact the code path that leads to the printing of <code>g</code> is just:</p>

<pre class="lang-py prettyprint-override"><code>for g in reversed(e):
   print(g)
</code>```

g is just your loop variable.

Body:
Okay, I have converted an image to 1's and 0's. I then changed the code so that it would output the 1's and 0's into a list of each row, this way I could reverse the rows to flip the image. Now I am trying to merge those lists back together. At first the output was a list of lists, and I knew how to combine those lists, but when I reversed the order of the lists, it was no longer a list of lists and what I thought would work to combine them didn't.

So here is the code I used to first convert the image and then remove the header and extra 0's that the program put into the code:

with open("monoT.bmp", "rb") as image:
  f = image.read()
  b = bytearray(f)

c=[(i >> j) & 1 for i in b for j in range(7, -1, -1)]

d=c[483:]
for i in range(0, 69):
    del d[i*(51):i*(51)+13]

e=[]
for i in range(int(len(d)/51)):
    e.append(d[i*(51):(i+1)*51])
print (e)

At this point, the output was a list of lists. I then reversed the order of the lists with this code snippet:

g=[]
for g in reversed(e):
   print(g)

After I reversed the order of the lists, they did not appear to be a list of lists anymore. This is my output:

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,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 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

I went ahead and tried to combine the lists using this:

g=[]
for g in reversed(e):
   reduce(lambda x,y: x+y, g)
   print(g)

but it did not change my output.

Because they aren't lists anymore, I'm not sure how to combine them into one.

Body:
In your first loop, you append to e and then print(e), showing you the list of lists.

In your second loop, you merely print each line of reversed(e), and throw away the reduction:

g=[]
for g in reversed(e):
   reduce(lambda x,y: x+y, g)
   print(g)

You've fooled yourself with g=[] into thinking that you're reducing and assigning to g. In fact the code path that leads to the printing of g is just:

for g in reversed(e):
   print(g)

g is just your loop variable.


问:
How easy is it to roll back a file that has been checked-in in TFS?
I've (apparently) checked-in (added) a file that shouldn't have been added to a branch. I need to revert this, but since then, 20 or so changesets have been added to the repository.

I'm used to working with Subversion, where it's only a few clicks and it's out. How easy is it in TFS?

答:
If it is added by mistake, you don't want to roll back.  Instead, you want to tf destroy (from the command line) that file in each of the branches.

TFS can be a bear to work with if you add a file, delete it, then re-add a new file with the same name.  It makes merging much more difficult.


问:
MSACCESS VBA: Add borders to Excel Sheet
The below does not work. How do I add borders? Thanks!</p>

```<code>            Set objApp = CreateObject("Excel.Application")
            objApp.Visible = True
            Set wb = objApp.Workbooks.Open("aFile.xls", True, False)
            objApp.Cells.Select
            objApp.Selection.Borders(xlDiagonalDown).LineStyle = xlNone
            objApp.Selection.Borders(xlDiagonalUp).LineStyle = xlNone
            With objApp.Selection.Borders(xlEdgeLeft)
                .LineStyle = xlContinuous
                .ColorIndex = 0
                .TintAndShade = 0
                .Weight = xlThin
            End With
            With objApp.Selection.Borders(xlEdgeTop)
                .LineStyle = xlContinuous
                .ColorIndex = 0
                .TintAndShade = 0
                .Weight = xlThin
            End With
            With objApp.Selection.Borders(xlEdgeBottom)
                .LineStyle = xlContinuous
                .ColorIndex = 0
                .TintAndShade = 0
                .Weight = xlThin
            End With
            With objApp.Selection.Borders(xlEdgeRight)
                .LineStyle = xlContinuous
                .ColorIndex = 0
                .TintAndShade = 0
                .Weight = xlThin
            End With
            With objApp.Selection.Borders(xlInsideVertical)
                .LineStyle = xlContinuous
                .ColorIndex = 0
                .TintAndShade = 0
                .Weight = xlThin
            End With
            With objApp.Selection.Borders(xlInsideHorizontal)
                .LineStyle = xlContinuous
                .ColorIndex = 0
                .TintAndShade = 0
                .Weight = xlThin
            End With

            Set objApp = Nothing
</code>```

答:
Get the workbook and worksheet as variables, then just set the borders for used range.</p>

```<code>Set objXLBook = objXLApp.Workbooks.Open(strXLSFile)
Set objXLSheet = objXLBook.Sheets("Name of Sheet")

objXLSheet.UsedRange.Borders.LineStyle = xlContinuous
</code>```

Body:
The below does not work. How do I add borders? Thanks!

            Set objApp = CreateObject("Excel.Application")
            objApp.Visible = True
            Set wb = objApp.Workbooks.Open("aFile.xls", True, False)
            objApp.Cells.Select
            objApp.Selection.Borders(xlDiagonalDown).LineStyle = xlNone
            objApp.Selection.Borders(xlDiagonalUp).LineStyle = xlNone
            With objApp.Selection.Borders(xlEdgeLeft)
                .LineStyle = xlContinuous
                .ColorIndex = 0
                .TintAndShade = 0
                .Weight = xlThin
            End With
            With objApp.Selection.Borders(xlEdgeTop)
                .LineStyle = xlContinuous
                .ColorIndex = 0
                .TintAndShade = 0
                .Weight = xlThin
            End With
            With objApp.Selection.Borders(xlEdgeBottom)
                .LineStyle = xlContinuous
                .ColorIndex = 0
                .TintAndShade = 0
                .Weight = xlThin
            End With
            With objApp.Selection.Borders(xlEdgeRight)
                .LineStyle = xlContinuous
                .ColorIndex = 0
                .TintAndShade = 0
                .Weight = xlThin
            End With
            With objApp.Selection.Borders(xlInsideVertical)
                .LineStyle = xlContinuous
                .ColorIndex = 0
                .TintAndShade = 0
                .Weight = xlThin
            End With
            With objApp.Selection.Borders(xlInsideHorizontal)
                .LineStyle = xlContinuous
                .ColorIndex = 0
                .TintAndShade = 0
                .Weight = xlThin
            End With

            Set objApp = Nothing

Body:
Get the workbook and worksheet as variables, then just set the borders for used range.

Set objXLBook = objXLApp.Workbooks.Open(strXLSFile)
Set objXLSheet = objXLBook.Sheets("Name of Sheet")

objXLSheet.UsedRange.Borders.LineStyle = xlContinuous


问:
Why is this python selenium example not working?
I recently needed selenium to do something with a website. So I did some research and found this guide on how to set up selenium with an example: https://dzone.com/articles/python-getting-started

They provided the following example code:

```<code>from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://www.ubuntu.com/')
</code>```

But instead of working it throws an error:

```<code>selenium.common.exceptions.WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary constructor, check it for details.
</code>```

Why is this example code not working?
Thanks, Ira.

答:
Run following commands and then try again

```<code>sudo apt-get install xvfb
sudo pip install pyvirtualdisplay
</code>```

and change your code like below

```<code>display = Display(visible=0, size=(1024, 768))
display.start()

browser = webdriver.Firefox()
</code>```

if none of these worked, try to set geckodriver path for firefox like this

```<code>options = Options()
options.add_argument("--window-size=1920,1080")

browser = webdriver.Firefox(executable_path='/usr/bin/geckodriver', options=options)
</code>```

Body:
I recently needed selenium to do something with a website. So I did some research and found this guide on how to set up selenium with an example: https://dzone.com/articles/python-getting-started

They provided the following example code:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://www.ubuntu.com/')

But instead of working it throws an error:

selenium.common.exceptions.WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary constructor, check it for details.

Why is this example code not working?
Thanks, Ira.

Body:
Run following commands and then try again

sudo apt-get install xvfb
sudo pip install pyvirtualdisplay

and change your code like below

display = Display(visible=0, size=(1024, 768))
display.start()

browser = webdriver.Firefox()

if none of these worked, try to set geckodriver path for firefox like this

options = Options()
options.add_argument("--window-size=1920,1080")

browser = webdriver.Firefox(executable_path='/usr/bin/geckodriver', options=options)


问:
How to evaluate a symbolic expression in different ways?
I have a list of symbolic expressions, like below:

```<code>import numpy as np
import sympy
s = sympy.Symbol('s')
x = [ s, s+1, 10*s**2, 5]
</code>```

After adding the elements by using "sum":

```<code>y = sum (x)
</code>```

I will get: 10*s**2 + 2*s + 6
I want to evaluate this expression for each of the elements of the list below:

```<code>s = [1, 2 , 3 , 4 , 5]
</code>```

I know that I can define a function like below:

```<code>def F (s):

    F = 10*s**2 + 2*s + 6
    return F
f_dis = [F(value )for value in s]
</code>```

and it will give the result I'm looking for: [18, 50, 102, 174, 266]
However, my problem is that I have to define the F and write the expression in my code. Is there any other way that I can evaluate the sum (x) without writing the F = 10*s**2 + 2*s + 6 inside my code?
I can not copy and paste the result of sum (x) inside my code.

答:
Or compute the sum once and use it in a lambda:</p>

```<code>>>> x = [ s, s+1, 10*s**2, 5]
>>> sumx = sum(x)
>>> do = lambda si: sumx.subs(s, si)
>>> list(map(do, range(1, 6)))
[18, 50, 102, 174, 266]
</code>```

Body:
I have a list of symbolic expressions, like below:

import numpy as np
import sympy
s = sympy.Symbol('s')
x = [ s, s+1, 10*s**2, 5]

After adding the elements by using "sum":

y = sum (x)

I will get: 10*s**2 + 2*s + 6
I want to evaluate this expression for each of the elements of the list below:

s = [1, 2 , 3 , 4 , 5]

I know that I can define a function like below:

def F (s):

    F = 10*s**2 + 2*s + 6
    return F
f_dis = [F(value )for value in s]

and it will give the result I'm looking for: [18, 50, 102, 174, 266]
However, my problem is that I have to define the F and write the expression in my code. Is there any other way that I can evaluate the sum (x) without writing the F = 10*s**2 + 2*s + 6 inside my code?
I can not copy and paste the result of sum (x) inside my code.

Body:
Or compute the sum once and use it in a lambda:

>>> x = [ s, s+1, 10*s**2, 5]
>>> sumx = sum(x)
>>> do = lambda si: sumx.subs(s, si)
>>> list(map(do, range(1, 6)))
[18, 50, 102, 174, 266]


答:
Reduce is a loop itself:

```<code>g.reverse() # Reverse the list of lists
g = reduce(lambda x, y: x + y, g) # combine them all
</code>```

though the fastest solution (faster than numpy) is iconcat:

```<code>import operator
from functools import reduce
g = [[1, 0, 1], [1, 1, 1], [0, 0, 1]]
g.reverse()
g = reduce(operator.iconcat, g, [])
</code>```

Note: This solution appends the lists in reverse order (the lists themselves are not reversed). If you need to reverse the lists individually as well than you should reverse them like this:

```<code>g = [list(reversed(x)) for x in reversed(g)]
</code>```

Reference: How to make a flat list out of list of lists

Title: Merging the output into one list (NOT merging a list of lists)

Body:
Reduce is a loop itself:

g.reverse() # Reverse the list of lists
g = reduce(lambda x, y: x + y, g) # combine them all

though the fastest solution (faster than numpy) is iconcat:

import operator
from functools import reduce
g = [[1, 0, 1], [1, 1, 1], [0, 0, 1]]
g.reverse()
g = reduce(operator.iconcat, g, [])

Note: This solution appends the lists in reverse order (the lists themselves are not reversed). If you need to reverse the lists individually as well than you should reverse them like this:

g = [list(reversed(x)) for x in reversed(g)]

Reference: How to make a flat list out of list of lists


问:
Apply style with setTimeout()
I created the next code:

  setTimeout(function () {
        var dot = document.querySelectorAll('.dot');
        for (var i=0;i<dot.length;i++) {
            dot[i].style.backgroundColor = 'blue';
        }
    },2000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code> .container{
        display: flex;
        justify-content: space-around;
    }
   .dot{
       background-color: red;
       width: 20px;
       height: 20px;
       border-radius: 50%;
   }</code>```

```

This code apply background-color for each dot at the same time after 2 seconds, but i want to apply the style for each dot separately. Fo example: after 2 seconds to apply the style for first dot, then after 2 seconds to apply the style for second dot, and so on. Who has a solution?

答:
You could try using the long way: ```
    setTimeout(function () {
        var dot = document.querySelectorAll('.dot');</p>

```    setTimeout(function () {
        for (var i=0;i<dot.length;i++) {
        dot[0].style.backgroundColor = 'blue';
        }

        setTimeout(function () {
            for (var i=0;i<dot.length;i++) {
            dot[1].style.backgroundColor = 'blue';
            }
        },2000);

    },2000);
},2000);
</script>```
</code>```

But i would suggest (i * 2000)

Title: Apply style with setTimeout()

Body:
I created the next code:

  setTimeout(function () {
        var dot = document.querySelectorAll('.dot');
        for (var i=0;i<dot.length;i++) {
            dot[i].style.backgroundColor = 'blue';
        }
    },2000);

 .container{
        display: flex;
        justify-content: space-around;
    }
   .dot{
       background-color: red;
       width: 20px;
       height: 20px;
       border-radius: 50%;
   }

This code apply background-color for each dot at the same time after 2 seconds, but i want to apply the style for each dot separately. Fo example: after 2 seconds to apply the style for first dot, then after 2 seconds to apply the style for second dot, and so on. Who has a solution?

Body:
You could try using the long way: ```
    setTimeout(function () {
        var dot = document.querySelectorAll('.dot');</p>

<pre><code>    setTimeout(function () {
        for (var i=0;i<dot.length;i++) {
        dot[0].style.backgroundColor = 'blue';
        }

        setTimeout(function () {
            for (var i=0;i<dot.length;i++) {
            dot[1].style.backgroundColor = 'blue';
            }
        },2000);

    },2000);
},2000);
</script>```

But i would suggest (i * 2000)


问:
AES Encryption- large files
I am doing AES encryption using EVP interface of OpenSSL in C language in the 128/192/256 cbc modes.
I found a nice example in stackoverflow with which I have started programming.

What I would like to know is:

What is the default padding used while encryption?

What happens if I have large data. Do I have to code to divide it into data blocks of 128 bits? or does EVP interface takes care of it?

What should be the size of the IV for 128bit, 192bit and 256bit cbc modes(where only the key lengths are 128, 192, 256 respectively and the block size is always 128)

thanks

答:
There is no default padding for encryption. There are several padding schemes. For EVP there is an encrypt final method that takes an incomplete block and adds padding (default PKCS padding) and encrypts it.

EVP will take care of it.

Size of the IV vector when CBC mode is used is the same size as the block size.

Title: AES Encryption- large files


问:
How to print a column header that satisfies row and column conditions
I have two columns, one with length and one with weight (columns D and F). I am trying to print for each combination of the two, a value that corresponds to the national percentile (headers on columns M through U).

I need to first match my length (column D) with one in column L. From there, I need to go across the row for the corresponding L value that matches the closest to my weight (column F). Then, I need to print that value's column header in column H, titled "Percentile".

I've included a screen shot of the beginning values but the possible lengths in column L extend to 104 and I have 4432 possible combinations of length and weight (columns D and F).

How can I go about doing this? I imagine it has something to do with index or maybe a vlookup?

I would expect the first two values to be 97 and 25. I'm rounding up in each case.

答:
Well.... first of all this will be volatile but you could use:

```<code>=INDEX($M$1:$U$1,,MATCH(MIN(ABS(INDIRECT("M"&MATCH(D2,$L$1:$L$61,0)&":U"&MATCH(D2,$L$1:$L$61,0))-F2)),ABS(INDIRECT("M"&MATCH(D2,$L$1:$L$61,0)&":U"&MATCH(D2,$L$1:$L$61,0))-F2),0))
</code>```

Enter through CtrlShiftEnter

Outcome will be 95 and 10 instead of 97 and 25 since that is really the closest matches!

Body:
Well.... first of all this will be volatile but you could use:

=INDEX($M$1:$U$1,,MATCH(MIN(ABS(INDIRECT("M"&MATCH(D2,$L$1:$L$61,0)&":U"&MATCH(D2,$L$1:$L$61,0))-F2)),ABS(INDIRECT("M"&MATCH(D2,$L$1:$L$61,0)&":U"&MATCH(D2,$L$1:$L$61,0))-F2),0))

Enter through CtrlShiftEnter

Outcome will be 95 and 10 instead of 97 and 25 since that is really the closest matches!