问:
Swift String escaping when serializing to JSON using Codable
I'm trying to serialize my object as following:

```<code>import Foundation

struct User: Codable {
    let username: String
    let profileURL: String
}

let user = User(username: "John", profileURL: "http://google.com")

let json = try? JSONEncoder().encode(user)

if let data = json, let str = String(data: data, encoding: .utf8) {
    print(str)
}
</code>```

However on macOS I'm getting the following:

```<code>{"profileURL":"http:\/\/google.com","username":"John"}
</code>```

(note escaped '/' character).

While on Linux machines I'm getting:

```<code>{"username":"John","profileURL":"http://google.com"}
</code>```

How can I make JSONEncoder return the unescaped?

I need the string in JSON to be strictly unescaped.

答:
While playing around JSONEncoder/JSONDecoder,
I found that the URL type is lossy on encode -> decode.

Initializes with a string, relative to another URL.

```<code>init?(string: String, relativeTo: URL?)
</code>```

Might be help this apple document: https://developer.apple.com/documentation/foundation/url

using the PropertyList version, however:

```<code>let url = URL(string: "../", relativeTo: URL(string: "http://google.com"))!
let url2 = PropertyListDecoder().decode([URL].self, from: PropertyListEncoder().encode([User]))
</code>```

Other way

```<code>let url = URL(string: "../", relativeTo: URL(string: "http://google.com"))!
let url2 = JSONDecoder().decode([URL].self, from: JSONEncoder().encode([User]))
</code>```

Hope will helpful to you!!

Body:
I'm trying to serialize my object as following:

import Foundation

struct User: Codable {
    let username: String
    let profileURL: String
}

let user = User(username: "John", profileURL: "http://google.com")

let json = try? JSONEncoder().encode(user)

if let data = json, let str = String(data: data, encoding: .utf8) {
    print(str)
}

However on macOS I'm getting the following:

{"profileURL":"http:\/\/google.com","username":"John"}

(note escaped '/' character).

While on Linux machines I'm getting:

{"username":"John","profileURL":"http://google.com"}

How can I make JSONEncoder return the unescaped?

I need the string in JSON to be strictly unescaped.

Body:
While playing around JSONEncoder/JSONDecoder,
I found that the URL type is lossy on encode -> decode.

Initializes with a string, relative to another URL.

init?(string: String, relativeTo: URL?)

Might be help this apple document: https://developer.apple.com/documentation/foundation/url

using the PropertyList version, however:

let url = URL(string: "../", relativeTo: URL(string: "http://google.com"))!
let url2 = PropertyListDecoder().decode([URL].self, from: PropertyListEncoder().encode([User]))

Other way

let url = URL(string: "../", relativeTo: URL(string: "http://google.com"))!
let url2 = JSONDecoder().decode([URL].self, from: JSONEncoder().encode([User]))

Hope will helpful to you!!


来源: stackexchange

问:
fadeIn and fadeOut not working as expected
In my code i've few images and i've tried to show them as slider so when a clickme button clicked the image will be change to next image.I  have succssfully done this fucntion but i want animation ,when i click clickme button then current image should fadeOut and next image should be fadeIn,
I'm unable to do this,

```<code>   $('#allimg li:first').addClass('activeimg');
  //code for like and next image
   $('.clickme').on('click', function() {
    var tagname = $('.activeimg img').attr('name');
    if ( $('#allimg li.activeimg').index() + parseInt(1) !== $('#allimg li').length ) {
        $('.activeimg').removeClass('activeimg').fadeIn().next('#allimg li').addClass('activeimg').fadeOut();
       }
  });
</code>```

Just a small help is needed,

答:
here is a very basic implementation of fadeIn and fadeOut;

Since your code wasn't complete; I created my own;

Hope this helps

 $("button").click(function(){
        $("#dog1").fadeOut("slow");
        $("#dog3").fadeIn("slow");
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dog3 {
  display:none;
}</code>```

<button> Fade Images </button>```

ContentLicense: CC BY-SA 3.0

Body:
In my code i've few images and i've tried to show them as slider so when a clickme button clicked the image will be change to next image.I  have succssfully done this fucntion but i want animation ,when i click clickme button then current image should fadeOut and next image should be fadeIn,
I'm unable to do this,

   $('#allimg li:first').addClass('activeimg');
  //code for like and next image
   $('.clickme').on('click', function() {
    var tagname = $('.activeimg img').attr('name');
    if ( $('#allimg li.activeimg').index() + parseInt(1) !== $('#allimg li').length ) {
        $('.activeimg').removeClass('activeimg').fadeIn().next('#allimg li').addClass('activeimg').fadeOut();
       }
  });

Just a small help is needed,

Body:
here is a very basic implementation of fadeIn and fadeOut;

Since your code wasn't complete; I created my own;

Hope this helps

 $("button").click(function(){
        $("#dog1").fadeOut("slow");
        $("#dog3").fadeIn("slow");
    });

#dog3 {
  display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://i.pinimg.com/originals/b0/d7/08/b0d708c285de860ce5d51a8d558409dc.jpg" width ="100px" height="100px" id="dog1">
<img src="https://www.cesarsway.com/sites/newcesarsway/files/styles/large_article_preview/public/Common-dog-behaviors-explained.jpg?itok=FSzwbBoi" width ="100px" height="100px" id="dog3">
<button> Fade Images </button>


问:
Trying to get Scrapy to work with Pycharm in Windows
I am migrating to Windows, and am desiring to get Scrapy to work with Pycharm.  What I have tried adding:

```<code>from scrapy.cmdline import execute
</code>```

As well as changing - /Library/Python/2.7/site-packages/scrapy/cmdline.py.  It did not like this.

My output looks like this-

https://imgur.com/a/De2jH

I have also tried:

```<code>from scrapy import cmdline
cmdline.execute("scrapy crawl spider".split())
</code>```

As well as setting the "script" parameter to /path_to_project_env/env/bin/scrapy

I get:
"

```<code>*] beginning main thread
Scrapy 1.4.0 - no active project
</code>```

Unknown command: crawl

Use "scrapy" to see available commands

Process finished with exit code 2
"
Though nothing is executed, no website is scraped.

I can run scrapy fine in CMD and in Linux.

It does not want to recognise Scrapy with Windows.

答: I would install scrapy with anaconda, which I find very convenient (even under Windows): conda install scrapy. Hope this helps.

Body:
I am migrating to Windows, and am desiring to get Scrapy to work with Pycharm.  What I have tried adding:

from scrapy.cmdline import execute

As well as changing - /Library/Python/2.7/site-packages/scrapy/cmdline.py.  It did not like this.

My output looks like this-

https://imgur.com/a/De2jH

I have also tried:

from scrapy import cmdline
cmdline.execute("scrapy crawl spider".split())

As well as setting the "script" parameter to /path_to_project_env/env/bin/scrapy

I get:
"

*] beginning main thread
Scrapy 1.4.0 - no active project

Unknown command: crawl

Use "scrapy" to see available commands

Process finished with exit code 2
"
Though nothing is executed, no website is scraped.

I can run scrapy fine in CMD and in Linux.

It does not want to recognise Scrapy with Windows.


问:
swift codable different key in array
I just used Swift 4 Codable to decode my json data from device.
I got a JSON data like below

```<code>{
    "CmdBegin": true,
    "GatewayMac": "1",
    "CmdName": "DevListUpdate",
    "DevItem": [
        {
            "DevMac": "00000000000000B0",
            "DevName": "Software Button",
            "DevAction": [
                {
                    "DevName": "A",
                    "Value": -1000
                },
                {
                    "DevName": "B",
                    "Value": -1000
                }
            ]
        },
        {
            "DevMac": "00000000000000B1",
            "DevName": "Software Button",
            "DevAction": [
                {
                    "DevName": "C",
                    "Value": -1000
                },
                {
                    "DevName": "D",
                    "Value": -1000
                }
            ]
        },
        {
            "DevMac": "00:17:88:01:00:fa:2a:5d-0b",
            "DevName": "E",
            "DevSubItem": [
                {
                    "SubIndex": 0,
                    "Cmdset": 0,
                    "SubStatus": "1"
                },
                {
                    "SubIndex": 1,
                    "Cmdset": 512,
                    "SubStatus": "14"
                }
            ]
        }
    ]
}
</code>```

And I use Swift 4

```<code>    struct DevResults: Codable{
        var CmdBegin: Bool
        var GatewayMac: String
        var CmdName: String
        var CmdEnd: Bool
        var DevItem: [DevList]
    }
    struct DevList: Codable {
        var DevMac: String
        var DevName: String
        var DevAction: [DevActionList]
        var DevSubItem: [DevSubItemList]
    }
    struct DevActionList: Codable{
        var DevMac: String
        var DevName: String
        var DevType: Int
        var DevProtocol: Int
        var ActionIdx: Int
        var Value: Int
    }
    struct DevSubItemList: Codable{
        var SubIndex: Int,
        var Cmdset: Int,
        var SubStatus: String
    }
    let decoder = JSONDecoder()
    if receiveData.contains("DevListUpdate"){
        let data = receiveData.data(using: .utf8)!
        do {
            let locList = try JSONDecoder().decode(DevResults.self, from: data)
            print(locList)
        } catch let error {
            print(error)
        }
    }

}
</code>```

But I cannot the correct JSON format because there are different key in DevItem Array. And I tried to use
var DevItem: Array<Dictionary<String: AnyObject>>

Is there any solution for different key-value JSON file?

答:
Couple of things you missing -

You should make DevSubItem & DevAction properties as Optional

You need to implement init(from decoder: Decoder) throws for
  decoding your JSON

Improved your code -

```<code>     let jsonExample2 = """
{
    "CmdBegin": true,
    "GatewayMac": "1",
    "CmdName": "DevListUpdate",
    "DevItem": [
        {
            "DevMac": "00000000000000B0",
            "DevName": "Software Button",
            "DevAction": [
                {
                    "DevName": "A",
                    "Value": -1000
                },
                {
                    "DevName": "B",
                    "Value": -1000
                }
            ]
        },
        {
            "DevMac": "00000000000000B1",
            "DevName": "Software Button",
            "DevAction": [
                {
                    "DevName": "C",
                    "Value": -1000
                },
                {
                    "DevName": "D",
                    "Value": -1000
                }
            ]
        },
        {
            "DevMac": "00:17:88:01:00:fa:2a:5d-0b",
            "DevName": "E",
            "DevSubItem": [
                {
                    "SubIndex": 0,
                    "Cmdset": 0,
                    "SubStatus": "1"
                },
                {
                    "SubIndex": 1,
                    "Cmdset": 512,
                    "SubStatus": "14"
                }
            ]
        }
    ]
}

""".data(using: .utf8)!
    struct DevResults: Codable{
        var CmdBegin: Bool
        var GatewayMac: String
        var CmdName: String
        var DevItem: [DevList]
    }
    struct DevList: Codable {
        var DevMac: String
        var DevName: String
        var DevAction: [DevActionList]?
        var DevSubItem: [DevSubItemList]?
    }
    struct DevActionList: Codable{
        var DevName: String
        var Value: Int
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            DevName = try values.decode(String.self, forKey: .DevName)
            Value = try values.decode(Int.self, forKey: .Value)
        }
    }
    struct DevSubItemList: Codable{
        var SubIndex: Int
        var Cmdset: Int
        var SubStatus: String
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            SubIndex = try values.decode(Int.self, forKey: .SubIndex)
            Cmdset = try values.decode(Int.self, forKey: .Cmdset)
            SubStatus = try values.decode(String.self, forKey: .SubStatus)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let jsonDecoder = JSONDecoder()
        do {
            let modelResult = try jsonDecoder.decode(DevResults.self,from: jsonExample2)
            if modelResult.DevItem.count > 0 {
                print("dev Name is \(modelResult.DevItem.first?.DevName ?? "-")")
            }

        } catch {
            print(error)
        }
    }
}
</code>```

Apple docs - Using JSON with Custom Types you can also download sample code from apple on that link.

Title: swift codable different key in array

Body:
I just used Swift 4 Codable to decode my json data from device.
I got a JSON data like below

{
    "CmdBegin": true,
    "GatewayMac": "1",
    "CmdName": "DevListUpdate",
    "DevItem": [
        {
            "DevMac": "00000000000000B0",
            "DevName": "Software Button",
            "DevAction": [
                {
                    "DevName": "A",
                    "Value": -1000
                },
                {
                    "DevName": "B",
                    "Value": -1000
                }
            ]
        },
        {
            "DevMac": "00000000000000B1",
            "DevName": "Software Button",
            "DevAction": [
                {
                    "DevName": "C",
                    "Value": -1000
                },
                {
                    "DevName": "D",
                    "Value": -1000
                }
            ]
        },
        {
            "DevMac": "00:17:88:01:00:fa:2a:5d-0b",
            "DevName": "E",
            "DevSubItem": [
                {
                    "SubIndex": 0,
                    "Cmdset": 0,
                    "SubStatus": "1"
                },
                {
                    "SubIndex": 1,
                    "Cmdset": 512,
                    "SubStatus": "14"
                }
            ]
        }
    ]
}

And I use Swift 4

    struct DevResults: Codable{
        var CmdBegin: Bool
        var GatewayMac: String
        var CmdName: String
        var CmdEnd: Bool
        var DevItem: [DevList]
    }
    struct DevList: Codable {
        var DevMac: String
        var DevName: String
        var DevAction: [DevActionList]
        var DevSubItem: [DevSubItemList]
    }
    struct DevActionList: Codable{
        var DevMac: String
        var DevName: String
        var DevType: Int
        var DevProtocol: Int
        var ActionIdx: Int
        var Value: Int
    }
    struct DevSubItemList: Codable{
        var SubIndex: Int,
        var Cmdset: Int,
        var SubStatus: String
    }
    let decoder = JSONDecoder()
    if receiveData.contains("DevListUpdate"){
        let data = receiveData.data(using: .utf8)!
        do {
            let locList = try JSONDecoder().decode(DevResults.self, from: data)
            print(locList)
        } catch let error {
            print(error)
        }
    }

}

But I cannot the correct JSON format because there are different key in DevItem Array. And I tried to use
var DevItem: Array<Dictionary<String: AnyObject>>

Is there any solution for different key-value JSON file?

Body:
Couple of things you missing -

You should make DevSubItem & DevAction properties as Optional

You need to implement init(from decoder: Decoder) throws for
  decoding your JSON

Improved your code -

     let jsonExample2 = """
{
    "CmdBegin": true,
    "GatewayMac": "1",
    "CmdName": "DevListUpdate",
    "DevItem": [
        {
            "DevMac": "00000000000000B0",
            "DevName": "Software Button",
            "DevAction": [
                {
                    "DevName": "A",
                    "Value": -1000
                },
                {
                    "DevName": "B",
                    "Value": -1000
                }
            ]
        },
        {
            "DevMac": "00000000000000B1",
            "DevName": "Software Button",
            "DevAction": [
                {
                    "DevName": "C",
                    "Value": -1000
                },
                {
                    "DevName": "D",
                    "Value": -1000
                }
            ]
        },
        {
            "DevMac": "00:17:88:01:00:fa:2a:5d-0b",
            "DevName": "E",
            "DevSubItem": [
                {
                    "SubIndex": 0,
                    "Cmdset": 0,
                    "SubStatus": "1"
                },
                {
                    "SubIndex": 1,
                    "Cmdset": 512,
                    "SubStatus": "14"
                }
            ]
        }
    ]
}

""".data(using: .utf8)!
    struct DevResults: Codable{
        var CmdBegin: Bool
        var GatewayMac: String
        var CmdName: String
        var DevItem: [DevList]
    }
    struct DevList: Codable {
        var DevMac: String
        var DevName: String
        var DevAction: [DevActionList]?
        var DevSubItem: [DevSubItemList]?
    }
    struct DevActionList: Codable{
        var DevName: String
        var Value: Int
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            DevName = try values.decode(String.self, forKey: .DevName)
            Value = try values.decode(Int.self, forKey: .Value)
        }
    }
    struct DevSubItemList: Codable{
        var SubIndex: Int
        var Cmdset: Int
        var SubStatus: String
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            SubIndex = try values.decode(Int.self, forKey: .SubIndex)
            Cmdset = try values.decode(Int.self, forKey: .Cmdset)
            SubStatus = try values.decode(String.self, forKey: .SubStatus)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let jsonDecoder = JSONDecoder()
        do {
            let modelResult = try jsonDecoder.decode(DevResults.self,from: jsonExample2)
            if modelResult.DevItem.count > 0 {
                print("dev Name is \(modelResult.DevItem.first?.DevName ?? "-")")
            }

        } catch {
            print(error)
        }
    }
}

Apple docs - Using JSON with Custom Types you can also download sample code from apple on that link.


问:
How can I make a label in an iOS renderer wrap around and resize?
I have this code in an iOS Renderer:

```<code>    private class CustomFooterTableViewModelRenderer : TableViewModelRenderer
    {
        public CustomFooterTableViewModelRenderer(TableView model) : base(model)
        {
        }

        public override UIView GetViewForFooter(UITableView tableView, nint section)
        {
                var lbl = new PaddedLabel()
                {

                    // Text = TitleForFooter(tableView, section), // or use some other text here
                    Text = "Select or deselect cards from the list above and they will added or removed from the card deck",
                    TextAlignment = UITextAlignment.Justified,
                    LineBreakMode = UILineBreakMode.WordWrap
                };
                return lbl;
        }

        public sealed class PaddedLabel : UILabel
        {
            private UIEdgeInsets EdgeInsets { get; set; } = new UIEdgeInsets(top: 10, left: 15, bottom: 0, right: 0);

            public override void DrawText(CoreGraphics.CGRect rect)
            {
                var newRect = new CoreGraphics.CGRect(0, 0, rect.Width + 10, rect.Height);
                base.DrawText(EdgeInsets.InsetRect(newRect));
            }
        }

    }
</code>```

The code works but my label does not wrap around and I am guessing it does not resize also  Note that I did try adding WordWrap but that doesn't seem to work. Anyone have any ideas as to how I can fix this and also make it autoresize.

答:
Instead of UILabel, try using 'UITextView` - it's easier to integrate word-wrap with padding/insets.

```<code>private class CustomFooterTableViewModelRenderer : TableViewModelRenderer
{
    public CustomFooterTableViewModelRenderer(TableView model) : base(model)
    {
    }

    public override UIView GetViewForFooter(UITableView tableView, nint section)
    {
        var txtView = new UITextView
        {
            Editable = false,
            Text = "Select or deselect cards from the list above and they will added or removed from the card deck,",
            TextAlignment = UITextAlignment.Justified,
            TextContainerInset = new UIEdgeInsets(top: 10, left: 15, bottom: 5, right: 5),
            BackgroundColor = Color.Transparent.ToUIColor()
        };

        txtView.TextContainer.LineBreakMode = UILineBreakMode.WordWrap;
        return txtView;
    }
}
</code>```

Body:
I have this code in an iOS Renderer:

    private class CustomFooterTableViewModelRenderer : TableViewModelRenderer
    {
        public CustomFooterTableViewModelRenderer(TableView model) : base(model)
        {
        }

        public override UIView GetViewForFooter(UITableView tableView, nint section)
        {
                var lbl = new PaddedLabel()
                {

                    // Text = TitleForFooter(tableView, section), // or use some other text here
                    Text = "Select or deselect cards from the list above and they will added or removed from the card deck",
                    TextAlignment = UITextAlignment.Justified,
                    LineBreakMode = UILineBreakMode.WordWrap
                };
                return lbl;
        }

        public sealed class PaddedLabel : UILabel
        {
            private UIEdgeInsets EdgeInsets { get; set; } = new UIEdgeInsets(top: 10, left: 15, bottom: 0, right: 0);

            public override void DrawText(CoreGraphics.CGRect rect)
            {
                var newRect = new CoreGraphics.CGRect(0, 0, rect.Width + 10, rect.Height);
                base.DrawText(EdgeInsets.InsetRect(newRect));
            }
        }

    }

The code works but my label does not wrap around and I am guessing it does not resize also  Note that I did try adding WordWrap but that doesn't seem to work. Anyone have any ideas as to how I can fix this and also make it autoresize.

Body:
Instead of UILabel, try using 'UITextView` - it's easier to integrate word-wrap with padding/insets.

private class CustomFooterTableViewModelRenderer : TableViewModelRenderer
{
    public CustomFooterTableViewModelRenderer(TableView model) : base(model)
    {
    }

    public override UIView GetViewForFooter(UITableView tableView, nint section)
    {
        var txtView = new UITextView
        {
            Editable = false,
            Text = "Select or deselect cards from the list above and they will added or removed from the card deck,",
            TextAlignment = UITextAlignment.Justified,
            TextContainerInset = new UIEdgeInsets(top: 10, left: 15, bottom: 5, right: 5),
            BackgroundColor = Color.Transparent.ToUIColor()
        };

        txtView.TextContainer.LineBreakMode = UILineBreakMode.WordWrap;
        return txtView;
    }
}


问:
Check for value definedness in C++
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

```<code>class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}
</code>```

Is it possible in C++?

Thanks

答: This is not possible in C/C++, primitives will always a value assigned (mostly garbage, whatever was on that spot in memory before it, unless explicitly assigned at declaration). I's common to have a placeholder value (i.e. 0 for pointers) which denotes not-used, however these have to be explicitly assigned as well. If your double can take on any value, then I suggest you put a boolean next to it, assigned to false initially, and test/set that one when you want to do your calculation.</p>

OwnerDisplayName: Tunnuz

ContentLicense: CC BY-SA 2.5

Title: Check for value definedness in C++

Body:
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}

Is it possible in C++?

Thanks

OwnerDisplayName: roe


问:
Failed to add data to database
im trying to add data to a database, via a form i have created, but i just can't seem to get it to work. Can anyone please help me?

I have included some of the code, which i think is the problem, but also included a pastbin link to all the code.

https://pastebin.com/PpfCvjhf

$user_id = $_POST['user_id'];
            $grafik_name = $_POST['grafik_name'];
            $grafik_coin = $_POST['grafik_coin'];
            $grafik_hashrate = $_POST['grafik_hashrate'];
            $grafik_bios_mod = $_POST['grafik_bios_mod'];
            $grafik_core_clock = $_POST['grafik_core_clock'];
            $grafik_memory_clock = $_POST['grafik_memory_clock'];
            $grafik_power_draw = $_POST['grafik_power_draw'];
            $grafik_additional_info = $_POST['grafik_additional_info'];

            $sql = "INSERT INTO `cards` (`id`, `name`, `coin`, `hashrate`, `bios_mod`, `core_clock`, `memory_clock`, `power_draw`, `additional_info`) VALUES ('$user_id','$grafik_name','$grafik_coin','$grafik_hashrate','$grafik_bios_mod','$grafik_core_clock','$grafik_memory_clock','$grafik_power_draw','$grafik_additional_info', NOW())";

            mysql_select_db('grafik');
            $retval = mysql_query( $sql, $conn );```
</div>
</div>
</p>

```<?php
```

https://pastebin.com/PpfCvjhf

答:
Column count doesn't match value.
The problem is : NOW()) take a look carefully. Remove the NOW())

Your query i think wrong.
The right one is, $sql = "INSERT INTO table_name (column1, column2) VALUES ('$values1', '$values2')";

Title: Failed to add data to database

Body:
im trying to add data to a database, via a form i have created, but i just can't seem to get it to work. Can anyone please help me?

I have included some of the code, which i think is the problem, but also included a pastbin link to all the code.

https://pastebin.com/PpfCvjhf

$user_id = $_POST['user_id'];
            $grafik_name = $_POST['grafik_name'];
            $grafik_coin = $_POST['grafik_coin'];
            $grafik_hashrate = $_POST['grafik_hashrate'];
            $grafik_bios_mod = $_POST['grafik_bios_mod'];
            $grafik_core_clock = $_POST['grafik_core_clock'];
            $grafik_memory_clock = $_POST['grafik_memory_clock'];
            $grafik_power_draw = $_POST['grafik_power_draw'];
            $grafik_additional_info = $_POST['grafik_additional_info'];

            $sql = "INSERT INTO `cards` (`id`, `name`, `coin`, `hashrate`, `bios_mod`, `core_clock`, `memory_clock`, `power_draw`, `additional_info`) VALUES ('$user_id','$grafik_name','$grafik_coin','$grafik_hashrate','$grafik_bios_mod','$grafik_core_clock','$grafik_memory_clock','$grafik_power_draw','$grafik_additional_info', NOW())";

            mysql_select_db('grafik');
            $retval = mysql_query( $sql, $conn );

<?php

https://pastebin.com/PpfCvjhf


问:
iPhone: Cannot access NSManagedObjectContext using appDelegate
I have started with iPhone development sometime back and I am trying to implement core data in my application.

In the process of executing FetchRequest I am stuck at following code...

```<code>MYAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
</code>```

While debugging the following error is displayed...

```<code>Program received signal: "EXC_BAD_ACCESS"
</code>```

When I run the app, it just crashes.

This error appears again and again when I press 'continue' button in debug mode.

I tried changing my code, to this.....

```<code>NSManagedObjectContext *context = [(MyAppDelegate *)[[UIApplication sharedApplication\ delegate] managedObjectContext];
</code>```

This lets the app run but when I press the Simulator home button, the same error is displayed in console.

What could be going wrong over here?

答:
Make sure you have a public accessor method for your application delegate. I would implement it like so, at the top of your AppDelegate.m

```<code>
+ (MYAppDelegate *)sharedAppDelegate
{
    return (MYAppDelegate *) [UIApplication sharedApplication].delegate;
}
</code>```

You may then access it using:

```<code>
[[MYAppDelegate sharedAppDelegate] managedObjectContext]
```

Body:
I have started with iPhone development sometime back and I am trying to implement core data in my application.

In the process of executing FetchRequest I am stuck at following code...

MYAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];

While debugging the following error is displayed...

Program received signal: "EXC_BAD_ACCESS"

When I run the app, it just crashes.

This error appears again and again when I press 'continue' button in debug mode.

I tried changing my code, to this.....

NSManagedObjectContext *context = [(MyAppDelegate *)[[UIApplication sharedApplication\ delegate] managedObjectContext];

This lets the app run but when I press the Simulator home button, the same error is displayed in console.

What could be going wrong over here?

Body:
Make sure you have a public accessor method for your application delegate. I would implement it like so, at the top of your AppDelegate.m

+ (MYAppDelegate *)sharedAppDelegate
{
    return (MYAppDelegate *) [UIApplication sharedApplication].delegate;
}

You may then access it using:

[[MYAppDelegate sharedAppDelegate] managedObjectContext]


问:
Powershell Invoke-Sqlcmd capture verbose output
I'm trying to capture the verbose output from the Invoke-Sqlcmd in Powershell. Anyone got any ideas to do this:

i.e.

```<code>Invoke-Sqlcmd  -Query "PRINT 'Hello World!';" -ServerInstance $Server -verbose  > D:\SqlLog.txt
</code>```

The SqlLog.txt file should contain the text "Hello World!"

答:
For me the below command worked:

```<code>invoke-sqlcmd -inputfile "C:\cfn\scripts\set-tempdb.sql" -Verbose *> "C:\cfn\log\set-tempdb.log"
</code>```

I am using Powershell 5.1 on Windows 2016 With SQL Enterprise 2016

Body:
I'm trying to capture the verbose output from the Invoke-Sqlcmd in Powershell. Anyone got any ideas to do this:

i.e.

Invoke-Sqlcmd  -Query "PRINT 'Hello World!';" -ServerInstance $Server -verbose  > D:\SqlLog.txt

The SqlLog.txt file should contain the text "Hello World!"

Body:
For me the below command worked:

invoke-sqlcmd -inputfile "C:\cfn\scripts\set-tempdb.sql" -Verbose *> "C:\cfn\log\set-tempdb.log"

I am using Powershell 5.1 on Windows 2016 With SQL Enterprise 2016


问:
Angular way to convert HTML-string to text string
Currently I'm using

```<code>htmlToText(html: string) {
    const tmp = document.createElement('DIV');
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText || '';
}
</code>```

for the task. What's the Angular way of doing that? Or is it perfectly fine to do like that? Can directly accessing document like that lead to problems, e.g. with mobile apps?

Note: There's an AngularJS related question, but I'm looking for an Angular2+ anwer. Plus I'm not sure whether the regex from that accepted answer is the way to go?

答:
Create a pipe

```

    import { Pipe, PipeTransform } from '@angular/core';
    @Pipe({name: 'htmlToPlaintext'})
    export class HtmlToPlaintextPipe implements PipeTransform {
      transform(value: string): string {
        return value? value.replace(/]+>/gm, '') : '';
      }
    }

```

and use this pipe in your template

```

    {{yourAttribute | htmlToPlaintext}}

```

In Angular, you should not modify the dom directly from your component. It should always be possible to use the template to achieve what you want.

ContentLicense: CC BY-SA 4.0

Body:
Currently I'm using

htmlToText(html: string) {
    const tmp = document.createElement('DIV');
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText || '';
}

for the task. What's the Angular way of doing that? Or is it perfectly fine to do like that? Can directly accessing document like that lead to problems, e.g. with mobile apps?

Note: There's an AngularJS related question, but I'm looking for an Angular2+ anwer. Plus I'm not sure whether the regex from that accepted answer is the way to go?

Body:
Create a pipe

    import { Pipe, PipeTransform } from '@angular/core';
    @Pipe({name: 'htmlToPlaintext'})
    export class HtmlToPlaintextPipe implements PipeTransform {
      transform(value: string): string {
        return value? value.replace(/]+>/gm, '') : '';
      }
    }

and use this pipe in your template

    {{yourAttribute | htmlToPlaintext}}

In Angular, you should not modify the dom directly from your component. It should always be possible to use the template to achieve what you want.


问:
Detect if the app was launched/opened from a push notification
Is it possible to know if the app was launched/opened from a push notification?

I guess the launching event can be caught here:

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    if (launchOptions != nil) {
         // Launched from push notification
         NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

    }
}
</code>```

However, how can I detect it was opened from a push notification when the app was in background?

答:
I'll start with a state chart that I created for my own use to visualize it more accurately and to consider all other states:
https://docs.google.com/spreadsheets/d/e/2PACX-1vSdKOgo_F1TZwGJBAED4C_7cml0bEATqeL3P9UKpBwASlT6ZkU3iLdZnOZoevkMzOeng7gs31IFhD-L/pubhtml?gid=0&single=true

Using this chart, we can see what is actually required in order to develop a robust notification handling system that works in almost all possible use cases.

Complete solution ↓

Store notification payload in didReceiveRemoteNotification

Clear stored notification in applicationWillEnterForeground and didFinishLaunchingWithOptions

To tackle cases where control Center/ Notification center pulled, you can use a flag willResignActiveCalled and set it to false initially,
Set this to true in applicationWillResignActive method,

In didReceiveRemoteNotification method, save notifications(userInfo) only when willResignActiveCalled is false.

Reset willResignActiveCalled to false in applicationDidEnterBackground and applicationDidBecomeActive method.

Note: A Similar answer is suggested in comments on Eric's answer, however, the state sheet helps in finding all possible scenarios as I did in my app.

Please find the complete code below and comment below if any specific case is not handled:

AppDelegate

```<code>class AppDelegate: UIResponder, UIApplicationDelegate {
  private var willResignActiveCalled = false

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    NotificationUtils.shared.notification = nil
    return true
  }
  func applicationWillResignActive(_ application: UIApplication) {
    willResignActiveCalled = true
  }
  func applicationDidEnterBackground(_ application: UIApplication) {
    willResignActiveCalled = false
  }
  func applicationWillEnterForeground(_ application: UIApplication) {
    NotificationUtils.shared.notification = nil
  }
  func applicationDidBecomeActive(_ application: UIApplication) {
    willResignActiveCalled = false
    NotificationUtils.shared.performActionOnNotification()
  }
  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if !willResignActiveCalled { // Check if app is in inactive by app switcher, control center, or notification center
      NotificationUtils.shared.handleNotification(userInfo: userInfo)
    }
  }
}
</code>```

NotificationUtils : This is where you can write all your code to navigating to different parts of the application, handling Databases(CoreData/Realm) and do all other stuff that needs to be done when a notification is received.

```<code>   class NotificationUtils {
  static let shared = NotificationUtils()
  private init() {}

  var notification : [AnyHashable: Any]?

  func handleNotification(userInfo : [AnyHashable: Any]){
    if UIApplication.shared.applicationState == UIApplicationState.active {
      self.notification = userInfo //Save Payload
      //Show inApp Alert/Banner/Action etc
      // perform immediate action on notification
    }
    else if UIApplication.shared.applicationState == UIApplicationState.inactive{
      self.notification = userInfo
    }
    else if UIApplication.shared.applicationState == UIApplicationState.background{
      //Process notification in background,
      // Update badges, save some data received from notification payload in Databases (CoreData/Realm)
    }
  }

  func performActionOnNotification(){
    // Do all the stuffs like navigating to ViewControllers, updating Badges etc
    defer {
      notification = nil
    }
  }
}
</code>```

Body:
Is it possible to know if the app was launched/opened from a push notification?

I guess the launching event can be caught here:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    if (launchOptions != nil) {
         // Launched from push notification
         NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

    }
}

However, how can I detect it was opened from a push notification when the app was in background?

Body:
I'll start with a state chart that I created for my own use to visualize it more accurately and to consider all other states:
https://docs.google.com/spreadsheets/d/e/2PACX-1vSdKOgo_F1TZwGJBAED4C_7cml0bEATqeL3P9UKpBwASlT6ZkU3iLdZnOZoevkMzOeng7gs31IFhD-L/pubhtml?gid=0&single=true

Using this chart, we can see what is actually required in order to develop a robust notification handling system that works in almost all possible use cases.

Complete solution ↓

Store notification payload in didReceiveRemoteNotification

Clear stored notification in applicationWillEnterForeground and didFinishLaunchingWithOptions

To tackle cases where control Center/ Notification center pulled, you can use a flag willResignActiveCalled and set it to false initially,
Set this to true in applicationWillResignActive method,

In didReceiveRemoteNotification method, save notifications(userInfo) only when willResignActiveCalled is false.

Reset willResignActiveCalled to false in applicationDidEnterBackground and applicationDidBecomeActive method.

Note: A Similar answer is suggested in comments on Eric's answer, however, the state sheet helps in finding all possible scenarios as I did in my app.

Please find the complete code below and comment below if any specific case is not handled:

AppDelegate

class AppDelegate: UIResponder, UIApplicationDelegate {
  private var willResignActiveCalled = false

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    NotificationUtils.shared.notification = nil
    return true
  }
  func applicationWillResignActive(_ application: UIApplication) {
    willResignActiveCalled = true
  }
  func applicationDidEnterBackground(_ application: UIApplication) {
    willResignActiveCalled = false
  }
  func applicationWillEnterForeground(_ application: UIApplication) {
    NotificationUtils.shared.notification = nil
  }
  func applicationDidBecomeActive(_ application: UIApplication) {
    willResignActiveCalled = false
    NotificationUtils.shared.performActionOnNotification()
  }
  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if !willResignActiveCalled { // Check if app is in inactive by app switcher, control center, or notification center
      NotificationUtils.shared.handleNotification(userInfo: userInfo)
    }
  }
}

NotificationUtils : This is where you can write all your code to navigating to different parts of the application, handling Databases(CoreData/Realm) and do all other stuff that needs to be done when a notification is received.

   class NotificationUtils {
  static let shared = NotificationUtils()
  private init() {}

  var notification : [AnyHashable: Any]?

  func handleNotification(userInfo : [AnyHashable: Any]){
    if UIApplication.shared.applicationState == UIApplicationState.active {
      self.notification = userInfo //Save Payload
      //Show inApp Alert/Banner/Action etc
      // perform immediate action on notification
    }
    else if UIApplication.shared.applicationState == UIApplicationState.inactive{
      self.notification = userInfo
    }
    else if UIApplication.shared.applicationState == UIApplicationState.background{
      //Process notification in background,
      // Update badges, save some data received from notification payload in Databases (CoreData/Realm)
    }
  }

  func performActionOnNotification(){
    // Do all the stuffs like navigating to ViewControllers, updating Badges etc
    defer {
      notification = nil
    }
  }
}


问:
Selenium (Java) Get FULL text from shortened displayed on page
I want to get the FULL text of link, that is contained in a page element and retrieve is value possibly with .getText() parameter. Problem is, that on the page there is only part of it displayed followed by "...".

```<code>.getText returns = "http://www.example.com/es_es/spa..."
what I need to get ="http://www.example.com/es_es/spain/legal-notice.html"
</code>```

this is HTML

http://www.example.com/es_es/spa...```

I am able to locate the element, just not to retrieve its full text. I tried .getAttribute("href") but it returns "null".

Thank you!

答:
Try this using xpath :</p>

```<code>WebElement hrefText=driver.findElement(By.xpath("//a[@href='http://www.example.com/es_es/spain/legal-notice.html']"));
String text_hrefText=hrefText.getAttribute("href");
System.out.println(text_hrefText);
</code>```

Body:
I want to get the FULL text of link, that is contained in a page element and retrieve is value possibly with .getText() parameter. Problem is, that on the page there is only part of it displayed followed by "...".

.getText returns = "http://www.example.com/es_es/spa..."
what I need to get ="http://www.example.com/es_es/spain/legal-notice.html"

this is HTML

http://www.example.com/es_es/spa...

I am able to locate the element, just not to retrieve its full text. I tried .getAttribute("href") but it returns "null".

Thank you!

Body:
Try this using xpath :

WebElement hrefText=driver.findElement(By.xpath("//a[@href='http://www.example.com/es_es/spain/legal-notice.html']"));
String text_hrefText=hrefText.getAttribute("href");
System.out.println(text_hrefText);


问:
jquery (this).parent.hasClass giving false positive while in animation
I use CSS animations and jQuery to open multiple flaps on a Calendar. That works great as long as the user waits for an animation to end and then clicks the next one. But the moment an opening animation is still running, and the user already starts the next, the script breaks and my class opend is removed from the .fenster div and window breaking the layout.

Does anybody see where my script is faulty?

$( document ).on("click" , '.flap' , function(){
    if ($(this).parent(".fenster").hasClass("opend")) {
     $(this).removeClass("flap_open" ).addClass("flap_close" );
  $(this).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
      $(this).next().hide();
      $(this).removeClass("flap_close");
      $(this).parent(".fenster").removeClass("opend");
  });
 } else {
     $(this).addClass("flap_open" );
     $(this).parent(".fenster").addClass("opend");
     //$(this).removeClass("flap_close" );
     $(this).next().show();
 }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fenster {
 width: 30%;
 min-width: 130px;
 max-width: 300px;
 border: 1px solid rgba(212, 212, 212, 1);
 position: relative;
    left: 200px;
 z-index: 200;
 cursor: pointer;
}
.opend {
 perspective: 1500px;
 -webkit-perspective: 1500px;
 box-shadow: inset 0px 0px 5px #2e2d2e;
 cursor: auto;
 -webkit-backface-visibility: hidden;
}
.flap {
 width: 100%;
 height: 100%;
 z-index: 100;
  background-color: red;
}
.flap:before {
 content: "";
 display: block;
 padding-top: 75%;
}
.flap_open {
 transform-origin: 0 50%;
 -webkit-transform-origin: 0 50%;
 background-size: cover;
 width: 100%;
 height: 100%;
 z-index: 100;
 cursor: alias;
 animation: turn 4s forwards;
 -webkit-animation: turn 4s forwards;
 box-shadow:  5px 0px 5px 0px #2e2d2e;
}
.flap_close {
 transform-origin: 0 50%;
 -webkit-transform-origin: 0 50%;
 -webkit-animation: zumachen 4s forwards;
 animation: zumachen 4s forwards;
 opacity: 0.8;
 box-shadow:  5px 0px 5px 0px #2e2d2e;
 transform: rotateY(-100deg);
}
.button{
 position: absolute;
 bottom: 2%;
 left: 15%;
 width: 70%;
 height: 5vh;
 min-width: 80px;
 min-height: 28px;
 max-height: 20px;
 z-index: -1;
 text-align: center;
 display: table;
  background-color: grey;
}
@keyframes turn {
  to {
  transform: rotateY(-100deg);
  opacity: 0.8;
  box-shadow:  5px 0px 5px 0px #2e2d2e;
  visibility: visible;
  }
}
@-webkit-keyframes turn {
  to {
  -webkit-transform: rotateY(-100deg);
  -webkit-opacity: 0.8;
  box-shadow:  5px 0px 5px 0px #2e2d2e;
  visibility: visible;
  }
}
@keyframes zumachen {
  to {
  transform: rotateY(0deg);
  opacity: 1;
  box-shadow:  none;
  visibility: visible;
  }
}
@-webkit-keyframes zumachen {
  to {
  -webkit-transform: rotateY(0deg);
  -webkit-opacity: 1;
  box-shadow:  none;
  visibility: visible;
  }
}</code>```

Something

Something

```

答:
If you add a class indicating the animation is running, you can then run a check to make sure that any currently animating element will not be affected by the .removeClass() method called on any closing element.

Add a class to the animating element, indicating that it is in
animation

With an additional .one() method to the else code block of your initial
conditional statement you can remove this aforementioned class again
once the animation has completed

Insert another conditional check in the first .one() method of
your initial conditional check to verify that the element in
question has no class .animation-running, therefore indicating
that it should have the necessary classes removed.

$(document).on("click", ".flap", function() {
  if ($(this).parent(".fenster").hasClass("opend")) {
    $(this).removeClass("flap_open").addClass("flap_close");
    $(this).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
      if (!$(this).parent(".fenster").hasClass("animation-running")) {
        /* only step into next code block if condition is equal to true,
         * i.e: parent does not have the class "animation-running", so animation is completed
         */
        $(this).next().hide();
        $(this).removeClass("flap_close");
        $(this).parent(".fenster").removeClass("opend");
      }
    });
  } else {
    $(this).addClass("flap_open");
    $(this).parent(".fenster").addClass("opend animation-running"); /* Additional class to indicate animation is running */
    $(this).next().show();
    /* Only once animation has completed should the indicating class be removed */
    $(this).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
      $(this).parent(".fenster").removeClass("animation-running");
    });
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fenster {
  width: 30%;
  min-width: 130px;
  max-width: 300px;
  border: 1px solid rgba(212, 212, 212, 1);
  position: relative;
  left: 200px;
  z-index: 200;
  cursor: pointer;
}

.opend {
  perspective: 1500px;
  -webkit-perspective: 1500px;
  box-shadow: inset 0px 0px 5px #2e2d2e;
  cursor: auto;
  -webkit-backface-visibility: hidden;
}

.flap {
  width: 100%;
  height: 100%;
  z-index: 100;
  background-color: red;
}

.flap:before {
  content: "";
  display: block;
  padding-top: 75%;
}

.flap_open {
  transform-origin: 0 50%;
  -webkit-transform-origin: 0 50%;
  background-size: cover;
  width: 100%;
  height: 100%;
  z-index: 100;
  cursor: alias;
  animation: turn 4s forwards;
  -webkit-animation: turn 4s forwards;
  box-shadow: 5px 0px 5px 0px #2e2d2e;
}

.flap_close {
  transform-origin: 0 50%;
  -webkit-transform-origin: 0 50%;
  -webkit-animation: zumachen 4s forwards;
  animation: zumachen 4s forwards;
  opacity: 0.8;
  box-shadow: 5px 0px 5px 0px #2e2d2e;
  transform: rotateY(-100deg);
}

.button {
  position: absolute;
  bottom: 2%;
  left: 15%;
  width: 70%;
  height: 5vh;
  min-width: 80px;
  min-height: 28px;
  max-height: 20px;
  z-index: -1;
  text-align: center;
  display: table;
  background-color: grey;
}

@keyframes turn {
  to {
    transform: rotateY(-100deg);
    opacity: 0.8;
    box-shadow: 5px 0px 5px 0px #2e2d2e;
    visibility: visible;
  }
}

@-webkit-keyframes turn {
  to {
    -webkit-transform: rotateY(-100deg);
    -webkit-opacity: 0.8;
    box-shadow: 5px 0px 5px 0px #2e2d2e;
    visibility: visible;
  }
}

@keyframes zumachen {
  to {
    transform: rotateY(0deg);
    opacity: 1;
    box-shadow: none;
    visibility: visible;
  }
}

@-webkit-keyframes zumachen {
  to {
    -webkit-transform: rotateY(0deg);
    -webkit-opacity: 1;
    box-shadow: none;
    visibility: visible;
  }
}</code>```

Something

Something

```

Body:
I use CSS animations and jQuery to open multiple flaps on a Calendar. That works great as long as the user waits for an animation to end and then clicks the next one. But the moment an opening animation is still running, and the user already starts the next, the script breaks and my class opend is removed from the .fenster div and window breaking the layout.

Does anybody see where my script is faulty?

$( document ).on("click" , '.flap' , function(){
    if ($(this).parent(".fenster").hasClass("opend")) {
     $(this).removeClass("flap_open" ).addClass("flap_close" );
  $(this).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
      $(this).next().hide();
      $(this).removeClass("flap_close");
      $(this).parent(".fenster").removeClass("opend");
  });
 } else {
     $(this).addClass("flap_open" );
     $(this).parent(".fenster").addClass("opend");
     //$(this).removeClass("flap_close" );
     $(this).next().show();
 }
});

.fenster {
 width: 30%;
 min-width: 130px;
 max-width: 300px;
 border: 1px solid rgba(212, 212, 212, 1);
 position: relative;
    left: 200px;
 z-index: 200;
 cursor: pointer;
}
.opend {
 perspective: 1500px;
 -webkit-perspective: 1500px;
 box-shadow: inset 0px 0px 5px #2e2d2e;
 cursor: auto;
 -webkit-backface-visibility: hidden;
}
.flap {
 width: 100%;
 height: 100%;
 z-index: 100;
  background-color: red;
}
.flap:before {
 content: "";
 display: block;
 padding-top: 75%;
}
.flap_open {
 transform-origin: 0 50%;
 -webkit-transform-origin: 0 50%;
 background-size: cover;
 width: 100%;
 height: 100%;
 z-index: 100;
 cursor: alias;
 animation: turn 4s forwards;
 -webkit-animation: turn 4s forwards;
 box-shadow:  5px 0px 5px 0px #2e2d2e;
}
.flap_close {
 transform-origin: 0 50%;
 -webkit-transform-origin: 0 50%;
 -webkit-animation: zumachen 4s forwards;
 animation: zumachen 4s forwards;
 opacity: 0.8;
 box-shadow:  5px 0px 5px 0px #2e2d2e;
 transform: rotateY(-100deg);
}
.button{
 position: absolute;
 bottom: 2%;
 left: 15%;
 width: 70%;
 height: 5vh;
 min-width: 80px;
 min-height: 28px;
 max-height: 20px;
 z-index: -1;
 text-align: center;
 display: table;
  background-color: grey;
}
@keyframes turn {
  to {
  transform: rotateY(-100deg);
  opacity: 0.8;
  box-shadow:  5px 0px 5px 0px #2e2d2e;
  visibility: visible;
  }
}
@-webkit-keyframes turn {
  to {
  -webkit-transform: rotateY(-100deg);
  -webkit-opacity: 0.8;
  box-shadow:  5px 0px 5px 0px #2e2d2e;
  visibility: visible;
  }
}
@keyframes zumachen {
  to {
  transform: rotateY(0deg);
  opacity: 1;
  box-shadow:  none;
  visibility: visible;
  }
}
@-webkit-keyframes zumachen {
  to {
  -webkit-transform: rotateY(0deg);
  -webkit-opacity: 1;
  box-shadow:  none;
  visibility: visible;
  }
}

Something

Something

Body:
If you add a class indicating the animation is running, you can then run a check to make sure that any currently animating element will not be affected by the .removeClass() method called on any closing element.

Add a class to the animating element, indicating that it is in
animation

With an additional .one() method to the else code block of your initial
conditional statement you can remove this aforementioned class again
once the animation has completed

Insert another conditional check in the first .one() method of
your initial conditional check to verify that the element in
question has no class .animation-running, therefore indicating
that it should have the necessary classes removed.

$(document).on("click", ".flap", function() {
  if ($(this).parent(".fenster").hasClass("opend")) {
    $(this).removeClass("flap_open").addClass("flap_close");
    $(this).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
      if (!$(this).parent(".fenster").hasClass("animation-running")) {
        /* only step into next code block if condition is equal to true,
         * i.e: parent does not have the class "animation-running", so animation is completed
         */
        $(this).next().hide();
        $(this).removeClass("flap_close");
        $(this).parent(".fenster").removeClass("opend");
      }
    });
  } else {
    $(this).addClass("flap_open");
    $(this).parent(".fenster").addClass("opend animation-running"); /* Additional class to indicate animation is running */
    $(this).next().show();
    /* Only once animation has completed should the indicating class be removed */
    $(this).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
      $(this).parent(".fenster").removeClass("animation-running");
    });
  }
});

.fenster {
  width: 30%;
  min-width: 130px;
  max-width: 300px;
  border: 1px solid rgba(212, 212, 212, 1);
  position: relative;
  left: 200px;
  z-index: 200;
  cursor: pointer;
}

.opend {
  perspective: 1500px;
  -webkit-perspective: 1500px;
  box-shadow: inset 0px 0px 5px #2e2d2e;
  cursor: auto;
  -webkit-backface-visibility: hidden;
}

.flap {
  width: 100%;
  height: 100%;
  z-index: 100;
  background-color: red;
}

.flap:before {
  content: "";
  display: block;
  padding-top: 75%;
}

.flap_open {
  transform-origin: 0 50%;
  -webkit-transform-origin: 0 50%;
  background-size: cover;
  width: 100%;
  height: 100%;
  z-index: 100;
  cursor: alias;
  animation: turn 4s forwards;
  -webkit-animation: turn 4s forwards;
  box-shadow: 5px 0px 5px 0px #2e2d2e;
}

.flap_close {
  transform-origin: 0 50%;
  -webkit-transform-origin: 0 50%;
  -webkit-animation: zumachen 4s forwards;
  animation: zumachen 4s forwards;
  opacity: 0.8;
  box-shadow: 5px 0px 5px 0px #2e2d2e;
  transform: rotateY(-100deg);
}

.button {
  position: absolute;
  bottom: 2%;
  left: 15%;
  width: 70%;
  height: 5vh;
  min-width: 80px;
  min-height: 28px;
  max-height: 20px;
  z-index: -1;
  text-align: center;
  display: table;
  background-color: grey;
}

@keyframes turn {
  to {
    transform: rotateY(-100deg);
    opacity: 0.8;
    box-shadow: 5px 0px 5px 0px #2e2d2e;
    visibility: visible;
  }
}

@-webkit-keyframes turn {
  to {
    -webkit-transform: rotateY(-100deg);
    -webkit-opacity: 0.8;
    box-shadow: 5px 0px 5px 0px #2e2d2e;
    visibility: visible;
  }
}

@keyframes zumachen {
  to {
    transform: rotateY(0deg);
    opacity: 1;
    box-shadow: none;
    visibility: visible;
  }
}

@-webkit-keyframes zumachen {
  to {
    -webkit-transform: rotateY(0deg);
    -webkit-opacity: 1;
    box-shadow: none;
    visibility: visible;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fenster f7 p3">
  <div class="flap"></div>
  <div class="button" style="display: none;"><span>Something</span></div>
</div>
<div class="fenster f3 p1">
  <div class="flap"></div>
  <div class="button" style="display: none;"><span>Something</span></div>
</div>


问:
Opening a TCP connection in Windows Phone 7
As the current version of the SDK doesn't support Socket class.

Is is possible to open a TCP connection?

I cannot see the point of using WCF to make a typical client/server scenario.

答: WCF with Windows Phone 7 is done by way of basicHttpBinding.</p>


问:
UInt8 Array Swift to const char* C
I have the following function

```<code>public func encryptWithRSAKey(_ data: String, rsaKeyRef: SecKey, padding: SecPadding) -> [UInt8]? {

    let blockSize = SecKeyGetBlockSize(rsaKeyRef)
    var messageEncrypted = [UInt8](repeating: 0, count: blockSize)
    var messageEncryptedSize = blockSize

    var status: OSStatus!

    status = SecKeyEncrypt(rsaKeyRef, SecPadding.OAEP, data, data.count, &messageEncrypted, &messageEncryptedSize)

    if status != noErr {
        print("\(logClassName): Encryption Error!")
    }

    return messageEncrypted

}
</code>```

the output is encryptedMessage = [9,43,128...] 128 length

and I have to send the result into a C function

```<code>void STDCALL CpProxyAvOpenhomeOrgCredentials1BeginSet(THandle aHandle, const char* aId, const char* aUserName, const char* aPassword, uint32_t aPasswordLen, OhNetCallbackAsync aCallback, void* aPtr)
{
    CpProxyAvOpenhomeOrgCredentials1C* proxyC = reinterpret_cast<CpProxyAvOpenhomeOrgCredentials1C*>(aHandle);
    ASSERT(proxyC != NULL);
    Brh buf_aId(aId);
    Brh buf_aUserName(aUserName);
    Brh buf_aPassword;
    buf_aPassword.Set((const TByte*)aPassword, aPasswordLen);
    FunctorAsync functor = MakeFunctorAsync(aPtr, (OhNetFunctorAsync)aCallback);
    proxyC->BeginSet(buf_aId, buf_aUserName, buf_aPassword, functor);
}
</code>```

What is the way for encoding messageEncrypted in swift to const char* aPassword in C

答:
I prefer this approach:

If I have:

```<code>let uint8ArrayVar:[UInt8]= [0,3,4,5]
</code>```

If i want to sent it throught my c function I just do:

```<code>cfunc(uint8ArrayVar.map { Int8(bitPattern: $0) })
</code>```

Title: UInt8 Array Swift to const char* C

Body:
I have the following function

public func encryptWithRSAKey(_ data: String, rsaKeyRef: SecKey, padding: SecPadding) -> [UInt8]? {

    let blockSize = SecKeyGetBlockSize(rsaKeyRef)
    var messageEncrypted = [UInt8](repeating: 0, count: blockSize)
    var messageEncryptedSize = blockSize

    var status: OSStatus!

    status = SecKeyEncrypt(rsaKeyRef, SecPadding.OAEP, data, data.count, &messageEncrypted, &messageEncryptedSize)

    if status != noErr {
        print("\(logClassName): Encryption Error!")
    }

    return messageEncrypted

}

the output is encryptedMessage = [9,43,128...] 128 length

and I have to send the result into a C function

void STDCALL CpProxyAvOpenhomeOrgCredentials1BeginSet(THandle aHandle, const char* aId, const char* aUserName, const char* aPassword, uint32_t aPasswordLen, OhNetCallbackAsync aCallback, void* aPtr)
{
    CpProxyAvOpenhomeOrgCredentials1C* proxyC = reinterpret_cast<CpProxyAvOpenhomeOrgCredentials1C*>(aHandle);
    ASSERT(proxyC != NULL);
    Brh buf_aId(aId);
    Brh buf_aUserName(aUserName);
    Brh buf_aPassword;
    buf_aPassword.Set((const TByte*)aPassword, aPasswordLen);
    FunctorAsync functor = MakeFunctorAsync(aPtr, (OhNetFunctorAsync)aCallback);
    proxyC->BeginSet(buf_aId, buf_aUserName, buf_aPassword, functor);
}

What is the way for encoding messageEncrypted in swift to const char* aPassword in C

Body:
I prefer this approach:

If I have:

let uint8ArrayVar:[UInt8]= [0,3,4,5]

If i want to sent it throught my c function I just do:

cfunc(uint8ArrayVar.map { Int8(bitPattern: $0) })


问:
Laravel auto translate $request
I have two table in my database. The first is industry and the second is industry_languages.

Industry's table

```<code>Schema::create('industries', function (Blueprint $table) {
        $table->increments('id');
        $table->string('industry_name', 100);
        $table->integer('language_id')->default(1);
        $table->timestamps();
    });
</code>```

Industry_Languages' table

```<code>Schema::create('industry_languages', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('industry_id');
        $table->string('industry_name', 200);
        $table->integer('language_id');
        $table->timestamps();
    });
</code>```

This is my IndustryController

```<code>public function store(Request $request)
{
    $industry = new Industry();
    $industry->industry_name = $request->industryName;
    $industry->save();

    return response()->json($industry);
}
</code>```

This function will only store data into industry's table with language id = 1, but I also want to store it into industry_languages' table with language id = 2 (because I have a language's table in my database with 2 row data: 'Indonesia', 'English')

Example: If I input 'Halo' in the industry_name field, It will store into my industry's table as 'Halo' in the industry_name field and '1' in the language_id field, then It will also store into my industry_languages' table as 'Hello' in the industry_name field and '2' in the language_id field

I have a problem with translating the request from the industry's table.
I have tried to use Laravel google-translate but, it didn't work

答:
Have you tried using https://github.com/spatie/laravel-translatable ?

Using laravel-translatable you could do something like

```<code>public function store(Request $request)
{
    $industry = new Industry();
    $industry
    ->setTranslation('industryName', 'en', 'Hello')
    ->setTranslation('industryName', 'es', $request->get('industryName'));

    $industry->save();

    return response()->json($industry);
}
</code>```

For the other languages you might need to use a translator package

Title: Laravel auto translate $request

Body:
I have two table in my database. The first is industry and the second is industry_languages.

Industry's table

Schema::create('industries', function (Blueprint $table) {
        $table->increments('id');
        $table->string('industry_name', 100);
        $table->integer('language_id')->default(1);
        $table->timestamps();
    });

Industry_Languages' table

Schema::create('industry_languages', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('industry_id');
        $table->string('industry_name', 200);
        $table->integer('language_id');
        $table->timestamps();
    });

This is my IndustryController

public function store(Request $request)
{
    $industry = new Industry();
    $industry->industry_name = $request->industryName;
    $industry->save();

    return response()->json($industry);
}

This function will only store data into industry's table with language id = 1, but I also want to store it into industry_languages' table with language id = 2 (because I have a language's table in my database with 2 row data: 'Indonesia', 'English')

Example: If I input 'Halo' in the industry_name field, It will store into my industry's table as 'Halo' in the industry_name field and '1' in the language_id field, then It will also store into my industry_languages' table as 'Hello' in the industry_name field and '2' in the language_id field

I have a problem with translating the request from the industry's table.
I have tried to use Laravel google-translate but, it didn't work

Body:
Have you tried using https://github.com/spatie/laravel-translatable ?

Using laravel-translatable you could do something like

public function store(Request $request)
{
    $industry = new Industry();
    $industry
    ->setTranslation('industryName', 'en', 'Hello')
    ->setTranslation('industryName', 'es', $request->get('industryName'));

    $industry->save();

    return response()->json($industry);
}

For the other languages you might need to use a translator package


问:
Get end of the day today in MySQL to compare against
I have this query:

```<code>CASE
WHEN NOW() < `Rank`.`StartDate` THEN "Pending"
WHEN NOW() > `Rank`.`StartDate` && NOW() < `Rank`.`EndDate` THEN "Active"
WHEN NOW() > `Rank`.`EndDate` THEN "Expired"
ELSE "Invalid"
END
</code>```

Now the problem is in this line:

```<code>WHEN NOW() > `Rank`.`EndDate` THEN "Expired"
</code>```

And the value of EndDate is like 2017-11-16 00:00:00. Now this will return Expired based on this value, but how do I write it so, that it will return Expired after NOW() = 2017-11-16 23:59:59.

答:
You could use the date function to only compare the date part and ignore the time of day:

```<code>CASE
WHEN DATE(NOW()) < `Rank`.`StartDate`
     THEN "Pending"
WHEN DATE(NOW()) >= `Rank`.`StartDate` && DATE(NOW()) <= `Rank`.`EndDate`
     THEN "Active"
WHEN DATE(NOW()) > `Rank`.`EndDate`
     THEN "Expired"
ELSE "Invalid"
END
</code>```

Body:
I have this query:

CASE
WHEN NOW() < `Rank`.`StartDate` THEN "Pending"
WHEN NOW() > `Rank`.`StartDate` && NOW() < `Rank`.`EndDate` THEN "Active"
WHEN NOW() > `Rank`.`EndDate` THEN "Expired"
ELSE "Invalid"
END

Now the problem is in this line:

WHEN NOW() > `Rank`.`EndDate` THEN "Expired"

And the value of EndDate is like 2017-11-16 00:00:00. Now this will return Expired based on this value, but how do I write it so, that it will return Expired after NOW() = 2017-11-16 23:59:59.

Body:
You could use the date function to only compare the date part and ignore the time of day:

CASE
WHEN DATE(NOW()) < `Rank`.`StartDate`
     THEN "Pending"
WHEN DATE(NOW()) >= `Rank`.`StartDate` && DATE(NOW()) <= `Rank`.`EndDate`
     THEN "Active"
WHEN DATE(NOW()) > `Rank`.`EndDate`
     THEN "Expired"
ELSE "Invalid"
END


问:
How to get started on making a custom payment system using PHP?
Let's say, for the sake of discussion, my client does not want to use the Paypal api for transactions. I have already made a shopping cart. The user submits the items on the shopping cart and their credit card number. </p>

<p>Assuming I'm not using any api, how would I then charge the user's credit card for the items on the shopping cart? I understand that it is complex, just wondering what the general process is like and how to get started. </p>

答: Payum efficiency proved by 1k+ stars on a GitHub, great comments and a million of downloads. Supports 50+ different payment gateways so you surely find what you need. </p>

Body:
Let's say, for the sake of discussion, my client does not want to use the Paypal api for transactions. I have already made a shopping cart. The user submits the items on the shopping cart and their credit card number.

Assuming I'm not using any api, how would I then charge the user's credit card for the items on the shopping cart? I understand that it is complex, just wondering what the general process is like and how to get started.


问:
Scalable seeding for Sequelize with Node.js?
I want to set up a piece of code that resets my whole database and seeds everything.

The problem is that with a few Foreign Key constraints, the seeds need to happen in order, however those seeds that are not dependent should happen at the same time asynchronously.

How can I define these seeds in separate files properly?

答:
The problem comes down to exporting Promises with module.exports.

When I was requiring a file that returned a Promise directly, the Promise was immediately called.

I solved the problem by returning functions that return the Promise.

Resetting DB and seeding

const Seed = require('../seeds/index');

sequelize.sync({ force: true }).then(() => {
    return Seed();
}).then(() => {
    // DB reset
}).catch(err => {
    // Error in one of the seeds, specific error in 'err'
});
```

<p><br></p>

<p><code>seeds/index.js</code> - Calling the seeds in other files</p>

<pre class="lang-js prettyprint-override"><code>const UserSeed = require('./user');
const BComponentSeed = require('./bcomponent');
const MaterialSeed = require('./material');

module.exports = function() {
    return Promise.all([ // Returning and thus passing a Promise here
        // Independent seeds first
        UserSeed(),
        BComponentSeed(),
        MaterialSeed(),
    ]).then(() => {
        // More seeds that require IDs from the seeds above
    }).then(() => {
        console.log('********** Successfully seeded db **********');
    });
}
</code>```

seeds/user.js - Example of the User seed

const User = require('../models/user');
const crypto = require('../globs/crypto');

module.exports = function() {
    return User.bulkCreate([ // Returning and thus passing a Promise here
        {
            email: 'John@doe.com',
            password: crypto.generateHash('john'),
        },
        {
            email: 'a@a.com',
            password: crypto.generateHash('a'),
        },
    ]);
};
```

Came up with this while responding to this GitHub issue

Body:
The problem comes down to exporting Promises with module.exports.

When I was requiring a file that returned a Promise directly, the Promise was immediately called.

I solved the problem by returning functions that return the Promise.

Resetting DB and seeding

const Seed = require('../seeds/index');

sequelize.sync({ force: true }).then(() => {
    return Seed();
}).then(() => {
    // DB reset
}).catch(err => {
    // Error in one of the seeds, specific error in 'err'
});

seeds/index.js - Calling the seeds in other files

const UserSeed = require('./user');
const BComponentSeed = require('./bcomponent');
const MaterialSeed = require('./material');

module.exports = function() {
    return Promise.all([ // Returning and thus passing a Promise here
        // Independent seeds first
        UserSeed(),
        BComponentSeed(),
        MaterialSeed(),
    ]).then(() => {
        // More seeds that require IDs from the seeds above
    }).then(() => {
        console.log('********** Successfully seeded db **********');
    });
}

seeds/user.js - Example of the User seed

const User = require('../models/user');
const crypto = require('../globs/crypto');

module.exports = function() {
    return User.bulkCreate([ // Returning and thus passing a Promise here
        {
            email: 'John@doe.com',
            password: crypto.generateHash('john'),
        },
        {
            email: 'a@a.com',
            password: crypto.generateHash('a'),
        },
    ]);
};

Came up with this while responding to this GitHub issue


问:
JUnit testing a comprehensive method
I have a single method which is really comprehensive. Within this method couple of other methods are called and each method depends on the previous one.

My question is: What is the best approach to test this complex method using JUnit?

Can I just create one single @Test Method and calling the other methods within this method? For example:

```<code>@Test
public void testRun(){
    testMethod1();
    testMethod2();
    ...
}

testMethod1(){
assertNotEquals();
...
}
</code>```

I can´t believe that it is that easy. Wouldn´t it be better to test each method on their own? But how can I implement that? Are their any best practises?

But maybe this is the right way.

Thanks for any suggestions !:)

答:
You have to refactor the comprehensive method first.

You've implied that the inner methods depend on each-other. That ussually means they share and update the same 'state'.

Try to extract this state into an object, and use this object as a parameter of each inner method.

This will allow you to test the inner methods seperately.

Title: JUnit testing a comprehensive method

Body:
I have a single method which is really comprehensive. Within this method couple of other methods are called and each method depends on the previous one.

My question is: What is the best approach to test this complex method using JUnit?

Can I just create one single @Test Method and calling the other methods within this method? For example:

@Test
public void testRun(){
    testMethod1();
    testMethod2();
    ...
}

testMethod1(){
assertNotEquals();
...
}

I can´t believe that it is that easy. Wouldn´t it be better to test each method on their own? But how can I implement that? Are their any best practises?

But maybe this is the right way.

Thanks for any suggestions !:)


答:
What you need to do is escape these characters, then you archive what you want:

```<code>" replace with "
& replace with &
< replace with <
> replace with >
</code>```

more about escape characters

XML / HTML / XHTML or any SGML derivat will not parse these characters as what they intended for.

Title: Angular way to convert HTML-string to text string

Body:
Currently I'm using

htmlToText(html: string) {
    const tmp = document.createElement('DIV');
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText || '';
}

for the task. What's the Angular way of doing that? Or is it perfectly fine to do like that? Can directly accessing document like that lead to problems, e.g. with mobile apps?

Note: There's an AngularJS related question, but I'm looking for an Angular2+ anwer. Plus I'm not sure whether the regex from that accepted answer is the way to go?

Body:
What you need to do is escape these characters, then you archive what you want:

" replace with &quot;
& replace with &amp;
< replace with &lt;
> replace with &gt;

more about escape characters

XML / HTML / XHTML or any SGML derivat will not parse these characters as what they intended for.


问:
Keras: ValueError: Negative dimension size caused by subtracting 5 from 1
When I try to define my model, I get the following error message: ValueError: Negative dimension size caused by subtracting 5 from 1 for 'conv2d_19/convolution' (op: 'Conv2D') with input shapes: [?,1,1,32], [5,5,32,64].

Here is a code snippet to reproduce the issue:

```<code>from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D, AveragePooling2D
import numpy as np

nb_filters = 32
batch_size = 128
epochs = 5
nb_classes = 10

pool_size = (3, 3)
kernel_size = (5, 5)

img_rows = 32
img_cols = 32

input_shape = (img_rows, img_cols, 1)

model = Sequential()
model.add(Convolution2D(nb_filters, kernel_size,
                        input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Convolution2D(nb_filters, kernel_size))
model.add(Activation('relu'))
model.add(AveragePooling2D(pool_size=pool_size))
model.add(Convolution2D(nb_filters*2, kernel_size))
model.add(Activation('relu'))
model.add(AveragePooling2D(pool_size=pool_size))
model.add(Flatten())
model.add(Dense(nb_classes))
model.add(Activation('softmax'))
</code>```

The issue has been observed on MacOS, with Python 2.7.11 and Keras 2.1.1.

Is there something wrong in the way I build my model?

Here is the architecture I want to build:

Convolutional layer with 32 filters of size 5 × 5, max-pooling over 3 × 3 regions, and ReLU activations

Convolutional layer with 32 filters of size 5 × 5, ReLU activations, and average-pooling over 3 × 3 regions

Convolutional layer with 64 filters of size 5 × 5, ReLU activations, and average-pooling over 3 × 3 regions

Fully connected layer with softmax.

答:
You're input shape is simply to small for all the pooling that is applied in your model.

Let's have a look at your model:

```<code>model = Sequential()
model.add(Convolution2D(nb_filters, kernel_size, input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Convolution2D(nb_filters, kernel_size))
model.add(Activation('relu'))
model.add(AveragePooling2D(pool_size=pool_size))
</code>```

Until here everything is fine. The output shape of the AveragePooling2D layer is (1, 1, 32).

```<code>_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_1 (Conv2D)            (None, 28, 28, 32)        832
_________________________________________________________________
activation_1 (Activation)    (None, 28, 28, 32)        0
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 9, 9, 32)          0
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 5, 5, 32)          25632
_________________________________________________________________
activation_2 (Activation)    (None, 5, 5, 32)          0
_________________________________________________________________
average_pooling2d_1 (Average (None, 1, 1, 32)          0
=================================================================
</code>```

Now you want to apply another Convolution2D layer with a kernel size of 3, altough the output of the last layer is just (1, 1, 32). So you want to learn a kernel of size (3, 3) that is actually smaller than the data you want to learn it on.

Now you can either increase the input shape of your data ((79, 79, ?) is the smallest that works for your model) or you change your model.

Decrease the pool size

Apply a padding by adding padding='same' to your convolutional layer

Cut down yout model

Cheers

Body:
When I try to define my model, I get the following error message: ValueError: Negative dimension size caused by subtracting 5 from 1 for 'conv2d_19/convolution' (op: 'Conv2D') with input shapes: [?,1,1,32], [5,5,32,64].

Here is a code snippet to reproduce the issue:

from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D, AveragePooling2D
import numpy as np

nb_filters = 32
batch_size = 128
epochs = 5
nb_classes = 10

pool_size = (3, 3)
kernel_size = (5, 5)

img_rows = 32
img_cols = 32

input_shape = (img_rows, img_cols, 1)

model = Sequential()
model.add(Convolution2D(nb_filters, kernel_size,
                        input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Convolution2D(nb_filters, kernel_size))
model.add(Activation('relu'))
model.add(AveragePooling2D(pool_size=pool_size))
model.add(Convolution2D(nb_filters*2, kernel_size))
model.add(Activation('relu'))
model.add(AveragePooling2D(pool_size=pool_size))
model.add(Flatten())
model.add(Dense(nb_classes))
model.add(Activation('softmax'))

The issue has been observed on MacOS, with Python 2.7.11 and Keras 2.1.1.

Is there something wrong in the way I build my model?

Here is the architecture I want to build:

Convolutional layer with 32 filters of size 5 × 5, max-pooling over 3 × 3 regions, and ReLU activations

Convolutional layer with 32 filters of size 5 × 5, ReLU activations, and average-pooling over 3 × 3 regions

Convolutional layer with 64 filters of size 5 × 5, ReLU activations, and average-pooling over 3 × 3 regions

Fully connected layer with softmax.

Body:
You're input shape is simply to small for all the pooling that is applied in your model.

Let's have a look at your model:

model = Sequential()
model.add(Convolution2D(nb_filters, kernel_size, input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Convolution2D(nb_filters, kernel_size))
model.add(Activation('relu'))
model.add(AveragePooling2D(pool_size=pool_size))

Until here everything is fine. The output shape of the AveragePooling2D layer is (1, 1, 32).

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_1 (Conv2D)            (None, 28, 28, 32)        832
_________________________________________________________________
activation_1 (Activation)    (None, 28, 28, 32)        0
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 9, 9, 32)          0
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 5, 5, 32)          25632
_________________________________________________________________
activation_2 (Activation)    (None, 5, 5, 32)          0
_________________________________________________________________
average_pooling2d_1 (Average (None, 1, 1, 32)          0
=================================================================

Now you want to apply another Convolution2D layer with a kernel size of 3, altough the output of the last layer is just (1, 1, 32). So you want to learn a kernel of size (3, 3) that is actually smaller than the data you want to learn it on.

Now you can either increase the input shape of your data ((79, 79, ?) is the smallest that works for your model) or you change your model.

Decrease the pool size

Apply a padding by adding padding='same' to your convolutional layer

Cut down yout model

Cheers


问:
mmapping /dev/zero on Mac OSX gives invalid argument
So I am trying to port some code from Linux to Mac OSX. During porting I came across this code.

```<code>static void allocZeroMap(unsigned long size, int prot, const char *name)
{
    struct map *newnode;
    int fd;
    char buf[11];

    fd = open("/dev/zero", O_RDWR);
    if (fd == -1) {
        printf("couldn't open /dev/zero\n");
        exit(EXIT_FAILURE);
    }

    newnode = zmalloc(sizeof(struct map));
    newnode->name = strdup(name);
    newnode->size = size;
    newnode->prot = prot;
    newnode->type = INITIAL_MAP;
    newnode->ptr = mmap(NULL, size, prot, MAP_ANONYMOUS | MAP_SHARED, fd, 0);
    if (newnode->ptr == MAP_FAILED) {
        perror("mmap");
        exit(EXIT_FAILURE);
    }

    newnode->name = zmalloc(80);

    sprintf(newnode->name, "anon(%s)", name);

    num_initial_mappings++;

    list_add_tail(&newnode->list, &initial_mappings->list);

    sizeUnit(size, buf);
    printf("mapping[%d]: (zeropage %s) %p (%s)\n",
           num_initial_mappings - 1, name, newnode->ptr, buf);

    close(fd);
}
</code>```

So I figured that I would need to just switch newnode->ptr = mmap(NULL, size, prot, MAP_ANONYMOUS | MAP_SHARED, fd, 0); to newnode->ptr = mmap(NULL, size, prot, MAP_ANON | MAP_SHARED, fd, 0); because Mac OSX does not have the MAP_ANONYMOUS flag and uses MAP_ANON instead.

But when I run the program, that mmap call fails with Invalid argument. So my next thought was check the man page for what causes Invalid arguments errors. The first cause is that MAP_FIXED is set and the addr argument is not page aligned, but I'm not calling MAP_FIXED. Second it's says it will return Invalid argument if you don't specify either MAP_PRIVATE or MAP_SHARED but I'm using MAP_SHARED so that shouldn't be it. Next it says the len argument must not be negative, so I printed the size variable and ran it and it's a positive value. The final reason is that the offset argument is not page aligned, but I am passing zero so that shouldn't be the problem either.

So next I checked stack overflow and saw this question mmap with /dev/zero . I tried using MAP_FILE instead of MAP_ANON but now I get Operation not supported by device, which the man page says means I am missing MAP_ANON. So I tried adding MAP_ANON so that I have mmap(NULL, size, prot, MAP_FILE | MAP_ANON| MAP_SHARED, fd, 0); but that returns Invalid argument as well.

So how do I mmap /dev/zero on Mac OSX or at least create a zero-filled memory map on Mac OSX?

答: You should pass -1 instead of fd as the value of the file descriptor as per mmap() man page. Also as you said MAP_ANON is the correct option for MacOS (at least older versions) and there is not need for MAP_FILE.

Body:
So I am trying to port some code from Linux to Mac OSX. During porting I came across this code.

static void allocZeroMap(unsigned long size, int prot, const char *name)
{
    struct map *newnode;
    int fd;
    char buf[11];

    fd = open("/dev/zero", O_RDWR);
    if (fd == -1) {
        printf("couldn't open /dev/zero\n");
        exit(EXIT_FAILURE);
    }

    newnode = zmalloc(sizeof(struct map));
    newnode->name = strdup(name);
    newnode->size = size;
    newnode->prot = prot;
    newnode->type = INITIAL_MAP;
    newnode->ptr = mmap(NULL, size, prot, MAP_ANONYMOUS | MAP_SHARED, fd, 0);
    if (newnode->ptr == MAP_FAILED) {
        perror("mmap");
        exit(EXIT_FAILURE);
    }

    newnode->name = zmalloc(80);

    sprintf(newnode->name, "anon(%s)", name);

    num_initial_mappings++;

    list_add_tail(&newnode->list, &initial_mappings->list);

    sizeUnit(size, buf);
    printf("mapping[%d]: (zeropage %s) %p (%s)\n",
           num_initial_mappings - 1, name, newnode->ptr, buf);

    close(fd);
}

So I figured that I would need to just switch newnode->ptr = mmap(NULL, size, prot, MAP_ANONYMOUS | MAP_SHARED, fd, 0); to newnode->ptr = mmap(NULL, size, prot, MAP_ANON | MAP_SHARED, fd, 0); because Mac OSX does not have the MAP_ANONYMOUS flag and uses MAP_ANON instead.

But when I run the program, that mmap call fails with Invalid argument. So my next thought was check the man page for what causes Invalid arguments errors. The first cause is that MAP_FIXED is set and the addr argument is not page aligned, but I'm not calling MAP_FIXED. Second it's says it will return Invalid argument if you don't specify either MAP_PRIVATE or MAP_SHARED but I'm using MAP_SHARED so that shouldn't be it. Next it says the len argument must not be negative, so I printed the size variable and ran it and it's a positive value. The final reason is that the offset argument is not page aligned, but I am passing zero so that shouldn't be the problem either.

So next I checked stack overflow and saw this question mmap with /dev/zero . I tried using MAP_FILE instead of MAP_ANON but now I get Operation not supported by device, which the man page says means I am missing MAP_ANON. So I tried adding MAP_ANON so that I have mmap(NULL, size, prot, MAP_FILE | MAP_ANON| MAP_SHARED, fd, 0); but that returns Invalid argument as well.

So how do I mmap /dev/zero on Mac OSX or at least create a zero-filled memory map on Mac OSX?


问:
Java exceptions wrapping: bad practice?
Coming from a PHP world where there's only one way to write exceptions handling.. I found the wrapping of exceptions in Java a bit "ugly":

```<code>public void exampleOneException(String input) throws MyBusinessException {
    try {
        // do something
    } catch (NumberFormatException e) {
        throw new MyBusinessException("Error...", e);
    }
}
</code>```

I prefer to use this style instead:

```<code>public void exampleTwoException() {
    try {
        // do something
    } catch (MyBusinessException e) {
        log.error("Error...: " + e);
    } catch (NumberFormatException e) {
        log.error("Error...: " + e);
    }
}
</code>```

Is there any difference or best practices on those approaches on handling exceptions?

答:
I would say both NumberFormatException and MyBusinessException are useful but in different cases.

They usually appear at different levels of class hierarchy: for example NumberFormatException is a lower-level exception and you might not want to expose it at a higher level (e.g. user interface) if the user of it has no power to recover from it. In this case it is more elegant to just throw MyBusinessException and display an informative message that explains for example that something in a previous step was badly supplied or some internal processing error occurred and he/she needs to restart the process.

On the other hand, if your function is used at an intermediate-level (e.g. API) and the developer has the means to recover from the exceptional behavior, NumberFormatException is more useful, as it can be dealt with programmatically and the flow of the application might continue with minimal interruption (e.g. supply a default valid number). Alternatively, this can indicate a flaw/bug in the code that should be fixed.

For details about how to follow best practice in using exceptions, read Item 61 - Throw exceptions appropriate to the abstraction from Effective Java by Joshua Bloch.

Title: Java exceptions wrapping: bad practice?

Body:
Coming from a PHP world where there's only one way to write exceptions handling.. I found the wrapping of exceptions in Java a bit "ugly":

public void exampleOneException(String input) throws MyBusinessException {
    try {
        // do something
    } catch (NumberFormatException e) {
        throw new MyBusinessException("Error...", e);
    }
}

I prefer to use this style instead:

public void exampleTwoException() {
    try {
        // do something
    } catch (MyBusinessException e) {
        log.error("Error...: " + e);
    } catch (NumberFormatException e) {
        log.error("Error...: " + e);
    }
}

Is there any difference or best practices on those approaches on handling exceptions?


问:
Sort an array based on another array of integers
Let's say I have an array: [0,3,4,2,5,1].

What I want to do is sort an array such as:

```<code>["one", "two", "three", "four", "five", "six"]
</code>```

So that the order corresponds to the first array.

This would be the output:

```<code>["one", "four", "five", "three", "six", "two"]
</code>```

Is there an easy way to accomplish this?

答:
```<code>class test1
{
  public static String[] sort(int[] array,String[] str)
  {
    String[] out=new String[str.length];
    for(int i=0;i<str.length;i++)
    {
      out[i]=str[array[i]];
    }
    return out;
  }
}
</code>```

Body:
Let's say I have an array: [0,3,4,2,5,1].

What I want to do is sort an array such as:

["one", "two", "three", "four", "five", "six"]

So that the order corresponds to the first array.

This would be the output:

["one", "four", "five", "three", "six", "two"]

Is there an easy way to accomplish this?


问:
Bootstrap Add textbox values to List
I'm developing an app using C# ASP.NET MVC 5 using Bootstrap and jquery. I'm very new to Javascript.

1. How can I change the javascript to allow only 'Quantity' number of coordinates?  (Found a way and updated the code)

How can I post the 'list' on 'Submit' to the Controller? I guess the corresponding Model will have a List of x & y to which I bind the list?

Thanks!

Controller

```<code>[HttpGet]
public ActionResult Index() {

 var plate = new Plate() {

   Holes = new Holes() {
    Coordinates = new List < Tuple < double, double >> ()
   },

 };

 return View(plate);
}

[HttpPost]
public ActionResult Index(Plate plate) {
 try {
  // access plate.Holes.Coordinates

  DrawingGenerator drawingGenerator = new DrawingGenerator(plate);
  string outputFileName = drawingGenerator.GenerateDrawing();

  ViewBag.fileName = outputFileName;

  return View("../Download/Success");
 } catch (Exception) {
  return View("ErrorPage");
  throw;
 }
}
</code>```

cshtml file

```<code><div class="tab-pane fade" id="tab2">
   <div class="form-inline col-md-5">
      @Html.TextBox("Quantity", null, new { @class = "form-control" })
      @Html.TextBox("X", null, new { @class = "form-control" })
      @Html.TextBox("Y", null, new { @class = "form-control" })
      <input type="button" id="Add" class="button1" value="Add" />
   </div>
   <ul id="list"></ul>
</div>

<script type="text/javascript">
$(document).ready(function () {

    // list container
    var listContainer = $('#list');
    var count = 0;

    $("#Add").click(function () {

        // get x  & y from tb
        var qty = $("#Quantity").val();

        if (count == qty)
        {
            alert("can't add more! update quantity");
            return;
        }

        var x = $("#X").val();
        var y = $("#Y").val();

        // add new list item
        listContainer.prepend('<li> (' + x + ', ' + y + ') </li>');
        count = count + 1;

        // clear value input
        $('#X').val('');
        $('#Y').val('');

    });
});
</code>```

答:
In button click event get the content and send it to server.

Fiddle

```<code>$('#get').click(function(){
   alert( $('#list').text());
});
</code>```

Post with ajax

```<code>$('#get').click(function(){
  console.log( $('#list').text());
 $.ajax({
        type: "POST",
        url: "/path to controller file",
        data: $('#list').text(),
        success: function(data) {
            console.log(data); //post successfully done
        }
    });
});
</code>```

Title: Bootstrap Add textbox values to List

Body:
I'm developing an app using C# ASP.NET MVC 5 using Bootstrap and jquery. I'm very new to Javascript.

1. How can I change the javascript to allow only 'Quantity' number of coordinates?  (Found a way and updated the code)

How can I post the 'list' on 'Submit' to the Controller? I guess the corresponding Model will have a List of x & y to which I bind the list?

Thanks!

Controller

[HttpGet]
public ActionResult Index() {

 var plate = new Plate() {

   Holes = new Holes() {
    Coordinates = new List < Tuple < double, double >> ()
   },

 };

 return View(plate);
}

[HttpPost]
public ActionResult Index(Plate plate) {
 try {
  // access plate.Holes.Coordinates

  DrawingGenerator drawingGenerator = new DrawingGenerator(plate);
  string outputFileName = drawingGenerator.GenerateDrawing();

  ViewBag.fileName = outputFileName;

  return View("../Download/Success");
 } catch (Exception) {
  return View("ErrorPage");
  throw;
 }
}

cshtml file

      @Html.TextBox("Quantity", null, new { @class = "form-control" })
      @Html.TextBox("X", null, new { @class = "form-control" })
      @Html.TextBox("Y", null, new { @class = "form-control" })
      <input type="button" id="Add" class="button1" value="Add" />

Body:
In button click event get the content and send it to server.

Fiddle

$('#get').click(function(){
   alert( $('#list').text());
});

Post with ajax

$('#get').click(function(){
  console.log( $('#list').text());
 $.ajax({
        type: "POST",
        url: "/path to controller file",
        data: $('#list').text(),
        success: function(data) {
            console.log(data); //post successfully done
        }
    });
});


问:
How do I set the selected item in a comboBox to match my string using C#?
I have a string "test1" and my comboBox contains test1, test2, and test3. How do I set the selected item to "test1"? That is, how do I match my string to one of the comboBox items?

I was thinking of the line below, but this doesn't work.

```<code>comboBox1.SelectedText = "test1";
</code>```

答:
this works for me.....</p>

```<code>comboBox.DataSource.To<DataTable>().Select(" valueMember = '" + valueToBeSelected + "'")[0]["DislplayMember"];
</code>```

OwnerDisplayName: May D

LastEditorDisplayName: Binary Worrier

Body:
I have a string "test1" and my comboBox contains test1, test2, and test3. How do I set the selected item to "test1"? That is, how do I match my string to one of the comboBox items?

I was thinking of the line below, but this doesn't work.

comboBox1.SelectedText = "test1";

Body:
this works for me.....

comboBox.DataSource.To<DataTable>().Select(" valueMember = '" + valueToBeSelected + "'")[0]["DislplayMember"];


问:
Validation Summary For Ajax Call
What is the best way to send back Validation Summaries back to the client when making an ajax call using jquery?</p>

答:
You should return them back in Json. You can do this by return Json("Your Message")

If you're using ASP.NET MVC 3, look into the new remote attribute: http://davidhayden.com/blog/dave/archive/2011/01/04/ASPNETMVC3RemoteValidationTutorial.aspx

Title: Validation Summary For Ajax Call


问:
PowerShell: ErrorAction set to "SilentlyContinue" not working
The following command does not show the error message, which is what I want:

```<code>Copy-Item "C:\Folder I Have Access To\*" "C:\Folder I Do Not Have Access To" -ErrorAction SilentlyContinue
</code>```

The following command does show the error message, which is not what I want:

```<code>Copy-Item "C:\Folder I Have Access To\*" "C:\Folder I Do Not Have Access To" -Force -ErrorAction SilentlyContinue
</code>```

This is because I'm using the "Force" parameter. Is there a way I can use the "Force" parameter and still not show the error message?

答:
I just happen to run across your post as I was searching for an answer to mine. This post seems to resolve to it being a bug, although this one is talking about the "Verbose" parameter, it could apply to -force as well.

https://social.technet.microsoft.com/Forums/windowsserver/en-US/b76eccae-4484-43ec-a3dc-d4bc581124c2/adding-verbose-to-a-cmdlet-prevents-script-from-terminating-on-error?forum=winserverpowershell

Body:
The following command does not show the error message, which is what I want:

Copy-Item "C:\Folder I Have Access To\*" "C:\Folder I Do Not Have Access To" -ErrorAction SilentlyContinue

The following command does show the error message, which is not what I want:

Copy-Item "C:\Folder I Have Access To\*" "C:\Folder I Do Not Have Access To" -Force -ErrorAction SilentlyContinue

This is because I'm using the "Force" parameter. Is there a way I can use the "Force" parameter and still not show the error message?