问:
How to implement network error alerts into my app?
I am developing a view based app that requires a network connection. I want to add code so that my app gives an error when a network is not available.

I am clueless as to, whether or what code to put into the appdelegate(.h/.m) and/or viewcontroller(.h/.m)

Can anyone help me?

Thanks in advance :)

答:
Did you read this post?

Once you know you're offline you just might wanna show an UIAlertView.

You could integrate this code into the method application:didFinishLaunchingWithOptions: of your appDelegate.

I would not recommend to use such a feature as "test for network connectivity". The general problem with it is, that even though you might have connectivity when your app tests for it, it might be gone a little later. So I would just try to use connectivity when your app really needs to use the network and then handle error cases carefully and display meaningful messages and so on.


来源: stackexchange

问:
User login system including username and password
How is it possible to check the entries for login and password and if they are correct, new tabs will open. If the entries are incorrect, an error message will be displayed. The user should also be able to register for an account</p>

```<code> from tkinter import *
import sqlite3
import tkinter
import time
root = Tk()

root.title("Sale System")
root.geometry("500x500")
root.configure(background='grey')

Label(root, text="Checkout System", background='grey').grid(row=0, column=1)
Label(root, text="Time:", background='grey').grid(row=1, column=1)

def clock():
    t=time.strftime('%I:%M:%S',time.localtime())
    if t!='':
        labeltime.config(text=t)
    root.after(100,clock)
labeltime=Label(root, text="Current System Time", background='grey')
labeltime.grid(row=1, column=1)
time1 = clock()

def new_winF(): #Opens registration confirmation window
    newwin = Toplevel(root)
    display = Label(newwin, text="Your account has been created. Please log in with your new details. This window may be closed.")
    display.pack()

Label(root, text="Username:", background='grey').grid(row=3, column=0, sticky=W)
Label(root, text="Password:", background='grey').grid(row=4, column=0, sticky=W)

e1 = Entry(root)
e1.grid(row=3, column=1)

if e1 == 'yes':
    command =new_winF

e2 = Entry(root)
e2.grid(row=4, column=1)

LoginButton = Button(root, text="Login", width=10)
LoginButton.grid(row=5, column=1)

RegisterButton = Button(root, text ="Register", command =new_winF, width=10)
RegisterButton.grid(row=6, column=1)

root.mainloop()
</code>```

答:
There is too many changes to describe it.

BTW: I use Frame to group widgets and later I can show one frame (pack()/grid()) and hide another (pack_forget()/grid_forget()). There are more useful examples with this method.

```<code>import tkinter as tk
import time

# --- functions ---

def clock():
    txt = time.strftime('%I:%M:%S', time.localtime())
    label_time.config(text=txt)
    root.after(1000, clock)

def on_register(): #Opens registration confirmation window
    newwin = tk.Toplevel(root)
    display = tk.Label(newwin, text="\nYour account has been created.\nPlease log in with your new details.\n\nThis window may be closed.")
    display.pack()
    tk.Button(newwin, text='Close', command=newwin.destroy).pack()

def on_login(): #Opens registration confirmation window
    newwin = tk.Toplevel(root)
    if e1.get() == 'admin' and e2.get() == '12345':
        display = tk.Label(newwin, text="\nYour are logged in.\n\nThis window may be closed.")
        display.pack()

        main_page.pack_forget() # hide it
        other_page.pack() # show it
    else:
        display = tk.Label(newwin, text="\nWrong login or password.\n\nThis window may be closed.")
        display.pack()
    tk.Button(newwin, text='Close', command=newwin.destroy).pack()

def create_main_page():
    global label_time
    global e1
    global e2

    frame = tk.Frame(root)
    #frame.pack() # don't show it

    tk.Label(frame, text="Checkout System", background='grey').grid(row=0, column=1)
    tk.Label(frame, text="Time:", background='grey').grid(row=1, column=1)

    label_time = tk.Label(frame, text="Current System Time", background='grey')
    label_time.grid(row=1, column=1)

    clock()

    tk.Label(frame, text="Username:", background='grey').grid(row=3, column=0, sticky='w')
    tk.Label(frame, text="Password:", background='grey').grid(row=4, column=0, sticky='w')

    e1 = tk.Entry(frame)
    e1.grid(row=3, column=1)

    e2 = tk.Entry(frame)
    e2.grid(row=4, column=1)

    login_button = tk.Button(frame, text="Login", width=10, command=on_login)
    login_button.grid(row=5, column=1)

    register_button = tk.Button(frame, text="Register", width=10, command=on_register)
    register_button.grid(row=6, column=1)

    return frame

def create_other_page():
    frame = tk.Frame(root)
    #frame.pack() # don't show it

    tk.Label(frame, text="You are on other page", background='grey').grid(row=0, column=1)

    return frame

# ---- main ---

root = tk.Tk()

root.title("Sale System")
root.geometry("500x500")
root.configure(background='grey')

main_page = create_main_page()
main_page.pack() # show it

other_page = create_other_page()
#other_page.pack() # don't show it yet

root.mainloop()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How is it possible to check the entries for login and password and if they are correct, new tabs will open. If the entries are incorrect, an error message will be displayed. The user should also be able to register for an account

 from tkinter import *
import sqlite3
import tkinter
import time
root = Tk()

root.title("Sale System")
root.geometry("500x500")
root.configure(background='grey')

Label(root, text="Checkout System", background='grey').grid(row=0, column=1)
Label(root, text="Time:", background='grey').grid(row=1, column=1)

def clock():
    t=time.strftime('%I:%M:%S',time.localtime())
    if t!='':
        labeltime.config(text=t)
    root.after(100,clock)
labeltime=Label(root, text="Current System Time", background='grey')
labeltime.grid(row=1, column=1)
time1 = clock()

def new_winF(): #Opens registration confirmation window
    newwin = Toplevel(root)
    display = Label(newwin, text="Your account has been created. Please log in with your new details. This window may be closed.")
    display.pack()

Label(root, text="Username:", background='grey').grid(row=3, column=0, sticky=W)
Label(root, text="Password:", background='grey').grid(row=4, column=0, sticky=W)

e1 = Entry(root)
e1.grid(row=3, column=1)

if e1 == 'yes':
    command =new_winF

e2 = Entry(root)
e2.grid(row=4, column=1)

LoginButton = Button(root, text="Login", width=10)
LoginButton.grid(row=5, column=1)

RegisterButton = Button(root, text ="Register", command =new_winF, width=10)
RegisterButton.grid(row=6, column=1)

root.mainloop()

Body:
There is too many changes to describe it.

BTW: I use Frame to group widgets and later I can show one frame (pack()/grid()) and hide another (pack_forget()/grid_forget()). There are more useful examples with this method.

import tkinter as tk
import time

# --- functions ---

def clock():
    txt = time.strftime('%I:%M:%S', time.localtime())
    label_time.config(text=txt)
    root.after(1000, clock)

def on_register(): #Opens registration confirmation window
    newwin = tk.Toplevel(root)
    display = tk.Label(newwin, text="\nYour account has been created.\nPlease log in with your new details.\n\nThis window may be closed.")
    display.pack()
    tk.Button(newwin, text='Close', command=newwin.destroy).pack()

def on_login(): #Opens registration confirmation window
    newwin = tk.Toplevel(root)
    if e1.get() == 'admin' and e2.get() == '12345':
        display = tk.Label(newwin, text="\nYour are logged in.\n\nThis window may be closed.")
        display.pack()

        main_page.pack_forget() # hide it
        other_page.pack() # show it
    else:
        display = tk.Label(newwin, text="\nWrong login or password.\n\nThis window may be closed.")
        display.pack()
    tk.Button(newwin, text='Close', command=newwin.destroy).pack()

def create_main_page():
    global label_time
    global e1
    global e2

    frame = tk.Frame(root)
    #frame.pack() # don't show it

    tk.Label(frame, text="Checkout System", background='grey').grid(row=0, column=1)
    tk.Label(frame, text="Time:", background='grey').grid(row=1, column=1)

    label_time = tk.Label(frame, text="Current System Time", background='grey')
    label_time.grid(row=1, column=1)

    clock()

    tk.Label(frame, text="Username:", background='grey').grid(row=3, column=0, sticky='w')
    tk.Label(frame, text="Password:", background='grey').grid(row=4, column=0, sticky='w')

    e1 = tk.Entry(frame)
    e1.grid(row=3, column=1)

    e2 = tk.Entry(frame)
    e2.grid(row=4, column=1)

    login_button = tk.Button(frame, text="Login", width=10, command=on_login)
    login_button.grid(row=5, column=1)

    register_button = tk.Button(frame, text="Register", width=10, command=on_register)
    register_button.grid(row=6, column=1)

    return frame

def create_other_page():
    frame = tk.Frame(root)
    #frame.pack() # don't show it

    tk.Label(frame, text="You are on other page", background='grey').grid(row=0, column=1)

    return frame

# ---- main ---

root = tk.Tk()

root.title("Sale System")
root.geometry("500x500")
root.configure(background='grey')

main_page = create_main_page()
main_page.pack() # show it

other_page = create_other_page()
#other_page.pack() # don't show it yet

root.mainloop()


问:
SQL Server displays char(1) as 4 characters wide, padded by spaces
I've been constructing a simple query to return fixed width records for export to an older application. I've used

```<code>Select Cast([myColumn1] as char(1)), Cast([myColumn2] as char(1)) from myTable
</code>```

for single character columns, but the displayed result in SQL Server Management Studio always pads it out to 4 characters. For example, for a couple of single-character columns, it displays:

```<code>---- ----
P    A
</code>```

I would expect to see:

```<code>- -
P A
</code>```

I have a couple of questions:

Will this still occur if I use the query in code or will it format as expected with single character width? What I'm wondering is if it is a feature of the output pane in SSMS (although it exhibits the same behaviour when output to a file).

If it does occur, is there a workaround?

I hope that's not a dumb question, but can't seem to find any documentation...

答:
for Microsoft SQL Server Management Studio you can change the output format in - Tools-> Options -> Query Results -> SQL Server -> Results To Text.

Options Menu

If you are using Column aligned for the Output format it will display with ---- and increase depending on the data type, however it doesn't have to match the data type actual length, e.g. data of size 1 will display with 4 ----.

You can test this with the following:

```<code>select 'a',  CAST(1 AS INT), CAST(1 AS BIGINT)
</code>```

To validate the data actual length you can use DATALENGTH - documentation here.

Body:
I've been constructing a simple query to return fixed width records for export to an older application. I've used

Select Cast([myColumn1] as char(1)), Cast([myColumn2] as char(1)) from myTable

for single character columns, but the displayed result in SQL Server Management Studio always pads it out to 4 characters. For example, for a couple of single-character columns, it displays:

---- ----
P    A

I would expect to see:

- -
P A

I have a couple of questions:

Will this still occur if I use the query in code or will it format as expected with single character width? What I'm wondering is if it is a feature of the output pane in SSMS (although it exhibits the same behaviour when output to a file).

If it does occur, is there a workaround?

I hope that's not a dumb question, but can't seem to find any documentation...

Body:
for Microsoft SQL Server Management Studio you can change the output format in - Tools-> Options -> Query Results -> SQL Server -> Results To Text.

Options Menu

If you are using Column aligned for the Output format it will display with ---- and increase depending on the data type, however it doesn't have to match the data type actual length, e.g. data of size 1 will display with 4 ----.

You can test this with the following:

select 'a',  CAST(1 AS INT), CAST(1 AS BIGINT)

To validate the data actual length you can use DATALENGTH - documentation here.


问:
How to get the nondecoded attributes from a Decoder container in Swift 4?
I'm using the  Decodable protocol in order to parse JSON received from an external source. After decoding the attributes that I do know about there still may be some attributes in the JSON that are unknown and have not yet been decoded. For example, if the external source added a new attribute to the JSON at some future point in time I would like to hold onto these unknown attributes by storing them in a [String: Any] dictionary (or an alternative) so the values do not get ignored.

The issue is that after decoding the attributes that I do know about there isn't any accessors on the container to retrieve the attributes that have not yet been decoded. I'm aware of the decoder.unkeyedContainer() which I could use to iterate over each value however this would not work in my case because in order for that to work you need to know what value type you're iterating over but the value types in the JSON are not always identical.

Here is an example in playground for what I'm trying to achieve:

```<code>// Playground
import Foundation

let jsonData = """
{
    "name": "Foo",
    "age": 21
}
""".data(using: .utf8)!

struct Person: Decodable {
    enum CodingKeys: CodingKey {
        case name
    }

    let name: String
    let unknownAttributes: [String: Any]

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try container.decode(String.self, forKey: .name)

        // I would like to store the `age` attribute in this dictionary
        // but it would not be known at the time this code was written.
        self.unknownAttributes = [:]
    }
}

let decoder = JSONDecoder()
let person = try! decoder.decode(Person.self, from: jsonData)

// The `person.unknownAttributes` dictionary should
// contain the "age" attribute with a value of 21.
</code>```

I would like for the unknownAttributes dictionary to store the age attribute and value in this case and any other possible value types if they get added to the JSON from the external source in the future.

The reason I am wanting to do something like this is so that I can persist the unknown attributes present in the JSON so that in a future update of the code I will be able to handle them appropriately once the attribute keys are known.

I've done plenty of searching on StackOverflow and Google but haven't yet encountered this unique case. Thanks in advance!

答:
You guys keep coming up with novel ways to stress the Swift 4 coding APIs... ;)

A general solution, supporting all value types, might not be possible. But, for primitive types, you can try this:

Create a simple CodingKey type with string-based keys:

```<code>struct UnknownCodingKey: CodingKey {
    init?(stringValue: String) { self.stringValue = stringValue }
    let stringValue: String

    init?(intValue: Int) { return nil }
    var intValue: Int? { return nil }
}
</code>```

Then write a general decoding function using the standard KeyedDecodingContainer keyed by the UnknownCodingKey above:

```<code>func decodeUnknownKeys(from decoder: Decoder, with knownKeys: Set<String>) throws -> [String: Any] {
    let container = try decoder.container(keyedBy: UnknownCodingKey.self)
    var unknownKeyValues = [String: Any]()

    for key in container.allKeys {
        guard !knownKeys.contains(key.stringValue) else { continue }

        func decodeUnknownValue<T: Decodable>(_ type: T.Type) -> Bool {
            guard let value = try? container.decode(type, forKey: key) else {
                return false
            }
            unknownKeyValues[key.stringValue] = value
            return true
        }
        if decodeUnknownValue(String.self) { continue }
        if decodeUnknownValue(Int.self)    { continue }
        if decodeUnknownValue(Double.self) { continue }
        // ...
    }
    return unknownKeyValues
}
</code>```

Finally, use the decodeUnknownKeys function to fill your unknownAttributes dictionary:

```<code>struct Person: Decodable {
    enum CodingKeys: CodingKey {
        case name
    }

    let name: String
    let unknownAttributes: [String: Any]

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try container.decode(String.self, forKey: .name)

        let knownKeys = Set(container.allKeys.map { $0.stringValue })
        self.unknownAttributes = try decodeUnknownKeys(from: decoder, with: knownKeys)
    }
}
</code>```

A simple test:

```<code>let jsonData = """
{
    "name": "Foo",
    "age": 21,
    "token": "ABC",
    "rate": 1.234
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let person = try! decoder.decode(Person.self, from: jsonData)
print(person.name)
print(person.unknownAttributes)
</code>```

prints:

Foo

  ["age": 21, "token": "ABC", "rate": 1.234]

Body:
I'm using the  Decodable protocol in order to parse JSON received from an external source. After decoding the attributes that I do know about there still may be some attributes in the JSON that are unknown and have not yet been decoded. For example, if the external source added a new attribute to the JSON at some future point in time I would like to hold onto these unknown attributes by storing them in a [String: Any] dictionary (or an alternative) so the values do not get ignored.

The issue is that after decoding the attributes that I do know about there isn't any accessors on the container to retrieve the attributes that have not yet been decoded. I'm aware of the decoder.unkeyedContainer() which I could use to iterate over each value however this would not work in my case because in order for that to work you need to know what value type you're iterating over but the value types in the JSON are not always identical.

Here is an example in playground for what I'm trying to achieve:

// Playground
import Foundation

let jsonData = """
{
    "name": "Foo",
    "age": 21
}
""".data(using: .utf8)!

struct Person: Decodable {
    enum CodingKeys: CodingKey {
        case name
    }

    let name: String
    let unknownAttributes: [String: Any]

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try container.decode(String.self, forKey: .name)

        // I would like to store the `age` attribute in this dictionary
        // but it would not be known at the time this code was written.
        self.unknownAttributes = [:]
    }
}

let decoder = JSONDecoder()
let person = try! decoder.decode(Person.self, from: jsonData)

// The `person.unknownAttributes` dictionary should
// contain the "age" attribute with a value of 21.

I would like for the unknownAttributes dictionary to store the age attribute and value in this case and any other possible value types if they get added to the JSON from the external source in the future.

The reason I am wanting to do something like this is so that I can persist the unknown attributes present in the JSON so that in a future update of the code I will be able to handle them appropriately once the attribute keys are known.

I've done plenty of searching on StackOverflow and Google but haven't yet encountered this unique case. Thanks in advance!

Body:
You guys keep coming up with novel ways to stress the Swift 4 coding APIs... ;)

A general solution, supporting all value types, might not be possible. But, for primitive types, you can try this:

Create a simple CodingKey type with string-based keys:

struct UnknownCodingKey: CodingKey {
    init?(stringValue: String) { self.stringValue = stringValue }
    let stringValue: String

    init?(intValue: Int) { return nil }
    var intValue: Int? { return nil }
}

Then write a general decoding function using the standard KeyedDecodingContainer keyed by the UnknownCodingKey above:

func decodeUnknownKeys(from decoder: Decoder, with knownKeys: Set<String>) throws -> [String: Any] {
    let container = try decoder.container(keyedBy: UnknownCodingKey.self)
    var unknownKeyValues = [String: Any]()

    for key in container.allKeys {
        guard !knownKeys.contains(key.stringValue) else { continue }

        func decodeUnknownValue<T: Decodable>(_ type: T.Type) -> Bool {
            guard let value = try? container.decode(type, forKey: key) else {
                return false
            }
            unknownKeyValues[key.stringValue] = value
            return true
        }
        if decodeUnknownValue(String.self) { continue }
        if decodeUnknownValue(Int.self)    { continue }
        if decodeUnknownValue(Double.self) { continue }
        // ...
    }
    return unknownKeyValues
}

Finally, use the decodeUnknownKeys function to fill your unknownAttributes dictionary:

struct Person: Decodable {
    enum CodingKeys: CodingKey {
        case name
    }

    let name: String
    let unknownAttributes: [String: Any]

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try container.decode(String.self, forKey: .name)

        let knownKeys = Set(container.allKeys.map { $0.stringValue })
        self.unknownAttributes = try decodeUnknownKeys(from: decoder, with: knownKeys)
    }
}

A simple test:

let jsonData = """
{
    "name": "Foo",
    "age": 21,
    "token": "ABC",
    "rate": 1.234
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let person = try! decoder.decode(Person.self, from: jsonData)
print(person.name)
print(person.unknownAttributes)

prints:

Foo

  ["age": 21, "token": "ABC", "rate": 1.234]


问:
ASP.NET Core with form tag - validate form onsubmit and prevent submission
I have an ASP.NET Core 2.0 project where I use the form tag for a submission. Now I want to add some client side validation on my form submission. So I use the onsubmit tag on my form like this:

<form id="formId" asp-action="ActionName" onsubmit="validationFunction(Event)">
```

<p>and I have a function like this:</p>

<pre class="lang-js prettyprint-override"><code>function validationFunction(e) {
    //CheckStuff
    e.preventDefault();
}
</code>```

Now when I submit my form, the function is triggered properly but the e.preventDefault() doesn't stop the submission. Nor does return false.

How can I prevent my submission from completing?

PS. I know that I could probably handle the case with the button click and submit my form when I complete my validation but I was wondering why doesn't the above work in ASP.NET Core or what am I missing?

答:
The onsubmit attribute should be returned and return false to prevent the submitting.

```<code><form id="formId" asp-action="ActionName" onsubmit="return validationFunction(Event)">
</code>```

Body:
I have an ASP.NET Core 2.0 project where I use the form tag for a submission. Now I want to add some client side validation on my form submission. So I use the onsubmit tag on my form like this:

<form id="formId" asp-action="ActionName" onsubmit="validationFunction(Event)">

and I have a function like this:

function validationFunction(e) {
    //CheckStuff
    e.preventDefault();
}

Now when I submit my form, the function is triggered properly but the e.preventDefault() doesn't stop the submission. Nor does return false.

How can I prevent my submission from completing?

PS. I know that I could probably handle the case with the button click and submit my form when I complete my validation but I was wondering why doesn't the above work in ASP.NET Core or what am I missing?

Body:
The onsubmit attribute should be returned and return false to prevent the submitting.

<form id="formId" asp-action="ActionName" onsubmit="return validationFunction(Event)">


问:
Scale canvas content based on the JFrame size
So basically I'm building a mini game in Java and I would like the content of the Canvas component to scale based on the windows' size, which is a JFrame. The reason I want that is because I'm running the game in full screen, and obviously not all screens have the same dimensions.

This is the Window class, the Game argument is the main Canvas component which I want to scale based on the JFrame size:

```<code>public class Window{

public Window(int width, int height, String title, Game game) {

    JFrame jf = new JFrame(title);

    //Setting the window size
    jf.setSize(width, height);

    //Fullscreen window
    jf.setExtendedState(JFrame.MAXIMIZED_BOTH);
    jf.setUndecorated(true);

    jf.setLocationRelativeTo(null);
    jf.setResizable(false);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    game.setPreferredSize(new Dimension(Game.WIDTH, Game.HEIGHT));
    game.setMaximumSize(new Dimension(Game.WIDTH, Game.HEIGHT));
    game.setMinimumSize(new Dimension(Game.WIDTH, Game.HEIGHT));

    jf.add(game);

    jf.setVisible(true);

    game.start();

}

}
</code>```

This is how I get the screen dimensions and then I add those variables to the constructor of the Window class:

```<code>private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

public static final int WIDTH = (int) screenSize.getWidth(), HEIGHT = (int) screenSize.getHeight();
</code>```

Can anyone help?

P.S. Sorry if the formating is terrible, first time posting on stackoverflow.

答:
I draw some objects with Graphics class and I also have some sprites which are buffered images.

You can add a ComponentListener to your panel. When the frame is made visible a componentResized event will be generated. Then you do you image scaling calculations.

Read the section from the Swing tutorial on How to Write a ComponentListener for more information and working examples.

Body:
So basically I'm building a mini game in Java and I would like the content of the Canvas component to scale based on the windows' size, which is a JFrame. The reason I want that is because I'm running the game in full screen, and obviously not all screens have the same dimensions.

This is the Window class, the Game argument is the main Canvas component which I want to scale based on the JFrame size:

public class Window{

public Window(int width, int height, String title, Game game) {

    JFrame jf = new JFrame(title);

    //Setting the window size
    jf.setSize(width, height);

    //Fullscreen window
    jf.setExtendedState(JFrame.MAXIMIZED_BOTH);
    jf.setUndecorated(true);

    jf.setLocationRelativeTo(null);
    jf.setResizable(false);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    game.setPreferredSize(new Dimension(Game.WIDTH, Game.HEIGHT));
    game.setMaximumSize(new Dimension(Game.WIDTH, Game.HEIGHT));
    game.setMinimumSize(new Dimension(Game.WIDTH, Game.HEIGHT));

    jf.add(game);

    jf.setVisible(true);

    game.start();

}

}

This is how I get the screen dimensions and then I add those variables to the constructor of the Window class:

private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

public static final int WIDTH = (int) screenSize.getWidth(), HEIGHT = (int) screenSize.getHeight();

Can anyone help?

P.S. Sorry if the formating is terrible, first time posting on stackoverflow.


问:
SQL: How to make a replace on the field ''
I have a very but tricky question for you guys. So, listen I have a field with spaces and numbers in one of my table columns. The key part is transform the content in a decimal field. The drawback is basically that for some rows I could get something like:

```<code>    ' 1584.00 '
    ' 156546'
    '545.00 '
    '    '
</code>```

So, to clean up my column, I have done a LTRIM and RTRIM so spaces gone. So now for a couple of records where the record were just spaces the new content is ''. Finally I need to convert this result to a decimal.

Issue: The thing is that for field that contend just the spaces the new result is '' and I'm not able to apply a REPLACE on this because it's a blank and the code below doesn't work:

```<code>SELECT REPLACE('','','0')

-- Final current verison
SELECT CAST(COALESCE(REPLACE(REPLACE([Gross_Weight],' ','0'),',',''),'0') AS DECIMAL(13,3))
</code>```

How could I figure it out?

thanks so much

答:
```<code>SELECT COALESCE(NULLIF(MyColumn, ''), 0)
</code>```

This has the side-effect that you will also turn NULL values into 0, which you might not want. If that's a problem then a simple CASE statement should do the trick:

```<code>SELECT CASE WHEN MyColumn = '' THEN 0 ELSE CAST(MyColumn AS DECIMAL(10, 4)) END
</code>```

Obviously you'll also have to incorporate any other manipulations that you're already doing.

Body:
I have a very but tricky question for you guys. So, listen I have a field with spaces and numbers in one of my table columns. The key part is transform the content in a decimal field. The drawback is basically that for some rows I could get something like:

    ' 1584.00 '
    ' 156546'
    '545.00 '
    '    '

So, to clean up my column, I have done a LTRIM and RTRIM so spaces gone. So now for a couple of records where the record were just spaces the new content is ''. Finally I need to convert this result to a decimal.

Issue: The thing is that for field that contend just the spaces the new result is '' and I'm not able to apply a REPLACE on this because it's a blank and the code below doesn't work:

SELECT REPLACE('','','0')

-- Final current verison
SELECT CAST(COALESCE(REPLACE(REPLACE([Gross_Weight],' ','0'),',',''),'0') AS DECIMAL(13,3))

How could I figure it out?

thanks so much

Body:
SELECT COALESCE(NULLIF(MyColumn, ''), 0)

This has the side-effect that you will also turn NULL values into 0, which you might not want. If that's a problem then a simple CASE statement should do the trick:

SELECT CASE WHEN MyColumn = '' THEN 0 ELSE CAST(MyColumn AS DECIMAL(10, 4)) END

Obviously you'll also have to incorporate any other manipulations that you're already doing.


问:
C# ExecuteNonQuery Error (Connecting My.ASP Web Form to an Access DB)
I'm trying to connect my ASP.NET online registration form to  MS Access backend database. The connection code I'm using is

```<code>String connString;
connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Z\Desktop\Comp\MyWebsite\WorkDatabase.mdb";
OleDbConnection myConnection = new  OleDbConnection(connString);
myConnection.Open();
string myQuery = "INSERT INTO Parent([Username], [FirstName], [Surname], [Email], [Mobile], [Postcode], [Password]) values('" + Usernametb.Text + "','" + Firsttnametb.Text + "','" + Surnametb.Text + "','" + Emailtb.Text + "','" + Mobiletb.Text + "','" + Postcodetb.Text + "','" + Passwordtb.Text + "')";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();

try
{
    using (myConnection)
    {
        myConnection.Open();
        myCommand.ExecuteNonQuery();
        SuccReglbl.Text = "successful registration";
    }
}
catch (Exception ex)
{
    SuccReglbl.Text = "Exception in DBHandler" + ex;
}
finally
{

}

myCommand.ExecuteNonQuery();
OleDbDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{

}
myConnection.Close();
</code>```

I keep getting an error when I click on the "Register" button. The error is

"ExecuteNonQuery requires an open and available Connection. The connection's current state is closed."

I'm unsure how to fix this.

答:
@Jerodev
The latest version of my code is
String connString;
            connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Z\Desktop\MyWebsite\WorkDatabase.mdb";

```<code>        OleDbConnection myConnection = new
            OleDbConnection(connString);
        myConnection.Open();
        string myQuery = "INSERT INTO Parent([Username], [FirstName], [Surname], [Email], [Mobile], [Postcode], [Password]) values('" + Usernametb.Text + "','" + Firsttnametb.Text + "','" + Surnametb.Text + "','" + Emailtb.Text + "','" + Mobiletb.Text + "','" + Postcodetb.Text + "','" + Passwordtb.Text + "')";
        OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);

        myCommand.ExecuteNonQuery();

        try
        {
            using (myConnection)

            {
                myCommand.ExecuteNonQuery();
                SuccReglbl.Text = "successful registration";
            }
        }
        catch (Exception ex)
        {
            SuccReglbl.Text = "Exception in DBHandler" + ex;
        }

        finally
        {
            myConnection.Close();
        }

         OleDbDataReader myReader = myCommand.ExecuteReader();
         while (myReader.Read())
         {
         }
</code>```

It is giving the same error but it is saying the error is in line
"OleDbDataReader myReader = myCommand.ExecuteReader();"

Body:
I'm trying to connect my ASP.NET online registration form to  MS Access backend database. The connection code I'm using is

String connString;
connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Z\Desktop\Comp\MyWebsite\WorkDatabase.mdb";
OleDbConnection myConnection = new  OleDbConnection(connString);
myConnection.Open();
string myQuery = "INSERT INTO Parent([Username], [FirstName], [Surname], [Email], [Mobile], [Postcode], [Password]) values('" + Usernametb.Text + "','" + Firsttnametb.Text + "','" + Surnametb.Text + "','" + Emailtb.Text + "','" + Mobiletb.Text + "','" + Postcodetb.Text + "','" + Passwordtb.Text + "')";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();

try
{
    using (myConnection)
    {
        myConnection.Open();
        myCommand.ExecuteNonQuery();
        SuccReglbl.Text = "successful registration";
    }
}
catch (Exception ex)
{
    SuccReglbl.Text = "Exception in DBHandler" + ex;
}
finally
{

}

myCommand.ExecuteNonQuery();
OleDbDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{

}
myConnection.Close();

I keep getting an error when I click on the "Register" button. The error is

"ExecuteNonQuery requires an open and available Connection. The connection's current state is closed."

I'm unsure how to fix this.

Body:
@Jerodev
The latest version of my code is
String connString;
            connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Z\Desktop\MyWebsite\WorkDatabase.mdb";

        OleDbConnection myConnection = new
            OleDbConnection(connString);
        myConnection.Open();
        string myQuery = "INSERT INTO Parent([Username], [FirstName], [Surname], [Email], [Mobile], [Postcode], [Password]) values('" + Usernametb.Text + "','" + Firsttnametb.Text + "','" + Surnametb.Text + "','" + Emailtb.Text + "','" + Mobiletb.Text + "','" + Postcodetb.Text + "','" + Passwordtb.Text + "')";
        OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);

        myCommand.ExecuteNonQuery();

        try
        {
            using (myConnection)

            {
                myCommand.ExecuteNonQuery();
                SuccReglbl.Text = "successful registration";
            }
        }
        catch (Exception ex)
        {
            SuccReglbl.Text = "Exception in DBHandler" + ex;
        }

        finally
        {
            myConnection.Close();
        }

         OleDbDataReader myReader = myCommand.ExecuteReader();
         while (myReader.Read())
         {
         }

It is giving the same error but it is saying the error is in line
"OleDbDataReader myReader = myCommand.ExecuteReader();"


问:
Right way for handling a java web application startup error
I'm currently writing a java web application that performs specific checks at startup. Example, checking that the configuration file exists and defines all the required setting variables.

I placed the checking code inside the a subclass of the ServletContextListener class and registered the ServletContextListener subclass inside web.xml using:

```<code><listener>
    <listener-class>com.bloxware.lls3.MainContextListener</listener-class>
</listener>
</code>```

In the overridden contextInitialized() method I wrote code that checks the configuration file is in place and contains valid values.

If an error takes place at startup, I want to log this error and inform the web user in a suitable manner.

I need help on how to move forward from here:

Am I reading the configuration file parameters in the correct place (inside the ServletContextListener.contextInitialized(..) method )?

How would I handle showing an error page to the user once this takes place (eg. shall I add code to each servlet and jsp page to check a global flag, or can I do that in a smarter way, possibly ServletRequestListener.requestInitialized(..))?

I need a way that if the user fixes the configuration file, refreshing the page is sufficient and there is no need to restart the web application.

答:
I can respect the goal of having a dynamic configuration that checks itself, but realistically I wouldn't suggest going that route.

For the most part (caveats later) when a web application starts up, it either is configured correctly or it isn't. If the application is mis-configured, it simply won't work. For example, when applications start, many will connect to a database. If they connection string is wrong, there is never going to be a good user experience. This should be handled at startup, and startup only. The web application should NOT start, if it knows that it cannot function. Spattering code through your entire application to deal with that isn't the way to go.

The idea of checking this on context initialization is fine. But, it should be perfectly willing to throw a detailed and logged exception on the spot so that an administrator (not a user!) can deal with the issue and restart the app.

As for dynamic configurations that update without a restart. This is fine for adjusting non-critical parameters, such as timeout lengths, logging levels, or pool settings. These should only be things that don't bring the app to an immediate halt if they are incorrect. The hostname of your DB connection (for example) isn't one of these things.

In my experience, none of these things is really worth the effort to deal with all the side issues induced by dynamic reloading of configurations. I'd go with just checking things at startup and halting immediately if there is a fatal issue.

EDIT: Side note - Checking that your configuration file is in place and contains all the necessary settings is something that should probably be done in testing, not at application startup time. You can do this as a simple unit test against the file itself.

ContentLicense: CC BY-SA 2.5

Body:
I'm currently writing a java web application that performs specific checks at startup. Example, checking that the configuration file exists and defines all the required setting variables.

I placed the checking code inside the a subclass of the ServletContextListener class and registered the ServletContextListener subclass inside web.xml using:

<listener>
    <listener-class>com.bloxware.lls3.MainContextListener</listener-class>
</listener>

In the overridden contextInitialized() method I wrote code that checks the configuration file is in place and contains valid values.

If an error takes place at startup, I want to log this error and inform the web user in a suitable manner.

I need help on how to move forward from here:

Am I reading the configuration file parameters in the correct place (inside the ServletContextListener.contextInitialized(..) method )?

How would I handle showing an error page to the user once this takes place (eg. shall I add code to each servlet and jsp page to check a global flag, or can I do that in a smarter way, possibly ServletRequestListener.requestInitialized(..))?

I need a way that if the user fixes the configuration file, refreshing the page is sufficient and there is no need to restart the web application.


问:
ReactJS: How to fix numerical rows values length with toFixed(2)
I am printing the data fetched from an API into a table, and I am facing some difficulties to fix the rows numerical values to decimals. If the rows data within the API consists of numerical values, i.e. 10.0, 333, 8 or 100, etc. to render it in the end with decimal values -> 10.00, 333.00, 100.00.

The function that I am familiar with .toFixed(2), doesn't function in the same way in React, as I used to code it in javaScript. I think I am misleading the ES6 standard, but I am not sure.
Here is how it's look like, if I avoid using .toFixed(2).

Here is my code sample with rows.toFixed(2), but it's doesn't function well:

```<code>class App extends React.Component
{
    constructor()
    {
        super();
        this.state = {
            rows: [],
            columns: []
        }
    }

    componentDidMount()
    {

        fetch( "http://ickata.net/sag/api/staff/bonuses/" )
            .then( function ( response )
            {
                return response.json();
            } )
            .then( data =>
            {
                this.setState( { rows: data.rows, columns: data.columns } );
            } );

    }

    render()
    {

        return (
            <div id="container" className="container">
                <h1>Final Table with React JS</h1>
                <table className="datagrid">
                    <thead>
                        <tr> {
                            this.state.columns.map(( column, index ) =>
                            {
                                return ( <th>{column}</th> )
                            }
                            )
                        }
                        </tr>
                    </thead>
                    <tbody> {
                        this.state.rows.toFixed(2).map( row => (
                            <tr>{row.toFixed(2).map( cell => (
                                <td>{cell}</td>
                            ) )}
                            </tr>
                        ) )
                    }
                    </tbody>
                </table>
            </div>
        )
    }
}

ReactDOM.render( <div id="container"><App /></div>, document.querySelector( 'body' ) );
</code>```

You are welcome to contribute directly to my Repo: Fetching API data into a table

Here is how looks like my example, when the .toFixed has been used:

Unfortunately I was not able to find related documentation at ReactJs.org

It's doesn't function with rows[].length.toFixed(2) either.

Any suggestions will be appreciated!

答:
You're called toFixed(2) agains this.state.rows, which is an array - this is probably throwing an error which will make the render fail. This explains why you're not seeing anything on the screen.

I suspect you want something more like this:

```<code>this.state.rows.map( row => (
<tr>{row.map( cell => (
<td>{typeof cell === 'number' ? cell.toFixed( 2 ) : cell}</td>
) )}
</tr>
) )
</code>```

In this version, we look at each cell - if the content is a number, we call toFixed(2) on it before rendering - otherwise we just render it. Technically this answer is correct, but it prints as well age row values, which should not be decimals. I guess i have to hardcode the rows[3] value.

Body:
I am printing the data fetched from an API into a table, and I am facing some difficulties to fix the rows numerical values to decimals. If the rows data within the API consists of numerical values, i.e. 10.0, 333, 8 or 100, etc. to render it in the end with decimal values -> 10.00, 333.00, 100.00.

The function that I am familiar with .toFixed(2), doesn't function in the same way in React, as I used to code it in javaScript. I think I am misleading the ES6 standard, but I am not sure.
Here is how it's look like, if I avoid using .toFixed(2).

Here is my code sample with rows.toFixed(2), but it's doesn't function well:

class App extends React.Component
{
    constructor()
    {
        super();
        this.state = {
            rows: [],
            columns: []
        }
    }

    componentDidMount()
    {

        fetch( "http://ickata.net/sag/api/staff/bonuses/" )
            .then( function ( response )
            {
                return response.json();
            } )
            .then( data =>
            {
                this.setState( { rows: data.rows, columns: data.columns } );
            } );

    }

    render()
    {

        return (

Final Table with React JS

 {
                            this.state.columns.map(( column, index ) =>
                            {
                                return ( {column}	 )
                            }
                            )
                        }

 {
                        this.state.rows.toFixed(2).map( row => (

{row.toFixed(2).map( cell => (
                                {cell}
                            ) )}

                        ) )
                    }

        )
    }
}

ReactDOM.render(
<App />
, document.querySelector( 'body' ) );

You are welcome to contribute directly to my Repo: Fetching API data into a table

Here is how looks like my example, when the .toFixed has been used:

Unfortunately I was not able to find related documentation at ReactJs.org

It's doesn't function with rows[].length.toFixed(2) either.

Any suggestions will be appreciated!

Body:
You're called toFixed(2) agains this.state.rows, which is an array - this is probably throwing an error which will make the render fail. This explains why you're not seeing anything on the screen.

I suspect you want something more like this:

this.state.rows.map( row => (
<tr>{row.map( cell => (
<td>{typeof cell === 'number' ? cell.toFixed( 2 ) : cell}</td>
) )}
</tr>
) )

In this version, we look at each cell - if the content is a number, we call toFixed(2) on it before rendering - otherwise we just render it. Technically this answer is correct, but it prints as well age row values, which should not be decimals. I guess i have to hardcode the rows[3] value.


问:
Import Excel files with different Date types
Got a lot of Excel files, all containing the same columns. One of the columns is called "DateTime". The problem is, that this column contain different formats, e.g:

```<code>2/12/2013  11:59:45 PM
20/2/2013 14:36:58
</code>```

As you can see, the first example contains a PM at the end. Here is my problem:

My code to import all the Excel files in the specific folder:

```<code>file.list <- list.files(pattern='*.xlsx')
df.list <- lapply(file.list, read_excel)
df <- bind_rows(df.list, .id = "id")
</code>```

But, after I run the second line (df.list <- lapply(file.list, read_excel)) I got a warnings like (Expecting numeric, got a date).

I tried different things, such as assigning col_types = "text" (I hoped that I could import all the data as character, and afterwards change remove the PM at the end and change the characters back to as.Date again). But unfortunately the results was a lot of NA's.

Another thing that I tried was to import the the file as numeric (but again, received the same message "Expecting numeric, got a date).

So how can I tackle this problem? I can do it by changing the columns type in Excel, but that is not what I want to do (I prefer to do everything in R).

Edit

Some data as requested (after I imported the data into R with as "character" with the lubridate as_date function, as suggested).

```<code>Num Date
1  41277.000601851854
2  41277.004710648151
3  41277.004826388889
4  41277.007372685184
5  41277.007789351854
6  41277.007870370369
7  41277.010335648149
8  41277.010868055557
9  41277.013842592591
10 41277.014548611114
</code>```

答:
lubridate has the excellent parse_date_time function, you can specify the orders of day/month/year and also 'truncate', e.g. allow for some formats to have missing numbers.

```<code>library(lubridate)

time <- c("2/12/2013 11:59:45 PM", "20/2/2013 14:36:58")
parse_date_time(time, orders = c('dmyHMS') )

[1] "2013-12-02 11:59:45 UTC" "2013-02-20 14:36:58 UTC"
</code>```

Body:
Got a lot of Excel files, all containing the same columns. One of the columns is called "DateTime". The problem is, that this column contain different formats, e.g:

2/12/2013  11:59:45 PM
20/2/2013 14:36:58

As you can see, the first example contains a PM at the end. Here is my problem:

My code to import all the Excel files in the specific folder:

file.list <- list.files(pattern='*.xlsx')
df.list <- lapply(file.list, read_excel)
df <- bind_rows(df.list, .id = "id")

But, after I run the second line (df.list <- lapply(file.list, read_excel)) I got a warnings like (Expecting numeric, got a date).

I tried different things, such as assigning col_types = "text" (I hoped that I could import all the data as character, and afterwards change remove the PM at the end and change the characters back to as.Date again). But unfortunately the results was a lot of NA's.

Another thing that I tried was to import the the file as numeric (but again, received the same message "Expecting numeric, got a date).

So how can I tackle this problem? I can do it by changing the columns type in Excel, but that is not what I want to do (I prefer to do everything in R).

Edit

Some data as requested (after I imported the data into R with as "character" with the lubridate as_date function, as suggested).

Num Date
1  41277.000601851854
2  41277.004710648151
3  41277.004826388889
4  41277.007372685184
5  41277.007789351854
6  41277.007870370369
7  41277.010335648149
8  41277.010868055557
9  41277.013842592591
10 41277.014548611114

Body:
lubridate has the excellent parse_date_time function, you can specify the orders of day/month/year and also 'truncate', e.g. allow for some formats to have missing numbers.

library(lubridate)

time <- c("2/12/2013 11:59:45 PM", "20/2/2013 14:36:58")
parse_date_time(time, orders = c('dmyHMS') )

[1] "2013-12-02 11:59:45 UTC" "2013-02-20 14:36:58 UTC"


答:
No need for replace, just concatenate a zero to your column, like</p>

```<code>SELECT RTRIM('0' + LTRIM(column))
</code>```

Title: SQL: How to make a replace on the field ''

Body:
No need for replace, just concatenate a zero to your column, like

SELECT RTRIM('0' + LTRIM(column))


问:
DateTimeFormatter.ISO_LOCAL_DATE vs DateTimeFormatter.ofPattern("yyyy-MM-dd") in Java 8+
I have a date I’ve created using ZonedDateTime.now(ZoneOffset.of("+2:00")).minusDays(5). Now I want to format it as yyyy-MM-dd.

In Java 8+, is DateTimeFormatter.ISO_LOCAL_DATE the equivalent of DateTimeFormatter.ofPattern("yyyy-MM-dd")?

The output appears identical and looks like, from the docs, they should be the same. However, the "LOCAL" part of that gave me pause. Notice I have an offset and I'm using ZonedDateTime. I wanted to make sure there were no any gotchas or "they're the same except under these special circumstances since you're dealing with offsets, etc".

答:
For formatting a date-time denoting 5 days ago the two formatters will be equivalent. They will not be equivalent for all possible dates, neither for formatting nor for parsing.

Let’s try them out:

```<code>    DateTimeFormatter yyyyMmDd = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    int[] yearsToTest = { -900_000_000, -10_000, -2, 0, 1, 2017, 2099, 9999, 10_000, 900_000_000 };
    for (int year : yearsToTest) {
        LocalDate date = LocalDate.of(year, Month.DECEMBER, 2);
        String dateFormattedIso = date.format(DateTimeFormatter.ISO_LOCAL_DATE);
        String dateFormattedYyyyMmDd = date.format(yyyyMmDd);
        String diff = dateFormattedIso.equals(dateFormattedYyyyMmDd) ? "Same" : "Different";
        System.out.format("%-18s%-18s%s%n", dateFormattedIso, dateFormattedYyyyMmDd, diff);
    }
</code>```

The above snippet prints:

```<code>-900000000-12-02  +900000001-12-02  Different
-10000-12-02      +10001-12-02      Different
-0002-12-02       0003-12-02        Different
0000-12-02        0001-12-02        Different
0001-12-02        0001-12-02        Same
2017-12-02        2017-12-02        Same
2099-12-02        2099-12-02        Same
9999-12-02        9999-12-02        Same
+10000-12-02      +10000-12-02      Same
+900000000-12-02  +900000000-12-02  Same
</code>```

So for formatting it seems they are equivalent for years in the common era (“AD”), but not for years before the common era. yyyy respects that there is no year 0, so a year of 0 in the LocalDate is rendered as year 1. It is understood that it is BCE, this information is not printed. The ISO formatter takes the year literally, with sign and all.

You may obtain the behaviour of ISO_LOCAL_DATE by using uuuu instead of yyyy.

“Local” here just means without time zone, in turn meaning that the time zone information from your ZonedDateTime isn’t printed, which you wouldn’t have expected anyway.

Body:
For formatting a date-time denoting 5 days ago the two formatters will be equivalent. They will not be equivalent for all possible dates, neither for formatting nor for parsing.

Let’s try them out:

    DateTimeFormatter yyyyMmDd = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    int[] yearsToTest = { -900_000_000, -10_000, -2, 0, 1, 2017, 2099, 9999, 10_000, 900_000_000 };
    for (int year : yearsToTest) {
        LocalDate date = LocalDate.of(year, Month.DECEMBER, 2);
        String dateFormattedIso = date.format(DateTimeFormatter.ISO_LOCAL_DATE);
        String dateFormattedYyyyMmDd = date.format(yyyyMmDd);
        String diff = dateFormattedIso.equals(dateFormattedYyyyMmDd) ? "Same" : "Different";
        System.out.format("%-18s%-18s%s%n", dateFormattedIso, dateFormattedYyyyMmDd, diff);
    }

The above snippet prints:

-900000000-12-02  +900000001-12-02  Different
-10000-12-02      +10001-12-02      Different
-0002-12-02       0003-12-02        Different
0000-12-02        0001-12-02        Different
0001-12-02        0001-12-02        Same
2017-12-02        2017-12-02        Same
2099-12-02        2099-12-02        Same
9999-12-02        9999-12-02        Same
+10000-12-02      +10000-12-02      Same
+900000000-12-02  +900000000-12-02  Same

So for formatting it seems they are equivalent for years in the common era (“AD”), but not for years before the common era. yyyy respects that there is no year 0, so a year of 0 in the LocalDate is rendered as year 1. It is understood that it is BCE, this information is not printed. The ISO formatter takes the year literally, with sign and all.

You may obtain the behaviour of ISO_LOCAL_DATE by using uuuu instead of yyyy.

“Local” here just means without time zone, in turn meaning that the time zone information from your ZonedDateTime isn’t printed, which you wouldn’t have expected anyway.


问:
Page fadeOut when links are clicked, except mailto: links
in the below code, I am fading out any page, and then fading in the new page, when any  tag is clicked. However, there are certain instances where we don't want to fade the page out on click, for example, when an  tag is set to open externally via target="_blank". The code below reflects this and is working successfully.

However, one thing I'm not sure how to achieve, is to prevent the fade out when a link contains a mailto: reference, as obviously this is designed to open a mailing client window. Therefore I don't want the page to fade out?

Thank you.

```<code>$(window).bind("pageshow", function(event) {
    if (event.originalEvent.persisted) {
        window.location.reload();
    }
});

(function($) {
    if (window.history) {
        $(window).on('popstate', function() {
            $("body").show();
        });
    }

    // When links are clicked
    $(document).on("click", "a", function() {
    var $link   = $(this);
    var $href   = $link.attr("href");
    var $target = $link.attr("target");

        // If link exists
        if ($href) {
            // Fade out all links unless set to open in external window target="_blank"
            if ($target !== "_blank") {
                $("body").fadeOut(250, function() {
                    history.pushState($href, null, null);
                    window.location.href = $href;
                });
                return false;
            }
        }
    });

    // On page load, fade in
    $(document).ready(function() {
        $("body").fadeTo(250, 1);
    });
}(window.jQuery));
</code>```

答:
a very elegant way to do this is to use the awesome power of the css attribute selector and pass the validation so you only need this:

```<code>$(document).on('click','a[href]:not([href^=mailto],[target="_blank"])',function(){
     $("body").fadeOut(250, function() {
         history.pushState(this.href, null, null);
         window.location.href = this.href;
     });
     return false;
})
</code>```

this is where the "magic" happens: a[href]:not([href^=mailto],[target="_blank"]) (UPDATED to include the "has href" clause

I only select links that the href does not start with mailto and do not have target="_blank"

more on attribute selectors: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

Body:
in the below code, I am fading out any page, and then fading in the new page, when any  tag is clicked. However, there are certain instances where we don't want to fade the page out on click, for example, when an  tag is set to open externally via target="_blank". The code below reflects this and is working successfully.

However, one thing I'm not sure how to achieve, is to prevent the fade out when a link contains a mailto: reference, as obviously this is designed to open a mailing client window. Therefore I don't want the page to fade out?

Thank you.

$(window).bind("pageshow", function(event) {
    if (event.originalEvent.persisted) {
        window.location.reload();
    }
});

(function($) {
    if (window.history) {
        $(window).on('popstate', function() {
            $("body").show();
        });
    }

    // When links are clicked
    $(document).on("click", "a", function() {
    var $link   = $(this);
    var $href   = $link.attr("href");
    var $target = $link.attr("target");

        // If link exists
        if ($href) {
            // Fade out all links unless set to open in external window target="_blank"
            if ($target !== "_blank") {
                $("body").fadeOut(250, function() {
                    history.pushState($href, null, null);
                    window.location.href = $href;
                });
                return false;
            }
        }
    });

    // On page load, fade in
    $(document).ready(function() {
        $("body").fadeTo(250, 1);
    });
}(window.jQuery));

Body:
a very elegant way to do this is to use the awesome power of the css attribute selector and pass the validation so you only need this:

$(document).on('click','a[href]:not([href^=mailto],[target="_blank"])',function(){
     $("body").fadeOut(250, function() {
         history.pushState(this.href, null, null);
         window.location.href = this.href;
     });
     return false;
})

this is where the "magic" happens: a[href]:not([href^=mailto],[target="_blank"]) (UPDATED to include the "has href" clause

I only select links that the href does not start with mailto and do not have target="_blank"

more on attribute selectors: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors


问:
Rails: scope order question
I have some posts that belongs to location and category, sort of like craigslist post.

I want to order by most recently posted and also filter by location and category if those are specified by the user.

Can someone give an example/hints on how to do this?

答:
You can cache the field you would use to sort be category and location into the post.

```<code>before_save: cache_sortables

def cache_sortables
  self.category_title = self.category.title if self.category?
  self.location_title = self.location.title if self.location?
end

Post.find(:all, :order => 'location_title, category_title, created_at')
</code>```

It is left as an exercise to the reader to update the posts when the parent category/location title changes.

Title: Rails: scope order question

Body:
You can cache the field you would use to sort be category and location into the post.

before_save: cache_sortables

def cache_sortables
  self.category_title = self.category.title if self.category?
  self.location_title = self.location.title if self.location?
end

Post.find(:all, :order => 'location_title, category_title, created_at')

It is left as an exercise to the reader to update the posts when the parent category/location title changes.


答: ISO here means ISO-8601.  That format is currently, and probably will permanently be, yyyy-MM-dd (no timezone, since it's local).  But ask yourself this - do you want an ISO format, or do you want yyyy-MM-dd?  The fact that they're the same should be insignificant to you - you're making a decision based either on wanting a standard representation, or wanting a specific representation.  Or perhaps the question is "I'm not sure if I want an ISO format date...do I?" - to that the answer is, all things equal, you probably do.</p>

Title: DateTimeFormatter.ISO_LOCAL_DATE vs DateTimeFormatter.ofPattern("yyyy-MM-dd") in Java 8+

Body:
I have a date I’ve created using ZonedDateTime.now(ZoneOffset.of("+2:00")).minusDays(5). Now I want to format it as yyyy-MM-dd.

In Java 8+, is DateTimeFormatter.ISO_LOCAL_DATE the equivalent of DateTimeFormatter.ofPattern("yyyy-MM-dd")?

The output appears identical and looks like, from the docs, they should be the same. However, the "LOCAL" part of that gave me pause. Notice I have an offset and I'm using ZonedDateTime. I wanted to make sure there were no any gotchas or "they're the same except under these special circumstances since you're dealing with offsets, etc".


问:
Company name on iOS Setting page
After a long search I didn't find anything that explains how this work.

Anyone knows, how to set Company name to our app So that it can be visible on the iOS Settings page.

I think that certificate name doesn't linked to this.

答: The company name is set when you created your Apple developer account. I don't believe it can be changed with contacting Apple and going through a manual process with them. Also, it cannot be specified per app, but rather applies to all apps from an organization. </p>

Title: Company name on iOS Setting page


问:
Change start time extensible calendar (extjs)
I trying an extjs component (extensible calendar)

http://ext.ensible.com/

I want change the start time in day view become 4.30, but the data doesn't show after 23:00.

This is make me crazy T.T

Please, any suggestion please...

答:
Set viewStartHour and viewEndHour on fly !!

```<code>var cal = Ext.ComponentQuery.query('#app-calendar')[0];
var activeView = cal.getActiveView();

activeView.body.viewStartHour = 6; //you most use an variable!!
activeView.body.viewEndHour = 12;

activeView.body.tpl.viewStartHour = 6;
activeView.body.tpl.viewEndHour = 12;
activeView.body.tpl.constructor();

activeView.body.refresh(false);
</code>```

Enjoy!!!!

Body:
Set viewStartHour and viewEndHour on fly !!

var cal = Ext.ComponentQuery.query('#app-calendar')[0];
var activeView = cal.getActiveView();

activeView.body.viewStartHour = 6; //you most use an variable!!
activeView.body.viewEndHour = 12;

activeView.body.tpl.viewStartHour = 6;
activeView.body.tpl.viewEndHour = 12;
activeView.body.tpl.constructor();

activeView.body.refresh(false);

Enjoy!!!!


问:
About The switch Statement in Java
I'm still learning. Today I have a question in SoloLearn, into The switch Statement lesion:

```<code>int day = 3;

switch(day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;

// Outputs "Wednesday"
</code>```

and I thinks, I can have a example to remember about input and switch Statement: I want input a number, and 1 as Monday, 2 as Tuesday.... to 7 as Sunday, and repeat: 8 as Monday, 9 as Tuesday....
This is my code:

```<code>import java.util.Scanner;

public class Program {
public static void main(String[] args) {
    Scanner day = new Scanner(System.in);

        if (day.nextInt()>7){
            day.nextInt()=day.nextInt()%7;
        }

    switch(day.nextInt()){
        case 1 :
            System.out.println("Monday");
            break;
        case 2:
            System.out.println("Tuesday");
            break;
        case 3:
            System.out.println("Wednesday");
            break;
        case 4:
            System.out.println("Thursday");
            break;
        case 5:
            System.out.println("Friday");
            break;
        case 6:
            System.out.println("Saturday");
            break;
        case 0:
            System.out.println("Sunday");
        case 7:
            System.out.println("Sunday");
            break;

        }
    }
}
</code>```

and error. My knowledge's not enough to fix this thing (I think so, because i'm a newbie and still learning). Can you expand for me, fix this thing and thanks for teach!
Have fun!

答:
You are missing a break statement below case 0. Java does not allow label fall-through like some other languages.

Also - you should be checking for your number being >= 7, not >7, or you'll never get a 0 on the second week. 8 % 7 is 1

Title: About The switch Statement in Java

Body:
I'm still learning. Today I have a question in SoloLearn, into The switch Statement lesion:

int day = 3;

switch(day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;

// Outputs "Wednesday"

and I thinks, I can have a example to remember about input and switch Statement: I want input a number, and 1 as Monday, 2 as Tuesday.... to 7 as Sunday, and repeat: 8 as Monday, 9 as Tuesday....
This is my code:

import java.util.Scanner;

public class Program {
public static void main(String[] args) {
    Scanner day = new Scanner(System.in);

        if (day.nextInt()>7){
            day.nextInt()=day.nextInt()%7;
        }

    switch(day.nextInt()){
        case 1 :
            System.out.println("Monday");
            break;
        case 2:
            System.out.println("Tuesday");
            break;
        case 3:
            System.out.println("Wednesday");
            break;
        case 4:
            System.out.println("Thursday");
            break;
        case 5:
            System.out.println("Friday");
            break;
        case 6:
            System.out.println("Saturday");
            break;
        case 0:
            System.out.println("Sunday");
        case 7:
            System.out.println("Sunday");
            break;

        }
    }
}

and error. My knowledge's not enough to fix this thing (I think so, because i'm a newbie and still learning). Can you expand for me, fix this thing and thanks for teach!
Have fun!


问:
Panning button controls on Bing V8 maps
While working on Bing V8 maps I found that we do not have default button controls for panning on map. Is there a way to display panning buttons for directions North, East, West and South or it is just not available in V8 maps.

答: Panning controls were rarely used in older versions of Bing Maps and were introduce back when dragging things with a mouse was uncommon. There are no built in panning buttons that can simply be turned on, but you can easy create custom buttons that pan the map. Here is a basic code sample that does this: http://bingmapsv8samples.azurewebsites.net/#CustomOverlay_BasicOverlay</p>

Title: Panning button controls on Bing V8 maps


问:
SEGFAULT after inspecting variable with GDB on QtCreator
I have the following situation: My program runs fine, does all I want it to do,  tests pass and Valgrind says it's all right. The only issue is the fact that if I pause execution at some point and try to inspect the state of some objects in the debug view of QtCreator (using GDB) some variables become <not-accessible> and, on resuming execution it reaches a segmentation fault.

To be a little more specific, the program is single threaded and this happens while following the pointers in a tree structure. The structure seems to be fine by the output of the tests.

Does anyone know about a possible cause? Maybe I have messed up with the stack in a way that luckily doesn't affect the tests or it may be just an IDE or debugger issue that should not care about? Thanks in advance for any answers.

答:
Does anyone know about a possible cause?

Do you have multiple threads in your program?

When a program behaves differently depending on whether some GDB breakpoints are present or not, in 99.99% of the cases the program has a data race, and mere fact of stopping it at "inopportune" time exposes that fact.

On Linux, you could use Thread Sanitizer to check for data races.


问:
Pass column values into selection for SQL query using pandas.io.sql
I have multiple sql queries I need to run (via pandas.io.sql / .read_sql) that have a very similar structure so I am attempting to parameterize them.

I am wondering if there is a way to pass in column values using .format (which works for strings).

My query (truncated to simplify this post):

```<code>sql= '''
SELECT DISTINCT
    CAST(report_suite AS STRING) AS report_suite, post_pagename,
    COUNT(DISTINCT(CONCAT(post_visid_high,post_visid_low))) AS unique_visitors
FROM
    FOO.db
WHERE
    date_time BETWEEN '{0}' AND '{1}'
    AND report_suite = '{2}'
GROUP BY
    report_suite, post_pagename
ORDER BY
    unique_visitors DESC
'''.format(*parameters)
</code>```

What I would like to do, is be able to parameterize the COUNT(DISTINCT(CONCAT(post_visid_high, post_visid_low))) as Unique Visitors

like this somehow:

```<code>COUNT(DISTINCT({3})) as {'4'}
</code>```

The problem I can't seem to get around is that in order to do this would require storing the column names as something other than a string to avoid the quotes. Is there any good ways around this?

答:
Consider the following approach:

```<code>sql_dynamic_parms = dict(
  func1='CONCAT(post_visid_high,post_visid_low)',
  name1='unique_visitors'
)

sql= '''
SELECT DISTINCT
    CAST(report_suite AS STRING) AS report_suite, post_pagename,
    COUNT(DISTINCT({func1})) AS {name1}
FROM
    FOO.db
WHERE
    date_time BETWEEN %(date_from)s AND %(date_to)s
    AND report_suite = %(report_suite)s
GROUP BY
    report_suite, post_pagename
ORDER BY
    unique_visitors DESC
'''.format(**sql_dynamic_parms)

params = dict(
  date_from=pd.to_datetime('2017-01-01'),
  date_to=pd.to_datetime('2017-12-01'),
  report_suite=111
)

df = pd.read_sql(sql, conn, params=params)
</code>```

PS you may want to read PEP-249 to see what kind of parameter placeholders are accepted

Body:
I have multiple sql queries I need to run (via pandas.io.sql / .read_sql) that have a very similar structure so I am attempting to parameterize them.

I am wondering if there is a way to pass in column values using .format (which works for strings).

My query (truncated to simplify this post):

sql= '''
SELECT DISTINCT
    CAST(report_suite AS STRING) AS report_suite, post_pagename,
    COUNT(DISTINCT(CONCAT(post_visid_high,post_visid_low))) AS unique_visitors
FROM
    FOO.db
WHERE
    date_time BETWEEN '{0}' AND '{1}'
    AND report_suite = '{2}'
GROUP BY
    report_suite, post_pagename
ORDER BY
    unique_visitors DESC
'''.format(*parameters)

What I would like to do, is be able to parameterize the COUNT(DISTINCT(CONCAT(post_visid_high, post_visid_low))) as Unique Visitors

like this somehow:

COUNT(DISTINCT({3})) as {'4'}

The problem I can't seem to get around is that in order to do this would require storing the column names as something other than a string to avoid the quotes. Is there any good ways around this?

Body:
Consider the following approach:

sql_dynamic_parms = dict(
  func1='CONCAT(post_visid_high,post_visid_low)',
  name1='unique_visitors'
)

sql= '''
SELECT DISTINCT
    CAST(report_suite AS STRING) AS report_suite, post_pagename,
    COUNT(DISTINCT({func1})) AS {name1}
FROM
    FOO.db
WHERE
    date_time BETWEEN %(date_from)s AND %(date_to)s
    AND report_suite = %(report_suite)s
GROUP BY
    report_suite, post_pagename
ORDER BY
    unique_visitors DESC
'''.format(**sql_dynamic_parms)

params = dict(
  date_from=pd.to_datetime('2017-01-01'),
  date_to=pd.to_datetime('2017-12-01'),
  report_suite=111
)

df = pd.read_sql(sql, conn, params=params)

PS you may want to read PEP-249 to see what kind of parameter placeholders are accepted


问:
Can I make an object public for integration tests and/or benchmarks only?
As suggested by The Book, I have moved the integration tests in my crate to a tests directory. Some of those tests use functions that I don't want to export outside of the crate, though, and I am no longer able to use them in the integration test folder. I use them for non-test purposes too, so they need to compile outside of tests too. I tried using variants of pub(restricted), but I wasn't able to make it work. Ideally I'd like to have something like pub(tests).

directory tree (the relevant bits):

```<code>my_crate
|- src
   |- parser.rs
|- tests
   |- parsing.rs
|- benches
   |- parsing.rs
</code>```

tests/parsing.rs:

```<code>extern crate my_crate;

use my_crate::parser::foo;

#[test]
fn temp() {
    foo();
}
</code>```

benches/parsing.rs:

```<code>#![feature(test)]
extern crate test;
extern crate my_crate;

use test::Bencher;
use my_crate::parser::foo;

#[bench]
fn temp(b: &mut Bencher) {
    b.iter(|| { foo(); });
}
</code>```

My current workaround is to make the relevant objects public and invisible in the docs (#[doc(hidden)]), but it doesn't convey the proper intention. Can I make an object public only for integration test / benchmarking purposes?

答:
One difference between integration tests and unit tests is that integration tests is supposed to test the "public API" of your crate only.  Tests for internal functions is fine to keep together with the functions themselves in the src tree.

If you want to keep them a little separate, you can use a test submodule to the module containing the functions to test, as private parts are available to submodules.

If you still really want to have internal / unit tests in the tests in the tests directory, you can use a feature flag to enable public wrappers of internal functions to test (and mark the tests with the same feature flag).  Something like this in the code:

```<code>#[cfg(feature = "testable_privates")]
pub fn exposed_something(args) {
    something_private(args)
}
</code>```

Then in your test methods, you can import and call exposed_something.  If the feature testable_privates is not defined, your tests will fail to compile.  To solve that, use the feature flag to make the tests conditional as well;

```<code>#[cfg(feature = "testable_privates")]
#[test]
fn test_something() {
    assert_eq!(exposed_something(my_args), expected_result)
}
</code>```

Also, before doing that you need to define the feature in your Cargo.toml, like so:

```<code>[features]
testable_privates = []
</code>```

(The empty array is to signify that the feature does not require any otherwise optional dependencies).

Now, if you just run cargo test, both exposed_something and test_something will just be silently ignored, but if you run cargo test --features testable_privates, they will be compiled and tested.

As you see, this gets rather complicated, so I really think it is a better idea to just test public aspects of your crates from tests and keep tests of private methods close to those methods themselves in src.

Body:
As suggested by The Book, I have moved the integration tests in my crate to a tests directory. Some of those tests use functions that I don't want to export outside of the crate, though, and I am no longer able to use them in the integration test folder. I use them for non-test purposes too, so they need to compile outside of tests too. I tried using variants of pub(restricted), but I wasn't able to make it work. Ideally I'd like to have something like pub(tests).

directory tree (the relevant bits):

my_crate
|- src
   |- parser.rs
|- tests
   |- parsing.rs
|- benches
   |- parsing.rs

tests/parsing.rs:

extern crate my_crate;

use my_crate::parser::foo;

#[test]
fn temp() {
    foo();
}

benches/parsing.rs:

#![feature(test)]
extern crate test;
extern crate my_crate;

use test::Bencher;
use my_crate::parser::foo;

#[bench]
fn temp(b: &mut Bencher) {
    b.iter(|| { foo(); });
}

My current workaround is to make the relevant objects public and invisible in the docs (#[doc(hidden)]), but it doesn't convey the proper intention. Can I make an object public only for integration test / benchmarking purposes?

Body:
One difference between integration tests and unit tests is that integration tests is supposed to test the "public API" of your crate only.  Tests for internal functions is fine to keep together with the functions themselves in the src tree.

If you want to keep them a little separate, you can use a test submodule to the module containing the functions to test, as private parts are available to submodules.

If you still really want to have internal / unit tests in the tests in the tests directory, you can use a feature flag to enable public wrappers of internal functions to test (and mark the tests with the same feature flag).  Something like this in the code:

#[cfg(feature = "testable_privates")]
pub fn exposed_something(args) {
    something_private(args)
}

Then in your test methods, you can import and call exposed_something.  If the feature testable_privates is not defined, your tests will fail to compile.  To solve that, use the feature flag to make the tests conditional as well;

#[cfg(feature = "testable_privates")]
#[test]
fn test_something() {
    assert_eq!(exposed_something(my_args), expected_result)
}

Also, before doing that you need to define the feature in your Cargo.toml, like so:

[features]
testable_privates = []

(The empty array is to signify that the feature does not require any otherwise optional dependencies).

Now, if you just run cargo test, both exposed_something and test_something will just be silently ignored, but if you run cargo test --features testable_privates, they will be compiled and tested.

As you see, this gets rather complicated, so I really think it is a better idea to just test public aspects of your crates from tests and keep tests of private methods close to those methods themselves in src.

ContentLicense: CC BY-SA 4.0


问:
Using yield to iterate over a datareader might not close the connection?
Here is a sample code to retrieve data from a database using the yield keyword that I found in a few place while googling around :

```<code>public IEnumerable<object> ExecuteSelect(string commandText)
{
    using (IDbConnection connection = CreateConnection())
    {
        using (IDbCommand cmd = CreateCommand(commandText, connection))
        {
             connection.Open();
             using (IDbDataReader reader = cmd.ExecuteReader())
             {
                while(reader.Read())
                {
                    yield return reader["SomeField"];
                }
             }
             connection.Close();
        }
    }
}
</code>```

Am I correct in thinking that in this sample code, the connection would not be closed if we do not iterate over the whole datareader ?

Here is an example that would not close the connection, if I understand yield correctly..

```<code>foreach(object obj in ExecuteSelect(commandText))
{
  break;
}
</code>```

For a db connection that might not be catastrophic, I suppose the GC would clean it up eventually, but what if instead of a connection it was a more critical resource?

答:
Judging from this technical explanation, your code will not work as expected, but abort on the second item, because the connection was already closed when returning the first item.

@Joel Gauvreau : Yes, I should have read on. Part 3 of this series explains that the compiler adds special handling for finally blocks to trigger only at the real end.

OwnerDisplayName: Joel Gauvreau

Body:
Here is a sample code to retrieve data from a database using the yield keyword that I found in a few place while googling around :

public IEnumerable<object> ExecuteSelect(string commandText)
{
    using (IDbConnection connection = CreateConnection())
    {
        using (IDbCommand cmd = CreateCommand(commandText, connection))
        {
             connection.Open();
             using (IDbDataReader reader = cmd.ExecuteReader())
             {
                while(reader.Read())
                {
                    yield return reader["SomeField"];
                }
             }
             connection.Close();
        }
    }
}

Am I correct in thinking that in this sample code, the connection would not be closed if we do not iterate over the whole datareader ?

Here is an example that would not close the connection, if I understand yield correctly..

foreach(object obj in ExecuteSelect(commandText))
{
  break;
}

For a db connection that might not be catastrophic, I suppose the GC would clean it up eventually, but what if instead of a connection it was a more critical resource?

OwnerDisplayName: David Schmitt

LastEditorDisplayName: David Schmitt


问:
why do we separate linkers and loaders into separate programs
Guys I want to why should we separate the linker and loaders prog? What I understand is that linker's produce a relocatable code and also build the symbol table and also provide info about any dynamically linked lib, and the loader's 've to just load the executable files into memory? Why cant we merge them both?

Thanks

答:
There are a number of reasons.  One has to do with static libraries, which may contain thousands of different functions.  But a single program might use only a few of the functions that are in a particular library.  If the linker and loader were the same program, you'd have to ship the entire static library with your application.  Think of a small C++ program that's only a few kilobytes in size.  It's created by linking against the static runtime library, that is many megabytes in size.

If you require the loader to do the linking, you increase the complexity of the loader and increase the size of the operating system kernel.  Linking is a hugely complex job that can take significant time.  It's not the job of the operating system.  The OS should be concerned with executing programs, not building them.


问:
Abstract Factory Error CS0246 C# .NET
I have a working project with separate classes for things like calcs, serial port, etc.. and want to encapsulate them into dll's for use in other similar projects. I'm trying to implement a factory, firstly for a serial port Factory, so I can use between multiple dlls. This is my first time and have read loads of tutorials and have started off with this example:

https://www.codeproject.com/articles/1075518/learning-factory-pattern-using-csharp

Which works nicely as it is, but I want to move the FileLogger out to it's own class, so I have been trying for some time, but need a nudge in the right direction please?

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryPatternSample
{

    interface ILogger
    {
        void Log(string Message);
    }

    enum LoggerType
    {
        File,
        Database,
        EventViewer
    }

    public class File
    {
        public class FileLogger : ILogger
        {
            public void Log(string Message)
            {
                Console.WriteLine("{0} - Logged in File.", Message);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryPatternSample
{
    class Program
    {
        File.FileLogger flogger = new File.FileLogger();

        interface ILogger
        {
            void Log(string Message);
        }

        enum LoggerType
        {
            File,
            Database,
            EventViewer
        }

        class DatabaseLogger : ILogger
        {
            public void Log(string Message)
            {
                Console.WriteLine("{0} - Logged in Database.", Message);
            }
        }

        class EventViewerLogger : ILogger
        {
            public void Log(string Message)
            {
                Console.WriteLine("{0} - Logged in EventViewer.", Message);
            }
        }

        class LoggerFactory
        {
            public static ILogger Get(LoggerType type)
            {
                switch (type)
                {
                    case LoggerType.Database:
                        return new DatabaseLogger();
                    case LoggerType.EventViewer:
                        return new EventViewerLogger();
                    case LoggerType.File:
                    default:
                        return new flogger();
                }
            }
        }

        static void Main(string[] args)
        {
            ILogger logger1 = LoggerFactory.Get(LoggerType.Database);
            logger1.Log("Message from Main");

            ILogger logger2 = LoggerFactory.Get(LoggerType.File);
            logger2.Log("Message from Main");

            ILogger logger3 = LoggerFactory.Get(LoggerType.EventViewer);
            logger3.Log("Message from Main");

            Console.ReadKey();

            /*Output
            Message from Main - Logged in Database.
            Message from Main - Logged in File.
            Message from Main - Logged in EventViewer.
            */
        }
    }
}
</code>```

This bit is what is causing the problem:

```<code>return new flogger();
</code>```

and this is the error:

Error   CS0246  The type or namespace name 'flogger' could not be found (are you missing a using directive or an assembly reference?)

I just can't get it to reference File.FileLogger, help please?

答:
Solved, once I removed the:

```<code>interface ILogger
{
    void Log(string Message);
}
</code>```

from the program class the end went and it now works, as I Had two interfaces

Title: Abstract Factory Error CS0246 C# .NET

Body:
I have a working project with separate classes for things like calcs, serial port, etc.. and want to encapsulate them into dll's for use in other similar projects. I'm trying to implement a factory, firstly for a serial port Factory, so I can use between multiple dlls. This is my first time and have read loads of tutorials and have started off with this example:

https://www.codeproject.com/articles/1075518/learning-factory-pattern-using-csharp

Which works nicely as it is, but I want to move the FileLogger out to it's own class, so I have been trying for some time, but need a nudge in the right direction please?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryPatternSample
{

    interface ILogger
    {
        void Log(string Message);
    }

    enum LoggerType
    {
        File,
        Database,
        EventViewer
    }

    public class File
    {
        public class FileLogger : ILogger
        {
            public void Log(string Message)
            {
                Console.WriteLine("{0} - Logged in File.", Message);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryPatternSample
{
    class Program
    {
        File.FileLogger flogger = new File.FileLogger();

        interface ILogger
        {
            void Log(string Message);
        }

        enum LoggerType
        {
            File,
            Database,
            EventViewer
        }

        class DatabaseLogger : ILogger
        {
            public void Log(string Message)
            {
                Console.WriteLine("{0} - Logged in Database.", Message);
            }
        }

        class EventViewerLogger : ILogger
        {
            public void Log(string Message)
            {
                Console.WriteLine("{0} - Logged in EventViewer.", Message);
            }
        }

        class LoggerFactory
        {
            public static ILogger Get(LoggerType type)
            {
                switch (type)
                {
                    case LoggerType.Database:
                        return new DatabaseLogger();
                    case LoggerType.EventViewer:
                        return new EventViewerLogger();
                    case LoggerType.File:
                    default:
                        return new flogger();
                }
            }
        }

        static void Main(string[] args)
        {
            ILogger logger1 = LoggerFactory.Get(LoggerType.Database);
            logger1.Log("Message from Main");

            ILogger logger2 = LoggerFactory.Get(LoggerType.File);
            logger2.Log("Message from Main");

            ILogger logger3 = LoggerFactory.Get(LoggerType.EventViewer);
            logger3.Log("Message from Main");

            Console.ReadKey();

            /*Output
            Message from Main - Logged in Database.
            Message from Main - Logged in File.
            Message from Main - Logged in EventViewer.
            */
        }
    }
}

This bit is what is causing the problem:

return new flogger();

and this is the error:

Error   CS0246  The type or namespace name 'flogger' could not be found (are you missing a using directive or an assembly reference?)

I just can't get it to reference File.FileLogger, help please?

Body:
Solved, once I removed the:

interface ILogger
{
    void Log(string Message);
}

from the program class the end went and it now works, as I Had two interfaces


问:
Whats is the correct way to sum different dataframe columns in a list in pyspark?
I want to sum different columns in a spark dataframe.

Code

```<code>from pyspark.sql import functions as F
cols = ["A.p1","B.p1"]
df = spark.createDataFrame([[1,2],[4,89],[12,60]],schema=cols)

# 1. Works
df = df.withColumn('sum1', sum([df[col] for col in ["`A.p1`","`B.p1`"]]))

#2. Doesnt work
df = df.withColumn('sum1', F.sum([df[col] for col in ["`A.p1`","`B.p1`"]]))

#3. Doesnt work
df = df.withColumn('sum1', sum(df.select(["`A.p1`","`B.p1`"])))
</code>```

Why isn't approach #2. & #3. not working?
I am on Spark 2.2

答:
TL;DR builtins.sum is just fine.

Following your comments:

Using native python sum() is not benefitting from spark optimization. so whats the spark way of doing it

and

its not a pypark function so it wont be really be completely benefiting from spark right.

I can see you are making incorrect assumptions.

Let's decompose the problem:

```<code>[df[col] for col in ["`A.p1`","`B.p1`"]]
</code>```

creates a list of Columns:

```<code>[Column<b'A.p1'>, Column<b'B.p1'>]
</code>```

Let's call it iterable.

sum reduces output by taking elements of this list and calling __add__ method (+). Imperative equivalent is:

```<code>accum = iterable[0]
for element in iterable[1:]:
    accum = accum + element
</code>```

This gives Column:

```<code>Column<b'(A.p1 + B.p1)'>
</code>```

which is the same as calling

```<code>df["`A.p1`"] + df["`B.p1`"]
</code>```

No data has been touched and when evaluated it is benefits from all Spark optimizations.

Body:
I want to sum different columns in a spark dataframe.

Code

from pyspark.sql import functions as F
cols = ["A.p1","B.p1"]
df = spark.createDataFrame([[1,2],[4,89],[12,60]],schema=cols)

# 1. Works
df = df.withColumn('sum1', sum([df[col] for col in ["`A.p1`","`B.p1`"]]))

#2. Doesnt work
df = df.withColumn('sum1', F.sum([df[col] for col in ["`A.p1`","`B.p1`"]]))

#3. Doesnt work
df = df.withColumn('sum1', sum(df.select(["`A.p1`","`B.p1`"])))

Why isn't approach #2. & #3. not working?
I am on Spark 2.2

Body:
TL;DR builtins.sum is just fine.

Following your comments:

Using native python sum() is not benefitting from spark optimization. so whats the spark way of doing it

and

its not a pypark function so it wont be really be completely benefiting from spark right.

I can see you are making incorrect assumptions.

Let's decompose the problem:

[df[col] for col in ["`A.p1`","`B.p1`"]]

creates a list of Columns:

[Column<b'A.p1'>, Column<b'B.p1'>]

Let's call it iterable.

sum reduces output by taking elements of this list and calling __add__ method (+). Imperative equivalent is:

accum = iterable[0]
for element in iterable[1:]:
    accum = accum + element

This gives Column:

Column<b'(A.p1 + B.p1)'>

which is the same as calling

df["`A.p1`"] + df["`B.p1`"]

No data has been touched and when evaluated it is benefits from all Spark optimizations.


问:
How to disable manually diagonal scrolling WHILE enable diagonal setContentOffset scroll annimation
I am using a collection view.
Although the directionLockEnabled can be set to YES, diagonal scrolling is still enabled.

So I found a solution somewhere:

```<code>- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView  {
    self.offset = self.collectionView.contentOffset;
}

// control scroll to only horizontal & vertical
- (void)scrollViewDidScroll:(UIScrollView *)scrollView  {
    CGFloat deltaX = ABS(self.offset.x - self.collectionView.contentOffset.x);
    CGFloat deltaY = ABS(self.offset.y - self.collectionView.contentOffset.y);
    if (deltaX != 0 && deltaY != 0) {
        if (deltaX >= deltaY) {
            self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x, self.offset.y);
        }
        else    {
            self.collectionView.contentOffset = CGPointMake(self.offset.x, self.collectionView.contentOffset.y);
        }
    }
}
</code>```

However the side effect is when I call with x, y > 0

```<code>[self.collectionView setContentOffset:CGPointMake(x, y) animated:animated];
</code>```

It doesn't scroll at all, because of the code block above.

How to deal with this?

答:
To disable manually diagonal scrolling in Swift:</p>

```<code>func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    self.offset = scrollView.contentOffset
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let deltaX = abs(self.offset.x - self.collectionView.contentOffset.x)
    let deltaY = abs(self.offset.y - self.collectionView.contentOffset.y)

    if deltaX != 0 && deltaY != 0 {
        if deltaX >= deltaY {
            self.collectionView.contentOffset = CGPoint(x: self.collectionView.contentOffset.x, y: self.offset.y)
        } else {
            self.collectionView.contentOffset = CGPoint(x: self.offset.x, y: self.collectionView.contentOffset.y)
        }
    }
}
</code>```

Body:
I am using a collection view.
Although the directionLockEnabled can be set to YES, diagonal scrolling is still enabled.

So I found a solution somewhere:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView  {
    self.offset = self.collectionView.contentOffset;
}

// control scroll to only horizontal & vertical
- (void)scrollViewDidScroll:(UIScrollView *)scrollView  {
    CGFloat deltaX = ABS(self.offset.x - self.collectionView.contentOffset.x);
    CGFloat deltaY = ABS(self.offset.y - self.collectionView.contentOffset.y);
    if (deltaX != 0 && deltaY != 0) {
        if (deltaX >= deltaY) {
            self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x, self.offset.y);
        }
        else    {
            self.collectionView.contentOffset = CGPointMake(self.offset.x, self.collectionView.contentOffset.y);
        }
    }
}

However the side effect is when I call with x, y > 0

[self.collectionView setContentOffset:CGPointMake(x, y) animated:animated];

It doesn't scroll at all, because of the code block above.

How to deal with this?

Body:
To disable manually diagonal scrolling in Swift:

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    self.offset = scrollView.contentOffset
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let deltaX = abs(self.offset.x - self.collectionView.contentOffset.x)
    let deltaY = abs(self.offset.y - self.collectionView.contentOffset.y)

    if deltaX != 0 && deltaY != 0 {
        if deltaX >= deltaY {
            self.collectionView.contentOffset = CGPoint(x: self.collectionView.contentOffset.x, y: self.offset.y)
        } else {
            self.collectionView.contentOffset = CGPoint(x: self.offset.x, y: self.collectionView.contentOffset.y)
        }
    }
}


问:
Migrate GIT commits to existing TFS
I have the following scenario:

The client is using the TFS Source control. A repository is already in place there, containing a version A of the application

A GIT repository was created for the TFS repository. This wasn't made using git-tf or any other application, a folder from TFS was copied in the GIT folder manually

Work was done on GIT repository, and now it contains version B of the application

What we want to achieve now, is move all the commits that were made on GIT into the TFS, so that the TFS will contain the version B of the application and to have one (or more) checkins on TFS to see the changes from version A to version B.

What I was able to find so far was that git-tf can be used to achieve this if the GIT repository is made using git-tf from the TFS source. Since this was not the case for us, is there another way to automatically retrieve the files that were modified on GIT and check them in on the TFS?

Thank you,

答:
I've used git-tfs, to migrate our repo. It can handle branches, and even 2 way sync if needed. The documentation is a bit fuzzy sometimes(sources are available tho :P). But you can sync a tfs and a git repo with it. I think it can squash your git commits into one tfs check-in, but worst case every git commit will be a tfs chk-in.

Good luck tho :D

Title: Migrate GIT commits to existing TFS


答:
You can probably do it by adding a public module that only exists when testing and that re-exports the required symbols. Something like:

```<code>#[cfg(test)]
pub mod testing_parser {
    pub use parser::foo;
}
</code>```

Then use my_crate::testing_parser::foo in your tests.

Title: Can I make an object public for integration tests and/or benchmarks only?

Body:
You can probably do it by adding a public module that only exists when testing and that re-exports the required symbols. Something like:

#[cfg(test)]
pub mod testing_parser {
    pub use parser::foo;
}

Then use my_crate::testing_parser::foo in your tests.