问:
DB & context too many errors
I am running below "go" code and getting lots of error :

```<code>package main

import (
    "database/sql"
    "log"
    "github.com/get-ion/ion"
    "github.com/get-ion/ion/context"
    "github.com/get-ion/ion/view"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    app := ion.New()
    app.RegisterView(view.HTML("./templates", ".html"))

    db, err := sql.Open("mysql", "root:password@/database?charset=utf8&parseTime=true&loc=Local")
    if err != nil {
        log.Fatalln(err)
        panic("There was an error handling mysql connection!")
    }
    defer db.Close()

    allRoutes := app.Party("/", logThisMiddleware)
    {
        allRoutes.Get("/", homePage(db))
    }
}

func logThisMiddleware(ctx context.Context) {
    ctx.Application().Logger().Infof("Path: %s | IP: %s\n", ctx.Path(), ctx.RemoteAddr())
    ctx.Next()
}

func homePage(db *sql.DB) {
    func(ctx context.Context) {
       var (
            id             int
            title          string
            featured_image string
            created_at     string
        )
        rows, err := db.Query("SELECT id, title, featured_image, created_at from blogs order by crated_at desc limit 0,5")
        if err != nil {
            ctx.Application().Logger().Fatalf("MySQL Error fetching row %s\n", err)
        }
        defer rows.Close()
        blogData := map[int]map[int]string{}
        for rows.Next() {
            err := rows.Scan(&id, &title, &featured_image, &created_at)
            if err != nil {
                ctx.Application().Logger().Fatalf("Error while fetching row from blog: %s\n", err)
            }
            blogData[id][0] = title
            blogData[id][1] = featured_image
            blogData[id][2] = created_at
        }
        err = rows.Err()
        if err != nil {
            ctx.Application().Logger().Fatalf("Error while scanning Row : %s\n", err)
        }
        ctx.ViewData("blog", blogData)
        ctx.View("homepage.html")
    }
}
</code>```

Errors are :-

```<code>./main.go:40: homePage(db) used as value
./main.go:50: func literal evaluated but not used
</code>```

All the values are fetched as mentioned in : http://go-database-sql.org/retrieving.html , Still not sure why undefined variable issue. I don't think, these variables are required to be created, but if in case it has to be , please let me know.

Thanks

答:
./main.go:40: homePage(db) used as value

homePage is void function. So you can't use it in function arguments.

./main.go:50: func literal evaluated but not used

```<code>func homePage(db *sql.DB) {
    func(ctx context.Context) {
        ...
    }
    return ""
}
</code>```

This is broken syntax. I suggest you to go https://tour.golang.org/

./main.go:79: too many arguments to return
      have (string)
      want ()

As I said in above, homePage is void function. So you can't use return with value. Below is code which I could suppose your code should be.

```<code>package main

import (
    "database/sql"
    "log"

    "github.com/get-ion/ion"
    "github.com/get-ion/ion/context"
    "github.com/get-ion/ion/view"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    app := ion.New()
    app.RegisterView(view.HTML("./templates", ".html"))

    db, err := sql.Open("mysql", "root:password@/database?charset=utf8&parseTime=true&loc=Local")
    if err != nil {
        log.Fatalln(err)
        panic("There was an error handling mysql connection!")
    }
    defer db.Close()

    allRoutes := app.Party("/", logThisMiddleware)
    {
        allRoutes.Get("/", homePage(db))
    }

    //app.Run(ion.Addr(":8080"))
}

func logThisMiddleware(ctx context.Context) {
    ctx.Application().Logger().Infof("Path: %s | IP: %s\n", ctx.Path(), ctx.RemoteAddr())
    ctx.Next()
}

func homePage(db *sql.DB) context.Handler {
    return func(ctx context.Context) {
        var (
            id             int
            title          string
            featured_image string
            created_at     string
        )
        rows, err := db.Query("SELECT id, title, featured_image, created_at from blogs order by crated_at desc limit 0,5")
        if err != nil {
            ctx.Application().Logger().Fatalf("MySQL Error fetching row %s\n", err)
        }
        defer rows.Close()
        blogData := map[int]map[int]string{}
        for rows.Next() {
            err := rows.Scan(&id, &title, &featured_image, &created_at)
            if err != nil {
                ctx.Application().Logger().Fatalf("Error while fetching row from blog: %s\n", err)
            }
            blogData[id][0] = title
            blogData[id][1] = featured_image
            blogData[id][2] = created_at
        }
        err = rows.Err()
        if err != nil {
            ctx.Application().Logger().Fatalf("Error while scanning Row : %s\n", err)
        }
        ctx.ViewData("blog", blogData)
        ctx.View("homepage.html")
    }
}
</code>```

Title: DB & context too many errors

Body:
I am running below "go" code and getting lots of error :

package main

import (
    "database/sql"
    "log"
    "github.com/get-ion/ion"
    "github.com/get-ion/ion/context"
    "github.com/get-ion/ion/view"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    app := ion.New()
    app.RegisterView(view.HTML("./templates", ".html"))

    db, err := sql.Open("mysql", "root:password@/database?charset=utf8&parseTime=true&loc=Local")
    if err != nil {
        log.Fatalln(err)
        panic("There was an error handling mysql connection!")
    }
    defer db.Close()

    allRoutes := app.Party("/", logThisMiddleware)
    {
        allRoutes.Get("/", homePage(db))
    }
}

func logThisMiddleware(ctx context.Context) {
    ctx.Application().Logger().Infof("Path: %s | IP: %s\n", ctx.Path(), ctx.RemoteAddr())
    ctx.Next()
}

func homePage(db *sql.DB) {
    func(ctx context.Context) {
       var (
            id             int
            title          string
            featured_image string
            created_at     string
        )
        rows, err := db.Query("SELECT id, title, featured_image, created_at from blogs order by crated_at desc limit 0,5")
        if err != nil {
            ctx.Application().Logger().Fatalf("MySQL Error fetching row %s\n", err)
        }
        defer rows.Close()
        blogData := map[int]map[int]string{}
        for rows.Next() {
            err := rows.Scan(&id, &title, &featured_image, &created_at)
            if err != nil {
                ctx.Application().Logger().Fatalf("Error while fetching row from blog: %s\n", err)
            }
            blogData[id][0] = title
            blogData[id][1] = featured_image
            blogData[id][2] = created_at
        }
        err = rows.Err()
        if err != nil {
            ctx.Application().Logger().Fatalf("Error while scanning Row : %s\n", err)
        }
        ctx.ViewData("blog", blogData)
        ctx.View("homepage.html")
    }
}

Errors are :-

./main.go:40: homePage(db) used as value
./main.go:50: func literal evaluated but not used

All the values are fetched as mentioned in : http://go-database-sql.org/retrieving.html , Still not sure why undefined variable issue. I don't think, these variables are required to be created, but if in case it has to be , please let me know.

Thanks

Body:
./main.go:40: homePage(db) used as value

homePage is void function. So you can't use it in function arguments.

./main.go:50: func literal evaluated but not used

func homePage(db *sql.DB) {
    func(ctx context.Context) {
        ...
    }
    return ""
}

This is broken syntax. I suggest you to go https://tour.golang.org/

./main.go:79: too many arguments to return
      have (string)
      want ()

As I said in above, homePage is void function. So you can't use return with value. Below is code which I could suppose your code should be.

package main

import (
    "database/sql"
    "log"

    "github.com/get-ion/ion"
    "github.com/get-ion/ion/context"
    "github.com/get-ion/ion/view"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    app := ion.New()
    app.RegisterView(view.HTML("./templates", ".html"))

    db, err := sql.Open("mysql", "root:password@/database?charset=utf8&parseTime=true&loc=Local")
    if err != nil {
        log.Fatalln(err)
        panic("There was an error handling mysql connection!")
    }
    defer db.Close()

    allRoutes := app.Party("/", logThisMiddleware)
    {
        allRoutes.Get("/", homePage(db))
    }

    //app.Run(ion.Addr(":8080"))
}

func logThisMiddleware(ctx context.Context) {
    ctx.Application().Logger().Infof("Path: %s | IP: %s\n", ctx.Path(), ctx.RemoteAddr())
    ctx.Next()
}

func homePage(db *sql.DB) context.Handler {
    return func(ctx context.Context) {
        var (
            id             int
            title          string
            featured_image string
            created_at     string
        )
        rows, err := db.Query("SELECT id, title, featured_image, created_at from blogs order by crated_at desc limit 0,5")
        if err != nil {
            ctx.Application().Logger().Fatalf("MySQL Error fetching row %s\n", err)
        }
        defer rows.Close()
        blogData := map[int]map[int]string{}
        for rows.Next() {
            err := rows.Scan(&id, &title, &featured_image, &created_at)
            if err != nil {
                ctx.Application().Logger().Fatalf("Error while fetching row from blog: %s\n", err)
            }
            blogData[id][0] = title
            blogData[id][1] = featured_image
            blogData[id][2] = created_at
        }
        err = rows.Err()
        if err != nil {
            ctx.Application().Logger().Fatalf("Error while scanning Row : %s\n", err)
        }
        ctx.ViewData("blog", blogData)
        ctx.View("homepage.html")
    }
}


来源: stackexchange

问:
Why this line do nothing
I am experimenting with some trigonometric functions, the code compile good, i want see a square moving on the 360 degrees, but when i run the code i see the square only move in the x-axis, everything work fine except a line on my function.

```<code>void mvdr(int* x, int* y, float d, float sp)
{
    if(d != 0)
        d = (d / 360.0) / 6.283185307179586;

    *x += cos(d)*sp;
    *y += sin(d)*sp; // here's the error
}
</code>```

I saw in gdb: y doesn't change.

```<code>(gdb) n
11       *y += sin(d)*sp; // here's the error
(gdb) p d
$4 = 0.000442097051
(gdb) p sin(d)*sp
$5 = 6.44245094e+09
(gdb) p *y
$6 = 256
(gdb) n
12       }
(gdb) p *y
$7 = 256
</code>```

I can't understand what is happening or if i did something wrong, i hope you can help me.

答:
To convert degrees to radians you should:

```<code>d = (d / 360.0) * 6.283185307179586;
</code>```

Your conversion function results in very small values which for sin() may not change the integer value of y and for cos() result in larger values for x

ContentLicense: CC BY-SA 3.0

Title: Why this line do nothing

Body:
I am experimenting with some trigonometric functions, the code compile good, i want see a square moving on the 360 degrees, but when i run the code i see the square only move in the x-axis, everything work fine except a line on my function.

void mvdr(int* x, int* y, float d, float sp)
{
    if(d != 0)
        d = (d / 360.0) / 6.283185307179586;

    *x += cos(d)*sp;
    *y += sin(d)*sp; // here's the error
}

I saw in gdb: y doesn't change.

(gdb) n
11       *y += sin(d)*sp; // here's the error
(gdb) p d
$4 = 0.000442097051
(gdb) p sin(d)*sp
$5 = 6.44245094e+09
(gdb) p *y
$6 = 256
(gdb) n
12       }
(gdb) p *y
$7 = 256

I can't understand what is happening or if i did something wrong, i hope you can help me.

Body:
To convert degrees to radians you should:

d = (d / 360.0) * 6.283185307179586;

Your conversion function results in very small values which for sin() may not change the integer value of y and for cos() result in larger values for x


问:
How can I access an object's property in Ruby
My user object has a boolean property that I want to check as a user logs in.

This is what I'm trying to do, but I am getting a 500 error:

```<code>user = User.find_by_email(params['email'])
if user.is_mentor
    #do something
end
</code>```

答:
You just have to check that the user exists first:

```<code>if user && user.is_mentor?
    # do something
end
</code>```

user will be nil and false if Rails didn't find the user.

Body:
My user object has a boolean property that I want to check as a user logs in.

This is what I'm trying to do, but I am getting a 500 error:

user = User.find_by_email(params['email'])
if user.is_mentor
    #do something
end

Body:
You just have to check that the user exists first:

if user && user.is_mentor?
    # do something
end

user will be nil and false if Rails didn't find the user.


问:
How can I import bs4 from Beautiful Soup in Python3 on OSX 10.12.5?
I'm trying to fix what seems like a common problem with importing a module in Python 3. I'm running OS X 10.12.5 and have Python 3 installed on my MacBook Air and am using Sublime Text to edit and run my code.

When I try this import:

```<code>from bs4 import BeautifulSoup
</code>```

...I get this error:

```<code>Traceback (most recent call last):
  File "/Users/<myname>/Python/code-python3/Pgm#001", line 5, in <module>
    from bs4 import BeautifulSoup
ImportError: No module named 'bs4'
</code>```

I successfully installed with this PIP and on every re-install I see this:

```<code>$ pip install beautifulsoup4
Requirement already satisfied: beautifulsoup4 in ./anaconda/lib/python3.5/site-packages
</code>```

I've tried qualifying the location with things like:

```<code>from ./anaconda/lib/python3.5/site-packages/bs4 import BeautifulSoup
</code>```

...but invariably get a variety of syntax errors; usually on the first '/'.

I am not using a virtual environment but do plan to read up on that approach as these kind of configuration and setup errors are big time wasters.

When I try to run this right in python3 I get slightly different errors:

```<code>>>> from bs4 import BeautifulSoup
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/<myname>/anaconda/lib/python3.5/site-packages/bs4/__init__.py", line 30, in <module>
    from .builder import builder_registry, ParserRejectedMarkup
  File "/Users/<myname>/anaconda/lib/python3.5/site-packages/bs4/builder/__init__.py", line 314, in <module>
    from . import _html5lib
  File "/Users/<myname>/anaconda/lib/python3.5/site-packages/bs4/builder/_html5lib.py", line 70, in <module>
    class TreeBuilderForHtml5lib(html5lib.treebuilders._base.TreeBuilder):
AttributeError: module 'html5lib.treebuilders' has no attribute '_base'
</code>```

Any tips about where the obvious answer exists that I am still missing would be greatly appreciated. I've seen a lot of things about PATH and PYTHONPATH in similar questions but had no success with any of these solutions either.

答:
Yes, I'm not a fan of anaconda but looks like the path is being pointed to:

"/Users//anaconda/lib/python3.5/site-packages"

... and for the sake of keeping things as clean as possible (this being a good example/reason why you'll see people say to use env for your python projects)

Lets google here! Here's how to remove anaconda:

```<code>conda install anaconda-clean #first the configs
anaconda-clean --yes
rm -rf ~/anaconda.* #then conda, the ".*" is regex to cover any version
</code>```

The check your bash_profile and/or bashrc; and here you can set your Python path. Make sure it not pointing to anaconda

if you run

```<code>ls -lh `which python # orpython3
</code>```

You'll get the path of which is the one you'll be setting as the path.

Body:
I'm trying to fix what seems like a common problem with importing a module in Python 3. I'm running OS X 10.12.5 and have Python 3 installed on my MacBook Air and am using Sublime Text to edit and run my code.

When I try this import:

from bs4 import BeautifulSoup

...I get this error:

Traceback (most recent call last):
  File "/Users/<myname>/Python/code-python3/Pgm#001", line 5, in <module>
    from bs4 import BeautifulSoup
ImportError: No module named 'bs4'

I successfully installed with this PIP and on every re-install I see this:

$ pip install beautifulsoup4
Requirement already satisfied: beautifulsoup4 in ./anaconda/lib/python3.5/site-packages

I've tried qualifying the location with things like:

from ./anaconda/lib/python3.5/site-packages/bs4 import BeautifulSoup

...but invariably get a variety of syntax errors; usually on the first '/'.

I am not using a virtual environment but do plan to read up on that approach as these kind of configuration and setup errors are big time wasters.

When I try to run this right in python3 I get slightly different errors:

>>> from bs4 import BeautifulSoup
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/<myname>/anaconda/lib/python3.5/site-packages/bs4/__init__.py", line 30, in <module>
    from .builder import builder_registry, ParserRejectedMarkup
  File "/Users/<myname>/anaconda/lib/python3.5/site-packages/bs4/builder/__init__.py", line 314, in <module>
    from . import _html5lib
  File "/Users/<myname>/anaconda/lib/python3.5/site-packages/bs4/builder/_html5lib.py", line 70, in <module>
    class TreeBuilderForHtml5lib(html5lib.treebuilders._base.TreeBuilder):
AttributeError: module 'html5lib.treebuilders' has no attribute '_base'

Any tips about where the obvious answer exists that I am still missing would be greatly appreciated. I've seen a lot of things about PATH and PYTHONPATH in similar questions but had no success with any of these solutions either.

Body:
Yes, I'm not a fan of anaconda but looks like the path is being pointed to:

"/Users//anaconda/lib/python3.5/site-packages"

... and for the sake of keeping things as clean as possible (this being a good example/reason why you'll see people say to use env for your python projects)

Lets google here! Here's how to remove anaconda:

conda install anaconda-clean #first the configs
anaconda-clean --yes
rm -rf ~/anaconda.* #then conda, the ".*" is regex to cover any version

The check your bash_profile and/or bashrc; and here you can set your Python path. Make sure it not pointing to anaconda

if you run

ls -lh `which python # orpython3

You'll get the path of which is the one you'll be setting as the path.


问:
Javascript innerHTML method returning wrong value
I'm looking for some support with this math's project I'm doing. Basically I've created four boxes, and populated one with the correct answer. When I click on the correct answer, the if statement doesn't run; it always shows as wrong.

I include a snippet, if someone can see something glaringly wrong then I'd appreciate a response.

I'm only trying it with box 1 to see if it works, and the correct answer does populate in 1 of the 4 boxes, however it always says it's the wrong answer, even when correct answer is in box1.

```<code>document.getElementById("box1").onclick = function() {
  if (playing == true) {
    if (this.innerHTML == correctAnswer) {
      score++;
      document.getElementById("scorevalue").innerHTML = score;
      hide("wrong");
      show("correct");
      setTimeout(function() {
        hide("correct");
      }, 1000);
    } else {
      hide("correct");
      show("wrong");
      setTimeout(function() {
        hide("wrong");
      }, 1000);
    }
  }
}
</code>```

答:
This is most likely related to your HTML, and the way you have setup your tags. For example, if box1 is a div, then if your code looks like this:

```<code><div id="box1">
    answer
</div>
</code>```

Then in some explorers, specifically Chrome and FireFox, it considers linebreak as empty space.

So, if var correctAnswer = "answer";

and you compare correctAnswer with box1.innerHTML like so:

```<code>if (correctAnswer == box1.innerHTML)
</code>```

Then you will always get false returned.

In order to fix the issue, change your HTML like so:

```<code><div id="box1">answer</div>
</code>```

Basically remove the linebreaks.

Everything else seems to be fine.

Body:
I'm looking for some support with this math's project I'm doing. Basically I've created four boxes, and populated one with the correct answer. When I click on the correct answer, the if statement doesn't run; it always shows as wrong.

I include a snippet, if someone can see something glaringly wrong then I'd appreciate a response.

I'm only trying it with box 1 to see if it works, and the correct answer does populate in 1 of the 4 boxes, however it always says it's the wrong answer, even when correct answer is in box1.

document.getElementById("box1").onclick = function() {
  if (playing == true) {
    if (this.innerHTML == correctAnswer) {
      score++;
      document.getElementById("scorevalue").innerHTML = score;
      hide("wrong");
      show("correct");
      setTimeout(function() {
        hide("correct");
      }, 1000);
    } else {
      hide("correct");
      show("wrong");
      setTimeout(function() {
        hide("wrong");
      }, 1000);
    }
  }
}

Body:
This is most likely related to your HTML, and the way you have setup your tags. For example, if box1 is a div, then if your code looks like this:

<div id="box1">
    answer
</div>

Then in some explorers, specifically Chrome and FireFox, it considers linebreak as empty space.

So, if var correctAnswer = "answer";

and you compare correctAnswer with box1.innerHTML like so:

if (correctAnswer == box1.innerHTML)

Then you will always get false returned.

In order to fix the issue, change your HTML like so:

<div id="box1">answer</div>

Basically remove the linebreaks.

Everything else seems to be fine.


问:
How to load a sublevel JSON file into DynamoDB using Boto3?
I got problems trying to load my JSON file into AWS dynamoDB with Python and Boto3, when this file have a sublevel json.

For exaple i have this code bellow:

```<code>from __future__ import print_function # Python 2/3 compatibility
import boto3

dynamodb = boto3.resource('dynamodb', region_name='sa-east-1', aws_access_key_id='AWS ACCESS KEY', aws_secret_access_key='AWS SECRET KEY')
table = dynamodb.create_table(
    TableName='Movies',
    KeySchema=[
        {
            'AttributeName': 'year',
            'KeyType': 'HASH'  #Partition key
        },
        {
            'AttributeName': 'title',
            'KeyType': 'RANGE'  #Sort key
        }
    ],
    AttributeDefinitions=[
        {
            'AttributeName': 'year',
            'AttributeType': 'N'
        },
        {
            'AttributeName': 'title',
            'AttributeType': 'S'
        },

    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 10,
        'WriteCapacityUnits': 10
    }
)

print("Table status:", table.table_status)
</code>```

In this layout i create a table in AWS dynamoDB, but only for JSON on one level structure, like:

```<code>[
    {
        "year": 2013,
        "title": "Rush"
    }
]
</code>```

But if i want to put a JSON file with sublevel? How i have to create this table with Boto3? And how to input the file? like this:

```<code>[
    {
        "year": 2013,
        "title": "Rush",
        "info": {
            "directors": ["Ron Howard"],
            "release_date": "2013-09-02T00:00:00Z",
            "rating": 8.3,
            "genres": [
                "Action",
                "Biography",
                "Drama",
                "Sport"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BMTQyMDE0MTY0OV5BMl5BanBnXkFtZTcwMjI2OTI0OQ@@._V1_SX400_.jpg",
            "plot": "A re-creation of the merciless 1970s rivalry between Formula One rivals James Hunt and Niki Lauda.",
            "rank": 2,
            "running_time_secs": 7380,
            "actors": [
                "Daniel Bruhl",
                "Chris Hemsworth",
                "Olivia Wilde"
            ]
        }
    }
]
</code>```

I read Boto3 Docs and search some tutorials on the internet, but I can not find how to do this. It should be simple, I know I must have a way to do this, but I can not get it yet. Someone have some tip for me?

答:
Actually i have made a simple concept mistake. To DynamoDB, when you are creating a table, you don't need to declare every attribute of the table. In this phase, you just need to say who will be the Partition Key and the Sort Key (if it have one). If the items you imputing have more attributes, u can declare on put_item() function, like:</p>

```<code>from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal

dynamodb = boto3.resource('dynamodb', region_name='sa-east-1', aws_access_key_id='AWS ACCESS KEY', aws_secret_access_key='AWS SECRET KEY')

table = dynamodb.Table('Movies')

title = "The Big New Movie"
year = 2015

response = table.put_item(
   Item={
        'year': year,
        'title': title,
        'info': {
            'plot':"Nothing happens at all.",
            'rating': decimal.Decimal(0)
        }
    }
)
</code>```

Body:
I got problems trying to load my JSON file into AWS dynamoDB with Python and Boto3, when this file have a sublevel json.

For exaple i have this code bellow:

from __future__ import print_function # Python 2/3 compatibility
import boto3

dynamodb = boto3.resource('dynamodb', region_name='sa-east-1', aws_access_key_id='AWS ACCESS KEY', aws_secret_access_key='AWS SECRET KEY')
table = dynamodb.create_table(
    TableName='Movies',
    KeySchema=[
        {
            'AttributeName': 'year',
            'KeyType': 'HASH'  #Partition key
        },
        {
            'AttributeName': 'title',
            'KeyType': 'RANGE'  #Sort key
        }
    ],
    AttributeDefinitions=[
        {
            'AttributeName': 'year',
            'AttributeType': 'N'
        },
        {
            'AttributeName': 'title',
            'AttributeType': 'S'
        },

    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 10,
        'WriteCapacityUnits': 10
    }
)

print("Table status:", table.table_status)

In this layout i create a table in AWS dynamoDB, but only for JSON on one level structure, like:

[
    {
        "year": 2013,
        "title": "Rush"
    }
]

But if i want to put a JSON file with sublevel? How i have to create this table with Boto3? And how to input the file? like this:

[
    {
        "year": 2013,
        "title": "Rush",
        "info": {
            "directors": ["Ron Howard"],
            "release_date": "2013-09-02T00:00:00Z",
            "rating": 8.3,
            "genres": [
                "Action",
                "Biography",
                "Drama",
                "Sport"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BMTQyMDE0MTY0OV5BMl5BanBnXkFtZTcwMjI2OTI0OQ@@._V1_SX400_.jpg",
            "plot": "A re-creation of the merciless 1970s rivalry between Formula One rivals James Hunt and Niki Lauda.",
            "rank": 2,
            "running_time_secs": 7380,
            "actors": [
                "Daniel Bruhl",
                "Chris Hemsworth",
                "Olivia Wilde"
            ]
        }
    }
]

I read Boto3 Docs and search some tutorials on the internet, but I can not find how to do this. It should be simple, I know I must have a way to do this, but I can not get it yet. Someone have some tip for me?

Body:
Actually i have made a simple concept mistake. To DynamoDB, when you are creating a table, you don't need to declare every attribute of the table. In this phase, you just need to say who will be the Partition Key and the Sort Key (if it have one). If the items you imputing have more attributes, u can declare on put_item() function, like:

from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal

dynamodb = boto3.resource('dynamodb', region_name='sa-east-1', aws_access_key_id='AWS ACCESS KEY', aws_secret_access_key='AWS SECRET KEY')

table = dynamodb.Table('Movies')

title = "The Big New Movie"
year = 2015

response = table.put_item(
   Item={
        'year': year,
        'title': title,
        'info': {
            'plot':"Nothing happens at all.",
            'rating': decimal.Decimal(0)
        }
    }
)


问:
How can you use a spring form tag to assign an html value to a variable using jquery/javascript?
I have a drag and drop UI. Its like a bucket list. What I have done is I have seperated the forms and the UI html for easier data manipulation. I have an empty form like this: (Take note that I am using spring form tags "form:")

```<code><form:form method="POST" id="sampleForm" commandName="sampleForm" modelAttribute="sampleForm" class="navbar-form navbar-center">
    <table id="formToBeSaved">
    </table>
</form:form>
</code>```

And then I have a script that is triggered whenever my other sortable receives an item. Sample below:

```<code>$("#sortable2").sortable({
        connectWith : "#sortable2 ul",
        scroll: false,
        receive: function(event,ui) {

        var saveElement = '<tr id="saveRow['+statusCounter+']"><td><form:input type="hidden" '+
                'path="sampleFormModel['+statusCounter+']." class="form-control" '+
                'id="name['+statusCounter+'].sampleForm" value="'+ someValue +'"></form:input></td></tr>'

                console.log(saveElement);

                $("#formToBeSaved").append(saveElement);

                statusCounter = statusCounter + 1;

                console.log(statusCounter);
            };

        },
</code>```

Now the problem is, whenever I submit the form thru ajax an error occurs. It seems that the system does not recognize my < form:input > tag (since I am using spring) because I've just assigned it as a string into a variable. Is there a way to fix this? Thanks stackoverflow community!

答:
You are using Spring XML templates, but the web browser can only work with HTML. This works when you are declaring your code in JSP files because Sprint will parse them and transform them to HTML.

So instead of manually adding JSP to the document, you should edit your JSP files in a way they generate the JSP you expect. In this case, you could use <c:forEach> to generate each
. This answer could help you to do that.

If you only have access to the datas required by these
 dynamically, I do not know Sprint enough to help you. Maybe you could find some resources on this question.

Body:
I have a drag and drop UI. Its like a bucket list. What I have done is I have seperated the forms and the UI html for easier data manipulation. I have an empty form like this: (Take note that I am using spring form tags "form:")

<form:form method="POST" id="sampleForm" commandName="sampleForm" modelAttribute="sampleForm" class="navbar-form navbar-center">

</form:form>

And then I have a script that is triggered whenever my other sortable receives an item. Sample below:

$("#sortable2").sortable({
        connectWith : "#sortable2 ul",
        scroll: false,
        receive: function(event,ui) {

        var saveElement = '
<form:input type="hidden" '+
                'path="sampleFormModel['+statusCounter+']." class="form-control" '+
                'id="name['+statusCounter+'].sampleForm" value="'+ someValue +'"></form:input>
'

                console.log(saveElement);

                $("#formToBeSaved").append(saveElement);

                statusCounter = statusCounter + 1;

                console.log(statusCounter);
            };

        },

Now the problem is, whenever I submit the form thru ajax an error occurs. It seems that the system does not recognize my < form:input > tag (since I am using spring) because I've just assigned it as a string into a variable. Is there a way to fix this? Thanks stackoverflow community!

Body:
You are using Spring XML templates, but the web browser can only work with HTML. This works when you are declaring your code in JSP files because Sprint will parse them and transform them to HTML.

So instead of manually adding JSP to the document, you should edit your JSP files in a way they generate the JSP you expect. In this case, you could use <c:forEach> to generate each <tr>. This answer could help you to do that.

If you only have access to the datas required by these <tr> dynamically, I do not know Sprint enough to help you. Maybe you could find some resources on this question.


问:
Stop httpd, apache2
When I stop httpd and apache2 localhost still shows "It works!". Why ? I want reinstall apache2, how to completely remove it ? (I done it port uninstall php5 and apache2)</p>

答:
Try this cd /usr/local/apache2/bin (your apache install fodler)then when you enter apache bin folder run ./apachectl stop
Then run this sudo apt-get purge apache2 apache2-utils apache2.2-bin apache2-common
It all depends how the apache was installed, it is possible that httpd was not added to services so the stop command wont be recognized for it.

Title: Stop httpd, apache2


问:
Changing a .click function button to load right away instead?
I'm loading html2canvas which has the following script:

```<code> $(function() {
             $("#btnSave").click(function() {
                                 html2canvas($(".widget"), {
                                             onrendered: function(canvas) {
                                             theCanvas = canvas;
                                             document.body.appendChild(canvas);

                                             // Convert and download as image
                                             Canvas2Image.saveAsPNG(canvas);
                                             $("#img-out").append(canvas);
                                             // Clean up
                                             //document.body.removeChild(canvas);
                                             }
                                             });
                                 });
             });
</code>```

I have a button with the id "btnSave" that when clicked it generates my canvas image. Now, instead of having to click the button I would prefer it to load on the page automatically. Is this possible?

jsFiddle to what I'm working with: https://jsfiddle.net/h5ase09f/

Thanks in advance!

答:
is this what you looking for?</p>

```<code>$(document).ready(function(){
    $( "#btnSave" ).trigger( "click" );
});
</code>```

Body:
I'm loading html2canvas which has the following script:

 $(function() {
             $("#btnSave").click(function() {
                                 html2canvas($(".widget"), {
                                             onrendered: function(canvas) {
                                             theCanvas = canvas;
                                             document.body.appendChild(canvas);

                                             // Convert and download as image
                                             Canvas2Image.saveAsPNG(canvas);
                                             $("#img-out").append(canvas);
                                             // Clean up
                                             //document.body.removeChild(canvas);
                                             }
                                             });
                                 });
             });

I have a button with the id "btnSave" that when clicked it generates my canvas image. Now, instead of having to click the button I would prefer it to load on the page automatically. Is this possible?

jsFiddle to what I'm working with: https://jsfiddle.net/h5ase09f/

Thanks in advance!

Body:
is this what you looking for?

$(document).ready(function(){
    $( "#btnSave" ).trigger( "click" );
});


问:
SQL query for two tables, ignoring resultsets from second table
I wish to cast a query in two tables, but the result set should show only all results from the first table with the info from the second table linked with the first one, but there are many linked info, i just want the last linked information. eg

table 1

```<code>id_t1 | number | type
1        555     file
2        666     img
</code>```

table 2

```<code>id_t2 | id_table1_fk | date_in | description
1        1             04/07       aaaaaaa
2        1             05/07       bbbbbbb
</code>```

query

```<code>id_t1 | number | type | date_in | description
1        555     file     05/07     bbbbbbb
2        666     img       null      null
</code>```

答:
Try this:</p>

```<code>SELECT
    t1.*,
    new_t2.date_in,
    new_t2.description

FROM
    t1,
    (  SELECT *
       FROM t2
       WHERE id_table1_fk = t1.id_t1
       ORDER BY id_t2 DESC
       LIMIT 1
    ) AS new_t2
</code>```

Body:
I wish to cast a query in two tables, but the result set should show only all results from the first table with the info from the second table linked with the first one, but there are many linked info, i just want the last linked information. eg

table 1

id_t1 | number | type
1        555     file
2        666     img

table 2

id_t2 | id_table1_fk | date_in | description
1        1             04/07       aaaaaaa
2        1             05/07       bbbbbbb

query

id_t1 | number | type | date_in | description
1        555     file     05/07     bbbbbbb
2        666     img       null      null

Body:
Try this:

SELECT
    t1.*,
    new_t2.date_in,
    new_t2.description

FROM
    t1,
    (  SELECT *
       FROM t2
       WHERE id_table1_fk = t1.id_t1
       ORDER BY id_t2 DESC
       LIMIT 1
    ) AS new_t2


问:
Search a word in a string of characters in Python
Hello guys I have two strings in Python:

```<code>str1 = "honey"
str2 = "eeehanoey"
</code>```

I want that the program returns me True if all the letters in str1 are in str2 and False otherwise, I have alredy tried with in but doesn't works, return me False.

Thank you

答:
This will work:

```<code>all([c in str2 for c in str1])
</code>```

Or if you care about repeats, this will do it:

```<code>all([str2.count(c) <= str1.count(c) for c in str1])

>>> str1 = "honey"
>>> str2 = "eeehanoey"
>>> str3 = "hooney"
>>> all([str1.count(c) <= str2.count(c) for c in str1])
True
>>> all([str3.count(c) <= str2.count(c) for c in str3])
False
</code>```

There are probably some other ways to go about it as well, but these one-liners are not too bad.

Body:
Hello guys I have two strings in Python:

str1 = "honey"
str2 = "eeehanoey"

I want that the program returns me True if all the letters in str1 are in str2 and False otherwise, I have alredy tried with in but doesn't works, return me False.

Thank you

Body:
This will work:

all([c in str2 for c in str1])

Or if you care about repeats, this will do it:

all([str2.count(c) <= str1.count(c) for c in str1])

>>> str1 = "honey"
>>> str2 = "eeehanoey"
>>> str3 = "hooney"
>>> all([str1.count(c) <= str2.count(c) for c in str1])
True
>>> all([str3.count(c) <= str2.count(c) for c in str3])
False

There are probably some other ways to go about it as well, but these one-liners are not too bad.


答:
```<code>select table1.*, table2.date_in, table2.description
from table1 left outer join table2 on table1.id_t1 = table2.id_table1_fk
</code>```

Title: SQL query for two tables, ignoring resultsets from second table


问:
Shorthand if/else statement error from missing closing tag
When I use {props.dollarsInputGroup ? <InputGroup><InputGroup.Addon>$</InputGroup.Addon> : ''} the statement doesn't work because there is no close tag for <InputGroup>. What am I missing here?

UPDATE

```<code><FormGroup>
  {props.dollarsInputGroup ? <InputGroup><InputGroup.Addon>$</InputGroup.Addon> : ''}
  <Input />
  {props.dollarsInputGroup ? </InputGroup> : ''}
  {props.error ? <HelpBlock>{props.error}</HelpBlock> : '' }
</FormGroup>
</code>```

答:
You'll need to either repeat the <FormControl />, or define it once as a variable and use it twice (possibly with a function). For example:

```<code>var formControl = <FormControl />;
return <FormGroup>
    {props.dollarsInputGroup ? <InputGroup><InputGroup.Addon>$</InputGroup.Addon>{formControl}</InputGroup> : formControl}
    {props.error ? <HelpBlock>{props.error}</HelpBlock> : null}
</FormGroup>;
</code>```

Or… (though I think this is much less readable)

```<code><FormGroup>
    {(props.dollarsInputGroup ? ((fc) => <InputGroup><InputGroup.Addon>$</InputGroup.Addon>{fc}</InputGroup>) : ((fc) => fc))(<FormControl />)}
    {props.error ? <HelpBlock>{props.error}</HelpBlock> : null}
</FormGroup>
</code>```

Though you could use a definition elsewhere to help it a bit:

```<code>function maybeWrapWithDollars(wrapWithDollars, wrappedControl) {
    if(wrapWithDollars) {
        return <InputGroup><InputGroup.Addon>$</InputGroup.Addon>{wrappedControl}</InputGroup>;
    }else{
        return wrappedControl;
    }
}
// …
<FormGroup>
    {maybeWrapWithDollars(props.dollarsInputGroup, <FormControl />)}
    {props.error ? <HelpBlock>{props.error}</HelpBlock> : null}
</FormGroup>
</code>```

Body:
When I use {props.dollarsInputGroup ? <InputGroup><InputGroup.Addon>$</InputGroup.Addon> : ''} the statement doesn't work because there is no close tag for <InputGroup>. What am I missing here?

UPDATE

<FormGroup>
  {props.dollarsInputGroup ? <InputGroup><InputGroup.Addon>$</InputGroup.Addon> : ''}
  <Input />
  {props.dollarsInputGroup ? </InputGroup> : ''}
  {props.error ? <HelpBlock>{props.error}</HelpBlock> : '' }
</FormGroup>

Body:
You'll need to either repeat the <FormControl />, or define it once as a variable and use it twice (possibly with a function). For example:

var formControl = <FormControl />;
return <FormGroup>
    {props.dollarsInputGroup ? <InputGroup><InputGroup.Addon>$</InputGroup.Addon>{formControl}</InputGroup> : formControl}
    {props.error ? <HelpBlock>{props.error}</HelpBlock> : null}
</FormGroup>;

Or… (though I think this is much less readable)

<FormGroup>
    {(props.dollarsInputGroup ? ((fc) => <InputGroup><InputGroup.Addon>$</InputGroup.Addon>{fc}</InputGroup>) : ((fc) => fc))(<FormControl />)}
    {props.error ? <HelpBlock>{props.error}</HelpBlock> : null}
</FormGroup>

Though you could use a definition elsewhere to help it a bit:

function maybeWrapWithDollars(wrapWithDollars, wrappedControl) {
    if(wrapWithDollars) {
        return <InputGroup><InputGroup.Addon>$</InputGroup.Addon>{wrappedControl}</InputGroup>;
    }else{
        return wrappedControl;
    }
}
// …
<FormGroup>
    {maybeWrapWithDollars(props.dollarsInputGroup, <FormControl />)}
    {props.error ? <HelpBlock>{props.error}</HelpBlock> : null}
</FormGroup>


答:
Merge the conditions:</p>

```<code><FormGroup>
  {props.dollarsInputGroup ? <InputGroup><InputGroup.Addon>$</InputGroup.Addon><Input /></InputGroup> : <Input />}
  {props.error ? <HelpBlock>{props.error}</HelpBlock> : '' }
</FormGroup>
</code>```

Title: Shorthand if/else statement error from missing closing tag

Body:
Merge the conditions:

<FormGroup>
  {props.dollarsInputGroup ? <InputGroup><InputGroup.Addon>$</InputGroup.Addon><Input /></InputGroup> : <Input />}
  {props.error ? <HelpBlock>{props.error}</HelpBlock> : '' }
</FormGroup>


问:
button below recyclerview disappear
here is my layout

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.esraabalbaa.graduationproject.CartActivity">`enter code here <android.support.v7.widget.Toolbar
    android:id="@+id/toolb"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="#009688"
    app:popupTheme="@style/AppTheme.PopupOverlay" >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/gotoback"
        android:src="@drawable/ic_arrow_back_black_24dp"
        android:layout_alignParentRight="true"
        android:clickable="true"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cart"
        android:padding="10dp"
        android:textSize="20dp"
        android:textColor="#ffffff"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textSize="20dp"
        android:id="@+id/selecteditemcounter"
        android:textColor="#ffffff"/>
    </android.support.v7.widget.Toolbar>
<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/mycartrecycler"/>
<Button
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/checkoutsummary"
    android:layout_alignParentBottom="true"
    android:text="Checkout"
    android:textAlignment="center"
    android:textSize="20dp"/>
</code>```

im displaying a button below the recyclerview, button dont appear when i first open the activity and it  does appear only when i delet an item from the recyclerview so what is the problem?

答:
Try something like this using layout weights:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="20dp"
        android:weightSum="1"
        tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight=".90" />

    <Button
        android:id="@+id/addToDo"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight=".10"
        android:text="Add Item" />

</LinearLayout>
</code>```

Title: button below recyclerview disappear

Body:
here is my layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.esraabalbaa.graduationproject.CartActivity">`enter code here <android.support.v7.widget.Toolbar
    android:id="@+id/toolb"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="#009688"
    app:popupTheme="@style/AppTheme.PopupOverlay" >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/gotoback"
        android:src="@drawable/ic_arrow_back_black_24dp"
        android:layout_alignParentRight="true"
        android:clickable="true"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cart"
        android:padding="10dp"
        android:textSize="20dp"
        android:textColor="#ffffff"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textSize="20dp"
        android:id="@+id/selecteditemcounter"
        android:textColor="#ffffff"/>
    </android.support.v7.widget.Toolbar>
<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/mycartrecycler"/>
<Button
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/checkoutsummary"
    android:layout_alignParentBottom="true"
    android:text="Checkout"
    android:textAlignment="center"
    android:textSize="20dp"/>

im displaying a button below the recyclerview, button dont appear when i first open the activity and it  does appear only when i delet an item from the recyclerview so what is the problem?

Body:
Try something like this using layout weights:

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="20dp"
        android:weightSum="1"
        tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight=".90" />

    <Button
        android:id="@+id/addToDo"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight=".10"
        android:text="Add Item" />

</LinearLayout>


问:
HTML + CSS: Child div not displayed if parent div's bottom value not set
My problem is that the div which id is "problem" is not displayed. If its parent div has bottom:0 then the div "problem" is displayed correctly and parent div's height is 100% of browser window height.

I just do not want to use full height of window. The height of div "problem" should be so that there is always 30px bottom margin. So, no extra height, but 30px bottom margin.

Hello

Header

This should be displayed
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a

```

答:
The problem is that your #problem
 has an overflow of auto, which hides the contents of the element if the contents escape the bounds. Your #problem
 has a height of 0, so there's nowhere for the
 inside of it to display.

Simply removing overflow: auto from #problem fixes this problem (by restoring the overflow to visible by default).

Hello

Header

This should be displayed

```
</div>
</div>
</p>

<p>Note that <code>overflow: visible</code> will not show a scrollbar. If you would like to retain a scrollbar (although not illustrated in your question), you need to provide <code>#problem</code> with a <code>height</code> large enough to fully contain any elements within. I've gone with <code>20px</code> in this example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="z-index:999;display:block;position:fixed;left:0;right:0;top:0;bottom:0;height:100%;min-height:100%;background:rgba(65,77,117,.5);">
  <div style="display:block;clear:both;position:relative;width:403px;background-color:#FFFFFF;overflow:visible;top:0;/*bottom:0;*/left:50%;margin-left:-240px;position:fixed;z-index:100;">
    <div style="position:absolute;left:30px;right:30px;top:5px;">Hello</div>
    <h2>Header</h2>
    <div id="problem" style="position:absolute;top:78px;bottom:30px;left:30px;right:30px;overflow:auto;height:20px;">
      <div style="width:100%;display:inline-block;">This should be displayed</div>
    </div>
  </div>
</div></code>```

Hope this helps! :)

Body:
The problem is that your #problem <div> has an overflow of auto, which hides the contents of the element if the contents escape the bounds. Your #problem <div> has a height of 0, so there's nowhere for the <div> inside of it to display.

Simply removing overflow: auto from #problem fixes this problem (by restoring the overflow to visible by default).

<div style="z-index:999;display:block;position:fixed;left:0;right:0;top:0;bottom:0;height:100%;min-height:100%;background:rgba(65,77,117,.5);">
  <div style="display:block;clear:both;position:relative;width:403px;background-color:#FFFFFF;overflow:visible;top:0;/*bottom:0;*/left:50%;margin-left:-240px;position:fixed;z-index:100;">
    <div style="position:absolute;left:30px;right:30px;top:5px;">Hello</div>
    <h2>Header</h2>
    <div id="problem" style="position:absolute;top:78px;bottom:30px;left:30px;right:30px;overflow:auto;height:20px;">
      <div style="width:100%;display:inline-block;">This should be displayed</div>
    </div>
  </div>
</div>

Note that overflow: visible will not show a scrollbar. If you would like to retain a scrollbar (although not illustrated in your question), you need to provide #problem with a height large enough to fully contain any elements within. I've gone with 20px in this example:

<div style="z-index:999;display:block;position:fixed;left:0;right:0;top:0;bottom:0;height:100%;min-height:100%;background:rgba(65,77,117,.5);">
  <div style="display:block;clear:both;position:relative;width:403px;background-color:#FFFFFF;overflow:visible;top:0;/*bottom:0;*/left:50%;margin-left:-240px;position:fixed;z-index:100;">
    <div style="position:absolute;left:30px;right:30px;top:5px;">Hello</div>
    <h2>Header</h2>
    <div id="problem" style="position:absolute;top:78px;bottom:30px;left:30px;right:30px;overflow:auto;height:20px;">
      <div style="width:100%;display:inline-block;">This should be displayed</div>
    </div>
  </div>
</div>

Hope this helps! :)


问:
spritekit: unable to detect collision
so i tried to use skphysicscontact but when the "cat" and "spinnynode" collides there is no output from them, even when there is physical interaction

on another note, why can't the timer function work? it doesn't seem to call out the function at all.

please help, I'm a newbie. Thanks

```<code>import SpriteKit
import GameplayKit
import UIKit
import Foundation

struct physicsCollision {
static let cat: UInt32 = 1
static let spinnyNode: UInt32 = 2
}

class GameScene: SKScene, SKPhysicsContactDelegate {

var entities = [GKEntity]()
var graphs = [String : GKGraph]()
var catTimer = Timer()
var score = 0

private var lastUpdateTime : TimeInterval = 0
private var label : SKLabelNode?
private var spinnyNode : SKShapeNode?

let meow = SKAction.playSoundFileNamed("cat meow", waitForCompletion: false)

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

//random range

func randomInRange(lo: Float, hi : Float) -> Float{
    return lo + Float(arc4random_uniform(UInt32(hi - lo + 1)))
}

//spawn cat

func spawnCat(){

    // x coordinate between MinX (left) and MaxX (right):
    let randomX = randomInRange(lo: Float(self.frame.minX + 5), hi: Float(self.frame.maxX + 5))

    let startPoint = CGPoint(x: CGFloat(randomX), y: self.frame.height * 1.2)
    let endPoint = CGPoint(x: CGFloat(randomX), y:self.frame.height * -0.5)
    let cat = SKSpriteNode(imageNamed: "before right")

    cat.name = "cat"
    cat.setScale(0.3)
    cat.position = startPoint
    cat.zPosition = 1
    cat.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: cat.size.width, height: cat.size.height))
    cat.physicsBody?.affectedByGravity = false
    cat.physicsBody?.categoryBitMask = physicsCollision.cat
    cat.physicsBody?.contactTestBitMask = physicsCollision.spinnyNode
    cat.physicsBody?.collisionBitMask = physicsCollision.spinnyNode
    cat.physicsBody?.isDynamic = false
    self.addChild(cat)

    let moveCat = SKAction.move(to: endPoint, duration: 5)
    let deleteCat = SKAction.removeFromParent()
    let catSequence = SKAction.sequence([moveCat, meow, deleteCat])
    cat.run(catSequence)

}

//contact func

func didBeginContact(contact:SKPhysicsContact){

    var firstBody = SKPhysicsBody()
    var secondBody = SKPhysicsBody()

    if contact.bodyA.node?.name == "cat"
    {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    }
    else{
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }
 if firstBody.node?.name == "cat" && (secondBody.node?.name)! == "skinnynode"{
    print("contacted")

    }
}

override func sceneDidLoad() {

    self.physicsWorld.contactDelegate = self

    self.lastUpdateTime = 0

    //spawn cat at intervals,, time interval to decrease when points increase, use if loop

    catTimer = Timer.init(timeInterval: 1 , target: self, selector: Selector(("cat")), userInfo: nil, repeats: true)

    // Create shape node to use during mouse interaction
    let w = (self.size.width + self.size.height) * 0.05
    self.spinnyNode = SKShapeNode.init(rectOf: CGSize.init(width: w, height: w), cornerRadius: w * 0.5)
    spinnyNode?.name = "spinnynode"
    spinnyNode?.physicsBody = SKPhysicsBody(circleOfRadius: 0.5)
    spinnyNode?.physicsBody?.affectedByGravity = false
    spinnyNode?.zPosition = 1
    spinnyNode?.physicsBody?.categoryBitMask = physicsCollision.spinnyNode
    if let spinnyNode = self.spinnyNode{
        spinnyNode.lineWidth = 1.5
        spinnyNode.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(Double.pi), duration: 1)))
        spinnyNode.run(SKAction.sequence([SKAction.wait(forDuration: 0.5),
                                          SKAction.fadeOut(withDuration: 0.3),
                                          SKAction.removeFromParent()]))
                                        }

    //create score label
    let scoreLabel = UILabel(frame: CGRect(x:((self.frame.height) * 0.5) , y:((self.frame.width) * 0.3), width: (self.frame.size.width)/3, height: 30))
    scoreLabel.center = CGPoint(x: (self.frame.size.width)/1.6 , y: (self.frame.size.height)/2)
    scoreLabel.textColor = UIColor.white
    scoreLabel.text = "\(score)"
    self.view?.addSubview(scoreLabel)

                                }

func touchDown(atPoint pos : CGPoint) {
    if let n = self.spinnyNode?.copy() as! SKShapeNode? {
        n.position = pos
        n.strokeColor = SKColor.green
        self.addChild(n)
    }
}

func touchMoved(toPoint pos : CGPoint) {
    if let n = self.spinnyNode?.copy() as! SKShapeNode? {
        n.position = pos
        n.strokeColor = SKColor.purple
        self.addChild(n)

    }
}

func touchUp(atPoint pos : CGPoint) {
    if let n = self.spinnyNode?.copy() as! SKShapeNode? {
        n.position = pos
        n.strokeColor = SKColor.red
        self.addChild(n)
    }
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

            spawnCat()
            if let label = self.label {
            label.run(SKAction.init(named: "Pulse")!, withKey: "fadeInOut")

    }

    for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}

override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered

    // Initialize _lastUpdateTime if it has not already been
    if (self.lastUpdateTime == 0) {
        self.lastUpdateTime = currentTime
    }

    // Calculate time since last update
    let dt = currentTime - self.lastUpdateTime

    // Update entities
    for entity in self.entities {
        entity.update(deltaTime: dt)
    }

    self.lastUpdateTime = currentTime
}
</code>```

}

答:
You spelled the function wrong. It is never getting called. This is the correct protocol function name:

```<code>func didBegin(_ contact: SKPhysicsContact) {
  // Your stuff here..
}
</code>```

You can use autocomplete to avoid this problem. Start typing "didbegin" and you will have Xcode fill out the correct function:

As an aside:

Also, you are using hardcoded strings which can cause problems later on. Perhaps you could try using a constant value or a struct to avoid potential future spelling mistakes in strings:

```<code>let names = (cat: "cat", spinnynode: "spinnynode")

// cat.name = names.cat, etc...

func didBeginContact(contact:SKPhysicsContact){
  // ...
  if contact.bodyA.node?.name == names.cat
  {
    firstBody = contact.bodyA
    secondBody = contact.bodyB
  }
  else{
    firstBody = contact.bodyB
    secondBody = contact.bodyA
  }

  if firstBody.node?.name == names.cat && secondBody.node!.name == names.spinnynode {
    print("contacted")
  }
}
</code>```

Title: spritekit: unable to detect collision

Body:
so i tried to use skphysicscontact but when the "cat" and "spinnynode" collides there is no output from them, even when there is physical interaction

on another note, why can't the timer function work? it doesn't seem to call out the function at all.

please help, I'm a newbie. Thanks

import SpriteKit
import GameplayKit
import UIKit
import Foundation

struct physicsCollision {
static let cat: UInt32 = 1
static let spinnyNode: UInt32 = 2
}

class GameScene: SKScene, SKPhysicsContactDelegate {

var entities = [GKEntity]()
var graphs = [String : GKGraph]()
var catTimer = Timer()
var score = 0

private var lastUpdateTime : TimeInterval = 0
private var label : SKLabelNode?
private var spinnyNode : SKShapeNode?

let meow = SKAction.playSoundFileNamed("cat meow", waitForCompletion: false)

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

//random range

func randomInRange(lo: Float, hi : Float) -> Float{
    return lo + Float(arc4random_uniform(UInt32(hi - lo + 1)))
}

//spawn cat

func spawnCat(){

    // x coordinate between MinX (left) and MaxX (right):
    let randomX = randomInRange(lo: Float(self.frame.minX + 5), hi: Float(self.frame.maxX + 5))

    let startPoint = CGPoint(x: CGFloat(randomX), y: self.frame.height * 1.2)
    let endPoint = CGPoint(x: CGFloat(randomX), y:self.frame.height * -0.5)
    let cat = SKSpriteNode(imageNamed: "before right")

    cat.name = "cat"
    cat.setScale(0.3)
    cat.position = startPoint
    cat.zPosition = 1
    cat.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: cat.size.width, height: cat.size.height))
    cat.physicsBody?.affectedByGravity = false
    cat.physicsBody?.categoryBitMask = physicsCollision.cat
    cat.physicsBody?.contactTestBitMask = physicsCollision.spinnyNode
    cat.physicsBody?.collisionBitMask = physicsCollision.spinnyNode
    cat.physicsBody?.isDynamic = false
    self.addChild(cat)

    let moveCat = SKAction.move(to: endPoint, duration: 5)
    let deleteCat = SKAction.removeFromParent()
    let catSequence = SKAction.sequence([moveCat, meow, deleteCat])
    cat.run(catSequence)

}

//contact func

func didBeginContact(contact:SKPhysicsContact){

    var firstBody = SKPhysicsBody()
    var secondBody = SKPhysicsBody()

    if contact.bodyA.node?.name == "cat"
    {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    }
    else{
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }
 if firstBody.node?.name == "cat" && (secondBody.node?.name)! == "skinnynode"{
    print("contacted")

    }
}

override func sceneDidLoad() {

    self.physicsWorld.contactDelegate = self

    self.lastUpdateTime = 0

    //spawn cat at intervals,, time interval to decrease when points increase, use if loop

    catTimer = Timer.init(timeInterval: 1 , target: self, selector: Selector(("cat")), userInfo: nil, repeats: true)

    // Create shape node to use during mouse interaction
    let w = (self.size.width + self.size.height) * 0.05
    self.spinnyNode = SKShapeNode.init(rectOf: CGSize.init(width: w, height: w), cornerRadius: w * 0.5)
    spinnyNode?.name = "spinnynode"
    spinnyNode?.physicsBody = SKPhysicsBody(circleOfRadius: 0.5)
    spinnyNode?.physicsBody?.affectedByGravity = false
    spinnyNode?.zPosition = 1
    spinnyNode?.physicsBody?.categoryBitMask = physicsCollision.spinnyNode
    if let spinnyNode = self.spinnyNode{
        spinnyNode.lineWidth = 1.5
        spinnyNode.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(Double.pi), duration: 1)))
        spinnyNode.run(SKAction.sequence([SKAction.wait(forDuration: 0.5),
                                          SKAction.fadeOut(withDuration: 0.3),
                                          SKAction.removeFromParent()]))
                                        }

    //create score label
    let scoreLabel = UILabel(frame: CGRect(x:((self.frame.height) * 0.5) , y:((self.frame.width) * 0.3), width: (self.frame.size.width)/3, height: 30))
    scoreLabel.center = CGPoint(x: (self.frame.size.width)/1.6 , y: (self.frame.size.height)/2)
    scoreLabel.textColor = UIColor.white
    scoreLabel.text = "\(score)"
    self.view?.addSubview(scoreLabel)

                                }

func touchDown(atPoint pos : CGPoint) {
    if let n = self.spinnyNode?.copy() as! SKShapeNode? {
        n.position = pos
        n.strokeColor = SKColor.green
        self.addChild(n)
    }
}

func touchMoved(toPoint pos : CGPoint) {
    if let n = self.spinnyNode?.copy() as! SKShapeNode? {
        n.position = pos
        n.strokeColor = SKColor.purple
        self.addChild(n)

    }
}

func touchUp(atPoint pos : CGPoint) {
    if let n = self.spinnyNode?.copy() as! SKShapeNode? {
        n.position = pos
        n.strokeColor = SKColor.red
        self.addChild(n)
    }
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

            spawnCat()
            if let label = self.label {
            label.run(SKAction.init(named: "Pulse")!, withKey: "fadeInOut")

    }

    for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}

override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered

    // Initialize _lastUpdateTime if it has not already been
    if (self.lastUpdateTime == 0) {
        self.lastUpdateTime = currentTime
    }

    // Calculate time since last update
    let dt = currentTime - self.lastUpdateTime

    // Update entities
    for entity in self.entities {
        entity.update(deltaTime: dt)
    }

    self.lastUpdateTime = currentTime
}

}

Body:
You spelled the function wrong. It is never getting called. This is the correct protocol function name:

func didBegin(_ contact: SKPhysicsContact) {
  // Your stuff here..
}

You can use autocomplete to avoid this problem. Start typing "didbegin" and you will have Xcode fill out the correct function:

As an aside:

Also, you are using hardcoded strings which can cause problems later on. Perhaps you could try using a constant value or a struct to avoid potential future spelling mistakes in strings:

let names = (cat: "cat", spinnynode: "spinnynode")

// cat.name = names.cat, etc...

func didBeginContact(contact:SKPhysicsContact){
  // ...
  if contact.bodyA.node?.name == names.cat
  {
    firstBody = contact.bodyA
    secondBody = contact.bodyB
  }
  else{
    firstBody = contact.bodyB
    secondBody = contact.bodyA
  }

  if firstBody.node?.name == names.cat && secondBody.node!.name == names.spinnynode {
    print("contacted")
  }
}


问:
Install mod_wsgi on Ubuntu with Python 3.6, Apache 2.4, and Django 1.11
How do I get mod_wsgi for Apache2 that was compiled for Python 3.6.1?

(or any future Python version)

I am using a Python 3.6.1 virtual environment with Django 1.11 and Everything is working according to the Apache error log except that mod_wsgi for Apache 2.4 was compiled for Python/3.5.1+ and is using Python/3.5.2 so my Python 3.6.1 code is failing because I'm using new features not available in 3.5.2

All of the other configurations and installs involved in setting my system up seem to be fine (Running in daemon mode) though mod_wsgi doesn't seem to be using my Python 3.6.1 virtual environment (though it is trying to use it for Django according to the error log)...

I used: sudo apt-get install libapache2-mod-wsgi-py3 to install mod_wsgi for Apache 2.4

I used: ./configure --with-python=/usr/local/bin/python3.6 and make with make install to install mod_wsgi for Python 3.6

I must be doing something wrong - please correct me!

Here is my Apache Error Log (cleaned a bit) - and yes I know it fails on the f"" string line (python 3.6 feature not in 3.5)

```<code>[wsgi:warn] mod_wsgi: Compiled for Python/3.5.1+.
[wsgi:warn] mod_wsgi: Runtime using Python/3.5.2.
[wsgi:warn] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/3.5.2 configured -- resuming normal operations
[wsgi:warn] AH00094: Command line: '/usr/sbin/apache2'
[wsgi:error] mod_wsgi (pid=12963): Target WSGI script '/home/jamin/www/dev.tir.com/tir/tir/wsgi.py' cannot be loaded as Python module.
[wsgi:error] mod_wsgi (pid=12963): Exception occurred processing WSGI script '/home/jamin/www/dev.tir.com/tir/tir/wsgi.py'.
[wsgi:error] Traceback (most recent call last):
[wsgi:error]   File "/home/jamin/www/dev.tir.com/tir/tir/wsgi.py", line 21, in <module>
[wsgi:error]     application = get_wsgi_application()
[wsgi:error]   File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
[wsgi:error]     django.setup(set_prefix=False)
[wsgi:error]   File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
[wsgi:error]     apps.populate(settings.INSTALLED_APPS)
[wsgi:error]   File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/django/apps/registry.py", line 116, in populate
[wsgi:error]     app_config.ready()
[wsgi:error]   File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 23, in ready
[wsgi:error]     self.module.autodiscover()
[wsgi:error]   File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
[wsgi:error]     autodiscover_modules('admin', register_to=site)
[wsgi:error]   File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
[wsgi:error]     import_module('%s.%s' % (app_config.name, module_to_search))
[wsgi:error]   File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
[wsgi:error]     return _bootstrap._gcd_import(name[level:], package, level)
[wsgi:error]   File "<frozen importlib._bootstrap>", line 986, in _gcd_import
[wsgi:error]   File "<frozen importlib._bootstrap>", line 969, in _find_and_load
[wsgi:error]   File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
[wsgi:error]   File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
[wsgi:error]   File "<frozen importlib._bootstrap_external>", line 665, in exec_module
[wsgi:error]   File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
[wsgi:error]   File "/home/jamin/www/dev.tir.com/tir/company/admin.py", line 13, in <module>
[wsgi:error]     from .forms import AdminInteractionForm
[wsgi:error]   File "/home/jamin/www/dev.tir.com/tir/company/forms.py", line 87
[wsgi:error]     resp = f"Hi {user.first_name}, you'll need to login to send any more suggestions. \\
[wsgi:error]                              \\n\\nFirst Time? Check your email/spam for login instructions from us."
[wsgi:error]
[wsgi:error]                                                                                ^
[wsgi:error] SyntaxError: invalid syntax
</code>```

*also tir.com is shorthand for my actual site - i do not have anything to do with that domain

答:
Do the following.

Uninstall your system mod_wsgi package.

```<code>sudo apt-get remove libapache2-mod-wsgi-py3
</code>```

Install mod_wsgi using pip, preferably into a Python virtual environment. Ensure pip is for the version of Python you want to use.

```<code>pip install mod_wsgi
</code>```

Display the config to add to Apache configuration file to load this mod_wsgi by running:

```<code>mod_wsgi-express module-config
</code>```

Take the output of above command to display config and add to Apache configuration.

Add configuration to Apache to load a hello world WSGI application to test it works.

See details for pip based install in:

https://pypi.python.org/pypi/mod_wsgi

Body:
How do I get mod_wsgi for Apache2 that was compiled for Python 3.6.1?

(or any future Python version)

I am using a Python 3.6.1 virtual environment with Django 1.11 and Everything is working according to the Apache error log except that mod_wsgi for Apache 2.4 was compiled for Python/3.5.1+ and is using Python/3.5.2 so my Python 3.6.1 code is failing because I'm using new features not available in 3.5.2

All of the other configurations and installs involved in setting my system up seem to be fine (Running in daemon mode) though mod_wsgi doesn't seem to be using my Python 3.6.1 virtual environment (though it is trying to use it for Django according to the error log)...

I used: sudo apt-get install libapache2-mod-wsgi-py3 to install mod_wsgi for Apache 2.4

I used: ./configure --with-python=/usr/local/bin/python3.6 and make with make install to install mod_wsgi for Python 3.6

I must be doing something wrong - please correct me!

Here is my Apache Error Log (cleaned a bit) - and yes I know it fails on the f"" string line (python 3.6 feature not in 3.5)

[wsgi:warn] mod_wsgi: Compiled for Python/3.5.1+.
[wsgi:warn] mod_wsgi: Runtime using Python/3.5.2.
[wsgi:warn] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/3.5.2 configured -- resuming normal operations
[wsgi:warn] AH00094: Command line: '/usr/sbin/apache2'
[wsgi:error] mod_wsgi (pid=12963): Target WSGI script '/home/jamin/www/dev.tir.com/tir/tir/wsgi.py' cannot be loaded as Python module.
[wsgi:error] mod_wsgi (pid=12963): Exception occurred processing WSGI script '/home/jamin/www/dev.tir.com/tir/tir/wsgi.py'.
[wsgi:error] Traceback (most recent call last):
[wsgi:error]   File "/home/jamin/www/dev.tir.com/tir/tir/wsgi.py", line 21, in <module>
[wsgi:error]     application = get_wsgi_application()
[wsgi:error]   File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
[wsgi:error]     django.setup(set_prefix=False)
[wsgi:error]   File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
[wsgi:error]     apps.populate(settings.INSTALLED_APPS)
[wsgi:error]   File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/django/apps/registry.py", line 116, in populate
[wsgi:error]     app_config.ready()
[wsgi:error]   File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 23, in ready
[wsgi:error]     self.module.autodiscover()
[wsgi:error]   File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
[wsgi:error]     autodiscover_modules('admin', register_to=site)
[wsgi:error]   File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
[wsgi:error]     import_module('%s.%s' % (app_config.name, module_to_search))
[wsgi:error]   File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
[wsgi:error]     return _bootstrap._gcd_import(name[level:], package, level)
[wsgi:error]   File "<frozen importlib._bootstrap>", line 986, in _gcd_import
[wsgi:error]   File "<frozen importlib._bootstrap>", line 969, in _find_and_load
[wsgi:error]   File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
[wsgi:error]   File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
[wsgi:error]   File "<frozen importlib._bootstrap_external>", line 665, in exec_module
[wsgi:error]   File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
[wsgi:error]   File "/home/jamin/www/dev.tir.com/tir/company/admin.py", line 13, in <module>
[wsgi:error]     from .forms import AdminInteractionForm
[wsgi:error]   File "/home/jamin/www/dev.tir.com/tir/company/forms.py", line 87
[wsgi:error]     resp = f"Hi {user.first_name}, you'll need to login to send any more suggestions. \\
[wsgi:error]                              \\n\\nFirst Time? Check your email/spam for login instructions from us."
[wsgi:error]
[wsgi:error]                                                                                ^
[wsgi:error] SyntaxError: invalid syntax

*also tir.com is shorthand for my actual site - i do not have anything to do with that domain

Body:
Do the following.

Uninstall your system mod_wsgi package.

sudo apt-get remove libapache2-mod-wsgi-py3

Install mod_wsgi using pip, preferably into a Python virtual environment. Ensure pip is for the version of Python you want to use.

pip install mod_wsgi

Display the config to add to Apache configuration file to load this mod_wsgi by running:

mod_wsgi-express module-config

Take the output of above command to display config and add to Apache configuration.

Add configuration to Apache to load a hello world WSGI application to test it works.

See details for pip based install in:

https://pypi.python.org/pypi/mod_wsgi


问:
SQLAlchemy won't connect correctly but pyodbc and pymssql will
I have been trying to diagnose the issue in a Windows Python 2.7 (Anaconda installed) environment running SQLAlchemy=1.1.11, pyodbc=4.0.17, and pymssql=2.1.3.

Both pyodbc and pymssql connections will successfully connect and query a table correctly.  However, when I attempt the same connection and query through SQLAlchemy either using an ORM or direct SQL, it fails with the following error:

sqlalchemy.exc.NoSuchColumnError: "Could not locate column in row for column '0'

The connection string I'm using is the following:

```<code>'mssql+pyodbc://:@CMPDSQL01:1433/CMP?driver=SQL+Server+Native+Client+10.0'
</code>```

The connection and simple query through pyodbc uses the following:

```<code>print "---- Testing pyodbc Directly"
cnxn = pyodbc.connect(
    r'Trusted_Connection=yes;'
    r'DRIVER={SQL Server Native Client 10.0};'
    r'SERVER=CMPDSQL01;'
    r'DATABASE=CMP;'
    )

print cnxn
print "---- Complete ----"

print "---- Running Direct SQL Query on pyodbc Direct Connection"
cursor = cnxn.cursor()
cursor.execute('SELECT * FROM EPO_MODELS')
for r in cursor:
    print r
print "---- Complete ----"
</code>```

The connection and simple query through pymssql uses the following:

```<code>print "---- Testing pymssql Directly"
cnxn = pymssql.connect(server='CMPDSQL01', port='1433', database='CMP')
print cnxn
print "---- Complete ----"

print "---- Running Direct SQL Query on pymssql Direct Connection"
cursor = cnxn.cursor()
cursor.execute('SELECT * FROM EPO_MODELS')
for r in cursor:
    print r
print "---- Complete ----"
</code>```

What is even more perplexing is that the SQLAlchemy connection used to work but now no longer works.  Unfortunately I don't know what broke it due to a clean start install.

I don't think the EPO_MODELS object model comes into play with this error because even a direct SQL query fails in the same way.  However, for completeness the EPO_MODELS object model is very simple and looks like the following:

```<code>class EPO_MODELS(Base):
    __tablename__ = 'EPO_MODELS'

    ID = Column(Integer, primary_key=True, autoincrement=False)
    MODELTYPE = Column(Integer, autoincrement=False)
    MODELNAME = Column(NVARCHAR(255))
    MEMO = Column(NVARCHAR(2000))
    NEXTUNIQUEID = Column(Integer, autoincrement=False)
    MODELSYNC = Column(Integer, autoincrement=False)
    MODELSTATUS = Column(Integer, autoincrement=False)
    AUDITUSERID = Column(Integer, autoincrement=False)
    DATEALTERED = Column(DateTime)
    CREATIONDATE = Column(DateTime)
</code>```

The direct SQLAlchemy query looks like the following after getting the session using the connection string above:

```<code>print "---- Running Direct SQL Query Through SQLAlchemy Connection"
result = con.execute('SELECT * FROM EPO_MODELS')
for r in result:
    print r
print "---- Complete ----"
</code>```

Very much appreciate any insight into what is going on here.  I can't seem to find the disconnect. Thanks in advance.

答:
After some diagnosis on the SQLAlchemy mailing list it looks like this is caused by the c extensions not being compatible with the server.  After removing the cresultproxy.pyd file from the sqlalchemy directory in site-packages the issue was resolved.

A pip uninstall/install did not fix the issue since the extensions were rebuilt during the install.  The c extension build did not emit any warnings or errors.  It just looks like this might be an edge case of an old Windows Server 2008 server configuration not working properly with the c extensions.

Body:
I have been trying to diagnose the issue in a Windows Python 2.7 (Anaconda installed) environment running SQLAlchemy=1.1.11, pyodbc=4.0.17, and pymssql=2.1.3.

Both pyodbc and pymssql connections will successfully connect and query a table correctly.  However, when I attempt the same connection and query through SQLAlchemy either using an ORM or direct SQL, it fails with the following error:

sqlalchemy.exc.NoSuchColumnError: "Could not locate column in row for column '0'

The connection string I'm using is the following:

'mssql+pyodbc://:@CMPDSQL01:1433/CMP?driver=SQL+Server+Native+Client+10.0'

The connection and simple query through pyodbc uses the following:

print "---- Testing pyodbc Directly"
cnxn = pyodbc.connect(
    r'Trusted_Connection=yes;'
    r'DRIVER={SQL Server Native Client 10.0};'
    r'SERVER=CMPDSQL01;'
    r'DATABASE=CMP;'
    )

print cnxn
print "---- Complete ----"

print "---- Running Direct SQL Query on pyodbc Direct Connection"
cursor = cnxn.cursor()
cursor.execute('SELECT * FROM EPO_MODELS')
for r in cursor:
    print r
print "---- Complete ----"

The connection and simple query through pymssql uses the following:

print "---- Testing pymssql Directly"
cnxn = pymssql.connect(server='CMPDSQL01', port='1433', database='CMP')
print cnxn
print "---- Complete ----"

print "---- Running Direct SQL Query on pymssql Direct Connection"
cursor = cnxn.cursor()
cursor.execute('SELECT * FROM EPO_MODELS')
for r in cursor:
    print r
print "---- Complete ----"

What is even more perplexing is that the SQLAlchemy connection used to work but now no longer works.  Unfortunately I don't know what broke it due to a clean start install.

I don't think the EPO_MODELS object model comes into play with this error because even a direct SQL query fails in the same way.  However, for completeness the EPO_MODELS object model is very simple and looks like the following:

class EPO_MODELS(Base):
    __tablename__ = 'EPO_MODELS'

    ID = Column(Integer, primary_key=True, autoincrement=False)
    MODELTYPE = Column(Integer, autoincrement=False)
    MODELNAME = Column(NVARCHAR(255))
    MEMO = Column(NVARCHAR(2000))
    NEXTUNIQUEID = Column(Integer, autoincrement=False)
    MODELSYNC = Column(Integer, autoincrement=False)
    MODELSTATUS = Column(Integer, autoincrement=False)
    AUDITUSERID = Column(Integer, autoincrement=False)
    DATEALTERED = Column(DateTime)
    CREATIONDATE = Column(DateTime)

The direct SQLAlchemy query looks like the following after getting the session using the connection string above:

print "---- Running Direct SQL Query Through SQLAlchemy Connection"
result = con.execute('SELECT * FROM EPO_MODELS')
for r in result:
    print r
print "---- Complete ----"

Very much appreciate any insight into what is going on here.  I can't seem to find the disconnect. Thanks in advance.


问:
Chrome extension Open homepage in new tab
I created a simple chrome extension. When user clicks on it, It will open a website in a new tab. My question is, I want my extension to open a  new tab with given URL every time when user opens chrome browser.</p>

答: browserAction.onClicked event handler worked in background.js

ContentLicense: CC BY-SA 4.0


问:
Facebook local testing: In which direction data is flowing?
This question is not about how to set up local environment to test Facebook application. Rather I've already set this up with the help of this thread. In short I changed my hosts file and its working great.

But, I've a got a doubt:

Assumption: Everywhere I've read that Facebook server works like a proxy and fetches web-pages, like a web service, from application provider's server and then sends this embedded data to browser.

For testing purposes, I've changed my hosts file like mentioned in above thread. My question is if Facebook server is fetching data from my web server then how come my browser gets this data locally after changing hosts file?

It seems either my assumption is wrong or I am missing something fundamental. Please help. Thanks.

答: Facebook only acts as a proxy server if you are building an FBML app. If you are building an iFrame app, the request to your application is coming directly from the client browser. You can test this out by actually setting your canvas url to something like http://localhost:8080/ and running your app locally. You will be able to run the application like normal, but obviously only you will be able to use it since it is on localhost.</p>

ContentLicense: CC BY-SA 2.5


问:
Paste Special in Excel as standard
Is there a way where I can make an Excel file where whenever you copy something from it then it will automatically use paste special formatted as values? Even if you paste in another Excel file.</p>

答:
Just add the paste special icon to the quick access toolbar, then it is available in any spreadsheet.  As a bonus this becomes easily accessible by a keyboard shortcut as well, just press ALT and the given alphanumeric.  See the images below.

When you copy, the information is passed into to clipboard but, AFAIK, there is no way to pass a parameter let alone have that modify the paste function.

Title: Paste Special in Excel as standard


问:
Date range question
If I have 2 dates, 21/05/2010 and 23/05/2010, how can I find out if 22/05/2006 7:16 AM exists in between them?

I am using the following code to calculate the min/max date and will then SELECT ALL records in the table that are clear to update them.

```<code>    $today = date('l');

    if($today == 'Wednesday'){
        $min = date('d/m/Y', strtotime('0 days'));
        $max = date('d/m/Y', strtotime('+6 days'));
    }else if($today == 'Thursday'){
        $min = date('d/m/Y', strtotime('-1 days'));
        $max = date('d/m/Y', strtotime('+5 days'));
    }else if($today == 'Friday'){
        $min = date('d/m/Y', strtotime('-2 days'));
        $max = date('d/m/Y', strtotime('+4 days'));
    }else if($today == 'Saturday'){
        $min = date('d/m/Y', strtotime('-3 days'));
        $max = date('d/m/Y', strtotime('+3 days'));
    }else if($today == 'Sunday'){
        $min = date('d/m/Y', strtotime('-4 days'));
        $max = date('d/m/Y', strtotime('+2 days'));
    }else if($today == 'Monday'){
        $min = date('d/m/Y', strtotime('-5 days'));
        $max = date('d/m/Y', strtotime('+1 days'));
    }else if($today == 'Tuesday'){
        $min = date('d/m/Y', strtotime('-6 days'));
        $max = date('d/m/Y', strtotime('0 days'));
    }
</code>```

答:
Use strtotime</p>

```<code> $date1 = strtotime($date1);
 $date2 = strtotime($date2);
 $datefind = strtotime($datefind);

 if ($datefind >= $date1 &&  $datefind <= $date2)
</code>```

Title: Date range question

Body:
If I have 2 dates, 21/05/2010 and 23/05/2010, how can I find out if 22/05/2006 7:16 AM exists in between them?

I am using the following code to calculate the min/max date and will then SELECT ALL records in the table that are clear to update them.

    $today = date('l');

    if($today == 'Wednesday'){
        $min = date('d/m/Y', strtotime('0 days'));
        $max = date('d/m/Y', strtotime('+6 days'));
    }else if($today == 'Thursday'){
        $min = date('d/m/Y', strtotime('-1 days'));
        $max = date('d/m/Y', strtotime('+5 days'));
    }else if($today == 'Friday'){
        $min = date('d/m/Y', strtotime('-2 days'));
        $max = date('d/m/Y', strtotime('+4 days'));
    }else if($today == 'Saturday'){
        $min = date('d/m/Y', strtotime('-3 days'));
        $max = date('d/m/Y', strtotime('+3 days'));
    }else if($today == 'Sunday'){
        $min = date('d/m/Y', strtotime('-4 days'));
        $max = date('d/m/Y', strtotime('+2 days'));
    }else if($today == 'Monday'){
        $min = date('d/m/Y', strtotime('-5 days'));
        $max = date('d/m/Y', strtotime('+1 days'));
    }else if($today == 'Tuesday'){
        $min = date('d/m/Y', strtotime('-6 days'));
        $max = date('d/m/Y', strtotime('0 days'));
    }

Body:
Use strtotime

 $date1 = strtotime($date1);
 $date2 = strtotime($date2);
 $datefind = strtotime($datefind);

 if ($datefind >= $date1 &&  $datefind <= $date2)


问:
Tensorflow GPU - Spyder
I am having a problem with importing tensorflow GPU on spyder.
This is what I get when I type import tensorflow on iPython using Spyder 3 (on MacOS)

When I checked what packages I have within tensorflow I get this list, which I see that iPython, and Spyder are not included.

Also in anaconda, when I click on tensorflow in Environments, I have the option to open it with Python, with terminal, but not with iPython or Spyder (or Jupyter)

I would very much appreciate any help.

UPDATE 1:

Ok I managed to get Spyder on tensorflow's ENV but when I run the command 'import tensorflow' on iPython I get this error (when I run the same command on Python's tab everything seems to work just fine.

答: Finally I solved this mystery. If you have installed Spyder from the Anaconda, go to the Anaconda launcher. There go to environments, you will see two of them: root and tensorflow. The latter one is created due to the instructions by tensorflow.org. Just run all those instructions on the root, don't activate tensorflow environment, it will work. Everything will be available in spyder.</p>

Title: Tensorflow GPU - Spyder


问:
Replace occurrence of string in another string with Numbers in PHP
I have a html string code which contain some "img" tags. I want to search the string and change each "<img " occurrence with something like "<img onclick=lightbox(XXXX)", so the first one should become "<img onclick=lightbox(0)" then the second occurrence should become "<img onclick=lightbox(1)" and then third one should become "<img onclick=lightbox(2)" and etc,  How can I achieve this in PHP?

答:
parse the html as a DOMObject and replace</p>

```<code>function replace_img($html) {
  $doc = new DOMDocument();
  $doc->loadHTML($html);
  $tags = $doc->getElementsByTagName('img');
  $i=0;
  foreach ($tags as $tag) {
    $tag->setAttribute('onclick', "lightbox($i)");
    $i++;
  }
   return $doc->saveHTML();
}
</code>```

Body:
parse the html as a DOMObject and replace

function replace_img($html) {
  $doc = new DOMDocument();
  $doc->loadHTML($html);
  $tags = $doc->getElementsByTagName('img');
  $i=0;
  foreach ($tags as $tag) {
    $tag->setAttribute('onclick', "lightbox($i)");
    $i++;
  }
   return $doc->saveHTML();
}


问:
ElementType.LOCAL_VARIABLE annotation type
I`d like to create my own annotations to annotate some local variable. To write the annotation is not the problem, the problem is to get the information of them at the Runtime. I could only get some information from annotated methods or method parameters, but not from local variables. Is there any way to get it?

My own annotation is something like that:

```<code>public void m(int a)
@MyOwnAnnotation(some information)
int b = 5;
}
</code>```

Or, as an alternative, is there any way to get the code of the method, to parse it further and finally get annotation value?

Thanks in advance.

答:
At the moment, as mentioned in some other posts, you cannot retrieve a local variable value simply from the annotation alone.

However, I did have a simimlar issue and managed to come up with a solution using fields. Sample code is below:

Interface Class

```<code>@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface test{
}
</code>```

PoJo

```<code>public class testObject{
    @test
    private String one;
    private String two;

    //Getters and Setters
}
</code>```

Get Object values

```<code>public void getFields (Object obj){
    Field fields = obj.getClass().getDeclaredFields();

    for (Field f : fields){
        test fieldAnnotation = f.getAnnotation(test.Class);
        if (fieldAnnotation != null){
            f.get(obj);
            // Do things here based on the values
        }
    }
}
</code>```

Main Class

```<code>public static void main(String[] args){
    //Create object
    testObject test = new testObject();

    test.setOne("testOne");
    test.setTwo("testTwo");
    getFields(test);
}
</code>```

Hopefully this helps in explaining how you can get the fields for an object based on the annotation. You are simply using the annotation to 'mark' the fields you want to retrieve and then reading the value from the object.

Body:
I`d like to create my own annotations to annotate some local variable. To write the annotation is not the problem, the problem is to get the information of them at the Runtime. I could only get some information from annotated methods or method parameters, but not from local variables. Is there any way to get it?

My own annotation is something like that:

public void m(int a)
@MyOwnAnnotation(some information)
int b = 5;
}

Or, as an alternative, is there any way to get the code of the method, to parse it further and finally get annotation value?

Thanks in advance.

Body:
At the moment, as mentioned in some other posts, you cannot retrieve a local variable value simply from the annotation alone.

However, I did have a simimlar issue and managed to come up with a solution using fields. Sample code is below:

Interface Class

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface test{
}

PoJo

public class testObject{
    @test
    private String one;
    private String two;

    //Getters and Setters
}

Get Object values

public void getFields (Object obj){
    Field fields = obj.getClass().getDeclaredFields();

    for (Field f : fields){
        test fieldAnnotation = f.getAnnotation(test.Class);
        if (fieldAnnotation != null){
            f.get(obj);
            // Do things here based on the values
        }
    }
}

Main Class

public static void main(String[] args){
    //Create object
    testObject test = new testObject();

    test.setOne("testOne");
    test.setTwo("testTwo");
    getFields(test);
}

Hopefully this helps in explaining how you can get the fields for an object based on the annotation. You are simply using the annotation to 'mark' the fields you want to retrieve and then reading the value from the object.


问:
Where to place the call to a external API that has a dependency on a Model?
Suppose I have a Django app named "blog".

There's a model called Post and I have an external API call that returns the list of the most popular posts in a given time, e.g., the Google Analytics API.

My question is: Where is the expected place that I should place the code that makes the call to the external API, parses the id from each post, query the database and sort the list of models accordingly?

I don't think that it should live in the Manager or in a templatetag. Any tips or suggestions?

Thanks in advance!

EDIT: The desired result might be need in several places across the project, so if I place the code in view, I'll have duplication.

答: This sounds like it should be done in a View, because then you will be returning to a template with all the required context.</p>