问:
Google Cloud Storage Signed URLs with Google App Engine
It's frustrating to deal with the regular Signed URLs (Query String Authentication) for Google Cloud Storage.

Google Cloud Storage Signed URLs Example -> Is this really the only code available in the whole internet for generating Signed URLs for Google Cloud Storage? Should I read it all and adapt it manually for Pure Python GAE if needed?

It's ridiculous when you compare it with AWS S3 getAuthenticatedURL(), already included in any SDK...

Am I missing something obvious or does everyone face the same problem? What's the deal?

答:
I have no idea why the docs are so bad. The only other comprehensive answer on SO is great but tedious.

Enter the generate_signed_url method. Crawling down the rabbit hole you will notice that the code path when using this method is the same as the solution in the above SO post when executed on GAE. This method however is less tedious, has support for other environments, and has better error messages.

In code:

```<code>def sign_url(obj, expires_after_seconds=60):

    client = storage.Client()
    default_bucket = '%s.appspot.com' % app_identity.get_application_id()
    bucket = client.get_bucket(default_bucket)
    blob = storage.Blob(obj, bucket)

    expiration_time = int(time.time() + expires_after_seconds)

    url = blob.generate_signed_url(expiration_time)

    return url
</code>```

Body:
I have no idea why the docs are so bad. The only other comprehensive answer on SO is great but tedious.

Enter the generate_signed_url method. Crawling down the rabbit hole you will notice that the code path when using this method is the same as the solution in the above SO post when executed on GAE. This method however is less tedious, has support for other environments, and has better error messages.

In code:

def sign_url(obj, expires_after_seconds=60):

    client = storage.Client()
    default_bucket = '%s.appspot.com' % app_identity.get_application_id()
    bucket = client.get_bucket(default_bucket)
    blob = storage.Blob(obj, bucket)

    expiration_time = int(time.time() + expires_after_seconds)

    url = blob.generate_signed_url(expiration_time)

    return url


来源: stackexchange

问:
is it possible to calculate next z-index in javascript
Is it possible to get the highest z-index property in some container if none of the elements in it have z-index set via styles? The only approach i've found googling returns "auto" for the z-index.</p>

答: If no z-index is set then auto is the z-index...</p>

ContentLicense: CC BY-SA 2.5


问:
How to create complex ViewModels in MVC ASP.NET
So I get the concept of ViewModels, in particular the security issue, where you want to restrict the controller capabilities to the reduced set of fields in a ViewModel (as the typical User model, where the ViewModel has no information about passwords and roles).

Assume a ViewModel deriving from different Models, how would one correctly implement this (keeping e.g. the security thought in mind). Here an image that depicts the issue

I could imagine, that it is better to derive from "Sub-ViewModels" rather than directly from the Models themselves. Is there a best-practice way to do this?

答:
See the following:

ViewModels in MVC / MVVM / Seperation of layers- best practices?

A ViewModel is just that most of the time. What do you want the user to be able to View. Generally a ViewModel will be re used in a set of pages, but could be limited to just one or two.

I have many times inherited projects with a ViewModel for each page. It doesn't necessarily have to match up with your complex model. There is a host of information you might not want to pass into the view for various reasons.

I find there is much use in creating a base Controller and inheriting common functions for each custom ViewModel / Set of ViewModels.

ContentLicense: CC BY-SA 3.0


问:
How to update different value in MySQL with PHP
I have one problem which I don't know how to resloved.

I want update MySQL with different value for all "ID" which I have in MySQL.

I use PHP for this and this is my code:

```<code>//First ID check

$result = mysqli_query($conn,"SELECT subscription_end, today_date FROM users_manager WHERE id=62");

while($date = mysqli_fetch_array($result))
{
  $date['subscription_end'];
  $date['today_date'];

  if ($date['subscription_end'] <= $date['today_date']) {
    $update = "UPDATE users_manager SET status='of' WHERE id=62";
  } else {
    $update = "UPDATE users_manager SET status='on' WHERE id=62";
  }
}

//Second ID check
$result = mysqli_query($conn,"SELECT subscription_end, today_date FROM users_manager WHERE id=50");

while($date = mysqli_fetch_array($result))
{
  $date['subscription_end'];
  $date['today_date'];

  if ($date['subscription_end'] <= $date['today_date']) {
    $update = "UPDATE users_manager SET status='off' WHERE id=50";
  } else {
    $update = "UPDATE users_manager SET status='on' WHERE id=50";
  }
}
</code>```

When I add new user and that user have new ID example 55 then I must again put one line of code for check new user.

Can you tell me how I can check all of this and new and old users all the time?

答:
There may be a more slick way of doing this using straight SQL, but from a PHP perspective...

```<code>$result = mysqli_query($conn,"SELECT id FROM  users_manager");
while($id = mysqli_fetch_assoc($result)){
    $result2 = mysqli_query($conn,"SELECT subscription_end, today_date FROM users_manager WHERE id=".$id['id']);
    while($date = mysqli_fetch_assoc($result2)){
        if ($date['subscription_end'] <= $date['today_date']) {
            $update = "UPDATE users_manager SET status='off' WHERE id=".$id['id'];
        } else {
            $update = "UPDATE users_manager SET status='on' WHERE id=".$id['id'];
        }
    $result3 = mysqli_query($conn, $update);
    mysqli_free_result($result2);
    mysqli_free_result($result3);
}
</code>```

Best Practice: We strongly recommend you use PDO and bind your parameters (e.g., bindParam() to protect yourself against SQL injection.  An excellent discussion of the problems with examples of the solution are found here.  My answer has not implemented this so you can see the solution in the context of your original question.

Body:
I have one problem which I don't know how to resloved.

I want update MySQL with different value for all "ID" which I have in MySQL.

I use PHP for this and this is my code:

//First ID check

$result = mysqli_query($conn,"SELECT subscription_end, today_date FROM users_manager WHERE id=62");

while($date = mysqli_fetch_array($result))
{
  $date['subscription_end'];
  $date['today_date'];

  if ($date['subscription_end'] <= $date['today_date']) {
    $update = "UPDATE users_manager SET status='of' WHERE id=62";
  } else {
    $update = "UPDATE users_manager SET status='on' WHERE id=62";
  }
}

//Second ID check
$result = mysqli_query($conn,"SELECT subscription_end, today_date FROM users_manager WHERE id=50");

while($date = mysqli_fetch_array($result))
{
  $date['subscription_end'];
  $date['today_date'];

  if ($date['subscription_end'] <= $date['today_date']) {
    $update = "UPDATE users_manager SET status='off' WHERE id=50";
  } else {
    $update = "UPDATE users_manager SET status='on' WHERE id=50";
  }
}

When I add new user and that user have new ID example 55 then I must again put one line of code for check new user.

Can you tell me how I can check all of this and new and old users all the time?

Body:
There may be a more slick way of doing this using straight SQL, but from a PHP perspective...

$result = mysqli_query($conn,"SELECT id FROM  users_manager");
while($id = mysqli_fetch_assoc($result)){
    $result2 = mysqli_query($conn,"SELECT subscription_end, today_date FROM users_manager WHERE id=".$id['id']);
    while($date = mysqli_fetch_assoc($result2)){
        if ($date['subscription_end'] <= $date['today_date']) {
            $update = "UPDATE users_manager SET status='off' WHERE id=".$id['id'];
        } else {
            $update = "UPDATE users_manager SET status='on' WHERE id=".$id['id'];
        }
    $result3 = mysqli_query($conn, $update);
    mysqli_free_result($result2);
    mysqli_free_result($result3);
}

Best Practice: We strongly recommend you use PDO and bind your parameters (e.g., bindParam() to protect yourself against SQL injection.  An excellent discussion of the problems with examples of the solution are found here.  My answer has not implemented this so you can see the solution in the context of your original question.


问:
try to add two columns in pandas data frame, always get error
please see code and return

new to Python and really appreciate your help!

```<code>df['Height'] = df['Wall Top'] - df['Elevation']
</code>```

答:
The columns of your df are of different types. if you type:

```<code>df.dtypes
</code>```

You'll see that one is str and one is float, or both are object type. You need to do this:

```<code>df['Height'] = df['Wall Top'].astype(float) - df['Elevation'].astype(float)
</code>```

It should do the calculation you want.

Body:
please see code and return

new to Python and really appreciate your help!

df['Height'] = df['Wall Top'] - df['Elevation']

Body:
The columns of your df are of different types. if you type:

df.dtypes

You'll see that one is str and one is float, or both are object type. You need to do this:

df['Height'] = df['Wall Top'].astype(float) - df['Elevation'].astype(float)

It should do the calculation you want.


问:
listing csv files using python re.match
I have created a small code in python to list csv files in the current directory:

```<code>>>> for i in range(len(os.listdir())):
...     isMatch = re.search(r'\.csv$', os.listdir()[i])
...     if (isMatch):
...             print(os.listdir()[i])
...
HR_data.csv
HR_data2.csv
HR_data_WEKA.csv
WholesaleCustomersData.csv
>>>
</code>```

Is there a more elegant and shorter way to do this, like using lambda expressions???
Thanks very much./

答:
```<code>from glob import glob

for f in glob('*.csv'):
    print(f)
</code>```

Title: listing csv files using python re.match

Body:
I have created a small code in python to list csv files in the current directory:

>>> for i in range(len(os.listdir())):
...     isMatch = re.search(r'\.csv$', os.listdir()[i])
...     if (isMatch):
...             print(os.listdir()[i])
...
HR_data.csv
HR_data2.csv
HR_data_WEKA.csv
WholesaleCustomersData.csv
>>>

Is there a more elegant and shorter way to do this, like using lambda expressions???
Thanks very much./


答: Don't think so without specifically scripting a solution - i've always wanted something like getNextHighestDepth which you get in Actionscript

Title: is it possible to calculate next z-index in javascript

Body: Is it possible to get the highest z-index property in some container if none of the elements in it have z-index set via styles? The only approach i've found googling returns "auto" for the z-index.


问:
ComponenWillMount happening after render for some reason in react native
```<code>    componentDidMount() {
    const refi = database.ref("highscores");

    // Pushing sorted data to highscoreArray.
    refi.orderByChild("highscore").limitToLast(3).on("value", function(snapshot) {
        sortedHighscores = [];
        snapshot.forEach(function(child) {
            sortedHighscores.push({
                "username" : child.val().username,
                "score" : child.val().highscore
            });
        });

        sortedHighscores.sort(function(a,b) {
            return a.score - b.score;
        });
        this.setState({highscoreArray : sortedHighscores.reverse()});
    });
    console.log("highscore is:", this.state.highscoreArray);
}
</code>```

I am trying to get data from database and put it inside highscoreArray. Then I am trying to put it as a text in render. Some reason it is empty or null. This means that componentWillMount() happens after render()

Can someone explain or make this work? I am so frustrated.

I have changed the code as people have assisted me but still it is giving error:

```<code>undefined is not a function (evaluating 'this.setState({ highscoreArray:sortedHighscores.reverse()})')
</code>```

答:
Basically you're not waiting for all the scores to be pushed before setting it to the state, if you turn componentWillMount into an async function I believe it will solve your issue:</p>

```<code>async componentWillMount() {
    sortedHighscores = [];
    const refi = database.ref("highscores");

    // Pushing sorted data to highscoreArray.
    await refi.orderByChild("highscore").limitToLast(3).on("child_added", function(snapshot) {
        sortedHighscores.push({
            "username" : snapshot.val().username,
            "score" : snapshot.val().highscore});
    });
     sortedHighscores.sort(function(a,b) {
        return a.score - b.score;
     });
    this.setState({highscoreArray : sortedHighscores.reverse()});
    console.log("highscorevvvvv", sortedHighscores);//this.state.highscoreArray) // these are EMPTY?!?!
}
</code>```

Body:
    componentDidMount() {
    const refi = database.ref("highscores");

    // Pushing sorted data to highscoreArray.
    refi.orderByChild("highscore").limitToLast(3).on("value", function(snapshot) {
        sortedHighscores = [];
        snapshot.forEach(function(child) {
            sortedHighscores.push({
                "username" : child.val().username,
                "score" : child.val().highscore
            });
        });

        sortedHighscores.sort(function(a,b) {
            return a.score - b.score;
        });
        this.setState({highscoreArray : sortedHighscores.reverse()});
    });
    console.log("highscore is:", this.state.highscoreArray);
}

I am trying to get data from database and put it inside highscoreArray. Then I am trying to put it as a text in render. Some reason it is empty or null. This means that componentWillMount() happens after render()

Can someone explain or make this work? I am so frustrated.

I have changed the code as people have assisted me but still it is giving error:

undefined is not a function (evaluating 'this.setState({ highscoreArray:sortedHighscores.reverse()})')

Body:
Basically you're not waiting for all the scores to be pushed before setting it to the state, if you turn componentWillMount into an async function I believe it will solve your issue:

async componentWillMount() {
    sortedHighscores = [];
    const refi = database.ref("highscores");

    // Pushing sorted data to highscoreArray.
    await refi.orderByChild("highscore").limitToLast(3).on("child_added", function(snapshot) {
        sortedHighscores.push({
            "username" : snapshot.val().username,
            "score" : snapshot.val().highscore});
    });
     sortedHighscores.sort(function(a,b) {
        return a.score - b.score;
     });
    this.setState({highscoreArray : sortedHighscores.reverse()});
    console.log("highscorevvvvv", sortedHighscores);//this.state.highscoreArray) // these are EMPTY?!?!
}


问:
hrefs with anchor scroll inside a dropdown
I have a drop-down like so:

```<code><div class="dropdown">
        <select>
            <option ng-repeat="i in sc.cl" value="{{i.deptname"}}><a ng-href="#{{i.id}}">{{i.deptname}}</a></option>
        </select>
</div>
</code>```

Basically, the dropdown element's name is inside an array and there are divs inside the html having the id as i.id like this:

```<code><div class="right-bar">
                <section class="contact-block" ng-repeat="i in sc.cl" id="{{i.id}}">
                    <div class="description">{{i.deptname}}</div>
                    <div class="inner-block">
                        <div ng-repeat="j in i.cgs">
                            <img class="vertical-image" src="frame.png">
                            <img class="horizontal-image" src="mobileframe.png">
                        </div>
                    </div>
                </section>
            </div>
</code>```

whenever I click the dropdown element, I want it to scroll to the particular section. But nothing happens when I do so. Why does this happen? And when I tried inspect element in chrome, it doesn't even show the  tags in the ng-repeat dropdown.

答: Uhhm, my suggestion seems completely unrelated as I'm a dummy at AngularJS. But I have a solution to scrolling to a section using jQuery. You could simply give the section an ID and animate scrolling to that point on click by calculating the top offset and animating the scrolltop to that point...If you want me to show you the code, I'll gladly do so...:-) (Oh and I know this should be a comment because it doesn't directly answer the question, but my reputation's 13 so I can't comment)...</p>

Body:
I have a drop-down like so:

        <select>
            <option ng-repeat="i in sc.cl" value="{{i.deptname"}}>{{i.deptname}}</option>
        </select>

Basically, the dropdown element's name is inside an array and there are divs inside the html having the id as i.id like this:

{{i.deptname}}

whenever I click the dropdown element, I want it to scroll to the particular section. But nothing happens when I do so. Why does this happen? And when I tried inspect element in chrome, it doesn't even show the  tags in the ng-repeat dropdown.


答:
Rather than using regex, you could try using Python's glob module:</p>

```<code>import glob

files = glob.glob('*.csv')
for f in files:
    print(f)
</code>```

Title: listing csv files using python re.match

Body:
Rather than using regex, you could try using Python's glob module:

import glob

files = glob.glob('*.csv')
for f in files:
    print(f)


问:
Why is F# compiler sometimes incorrectly generalizing functions?
I ran into some unexpected behavior from the F# compiler recently. I was able to find a workaround, but the original behavior baffles me and I wanted to see if anyone can help me understand what causes it.

A function that I had defined as non-generic was becoming generic, which interfered with the ability of the function to share state between multiple invocations. I simplified my use-case down to the following:

```<code>let nextId =
  let mutable i = 0
  let help (key:obj) =
    i <- i + 1
    i
  help
nextId "a" // returns 1
nextId "b" // also returns 1!!!!
</code>```

Why is nextId of type 'a -> int instead of obj -> int? Clearly the generalization is also responsible for the bug where it returns 1 repeatedly, but why is the generalization occurring in the first place?

Note that if I define it without naming the nested function, it works as expected in giving unique Ids:

```<code>let nextId =
  let mutable i = 0
  fun (key:obj) ->
    i <- i + 1
    i
nextId "a" // returns 1
nextId "b" // returns 2
</code>```

But even more mysterious, with this definition, F# Interactive can't decide whether nextId is an (obj -> int) or an ('a -> int). When I first define it I get

val nextId : (obj -> int)

but if I simply eval

```<code>nextId
</code>```

I get

val it : ('a -> int)

What's going on here and why does my simple function get automatically generalized?

答:
I can't tell why the compiler decides to generalize in your first scenario, but ultimately the distinction between nextId being of type obj -> int vs 'a -> int is what drives the seemingly weird behavior here.

For what it's worth, you can "force" the expected behavior in your first scenario with yet another type annotation:

```<code>let nextId : obj -> int =
    let mutable i = 0
    let help (key:obj) =
        i <- i + 1
        i
    help
</code>```

Now if you put those values in modules (like in this gist), compile and inspect the assembly in ILSpy, you'll find that the code is almost identical except for where the ref cell for the counter is instantiated:

In the concrete case, nextId is a property yielding a function which is instantiated together with the ref cell in the static initializer for the module, i.e. all calls to nextId share the same counter,

In the generic case, nextId is a generic function yielding a function, and the ref cell is instantiated within its body, i.e. you have a counter per a call to nextId.

So the code emitted in the generic case could actually be rendered in F# with this snippet:

```<code>let nextId () =
    let mutable i = 0
    fun key ->
        i <- i + 1
        i
</code>```

The bottom line is that it would make sense to emit a compiler warning when you have a generic value like this. It's easy to avoid the problem once you know it's there, but it's one of those things you won't see coming otherwise.

Body:
I ran into some unexpected behavior from the F# compiler recently. I was able to find a workaround, but the original behavior baffles me and I wanted to see if anyone can help me understand what causes it.

A function that I had defined as non-generic was becoming generic, which interfered with the ability of the function to share state between multiple invocations. I simplified my use-case down to the following:

let nextId =
  let mutable i = 0
  let help (key:obj) =
    i <- i + 1
    i
  help
nextId "a" // returns 1
nextId "b" // also returns 1!!!!

Why is nextId of type 'a -> int instead of obj -> int? Clearly the generalization is also responsible for the bug where it returns 1 repeatedly, but why is the generalization occurring in the first place?

Note that if I define it without naming the nested function, it works as expected in giving unique Ids:

let nextId =
  let mutable i = 0
  fun (key:obj) ->
    i <- i + 1
    i
nextId "a" // returns 1
nextId "b" // returns 2

But even more mysterious, with this definition, F# Interactive can't decide whether nextId is an (obj -> int) or an ('a -> int). When I first define it I get

val nextId : (obj -> int)

but if I simply eval

nextId

I get

val it : ('a -> int)

What's going on here and why does my simple function get automatically generalized?

Body:
I can't tell why the compiler decides to generalize in your first scenario, but ultimately the distinction between nextId being of type obj -> int vs 'a -> int is what drives the seemingly weird behavior here.

For what it's worth, you can "force" the expected behavior in your first scenario with yet another type annotation:

let nextId : obj -> int =
    let mutable i = 0
    let help (key:obj) =
        i <- i + 1
        i
    help

Now if you put those values in modules (like in this gist), compile and inspect the assembly in ILSpy, you'll find that the code is almost identical except for where the ref cell for the counter is instantiated:

In the concrete case, nextId is a property yielding a function which is instantiated together with the ref cell in the static initializer for the module, i.e. all calls to nextId share the same counter,

In the generic case, nextId is a generic function yielding a function, and the ref cell is instantiated within its body, i.e. you have a counter per a call to nextId.

So the code emitted in the generic case could actually be rendered in F# with this snippet:

let nextId () =
    let mutable i = 0
    fun key ->
        i <- i + 1
        i

The bottom line is that it would make sense to emit a compiler warning when you have a generic value like this. It's easy to avoid the problem once you know it's there, but it's one of those things you won't see coming otherwise.


问:
Error passing socket to child process when using STARTF_USESTDHANDLES flag with CreateProcess()
I am trying to call a FastCGI application from .Net - this means that I need to pass a handle to a socket to the child process.

However what I'm seeing is that if I use the STARTF_USESTDHANDLES flag with CreateProcess() then the child application fails when it attempts to read from the socket.

I've worked out that I get around this by not specifying STARTF_USESTDHANDLES, but I'd like to understand why this is happening., especially as my understanding of the MSDN documentation is that I should use this flag when redirecting standard inputs.

This is my C# application (error checking etc... removed for brevity)

```<code>string command = @"FastCGI.exe";

Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(new IPEndPoint(IPAddress.Any, 8221));

// Duplicate the socket handle so that it is inheritable
SafeFileHandle childHandle;
NativeMethods.DuplicateHandle(NativeMethods.GetCurrentProcess(), new SafeFileHandle(listener.Handle, false), NativeMethods.GetCurrentProcess(), out childHandle, 0, true, NativeMethods.DUPLICATE_SAME_ACCESS);

NativeMethods.STARTUPINFO startupInfo = new NativeMethods.STARTUPINFO();
startupInfo.hStdInput = childHandle;

// Uncommenting the following line causes the problem
//startupInfo.dwFlags = NativeMethods.STARTF_USESTDHANDLES;

// Start the child process
NativeMethods.PROCESS_INFORMATION processInformation;
NativeMethods.CreateProcess(null, command, null, null, true, 0, IntPtr.Zero, null, startupInfo, out processInformation);

// To prevent the process closing the socket handle
Console.ReadKey();
</code>```

My child process is the sample FastCGI application contained in the Windows Azure VS2010 C# code samples, the line that fails is:

```<code>BOOL ret = ReadFile( hStdin, pBuffer, dwSize, &nNumberOfBytes, NULL );
if(!ret)
{
    // dw = 87 (ERROR_INVALID_PARAMETER)
    DWORD dw = GetLastError();
}
</code>```

I'm relatively new to both socket and handle programming, so any insight into why this happens would be much appreciated.

答:
You might want to try to specify handles for std err and std out as well. These need to be explicitly set when you specify STARTF_USESTDHANDLES.

In unmanaged C/C++ this is done like this:

```<code>STARTUPINFO si;
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
...
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = myInheritableHandle;
si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
</code>```

Aside from that, I would expect that you need to specify an already connected socket - i.e. you can't just bind.

Body:
I am trying to call a FastCGI application from .Net - this means that I need to pass a handle to a socket to the child process.

However what I'm seeing is that if I use the STARTF_USESTDHANDLES flag with CreateProcess() then the child application fails when it attempts to read from the socket.

I've worked out that I get around this by not specifying STARTF_USESTDHANDLES, but I'd like to understand why this is happening., especially as my understanding of the MSDN documentation is that I should use this flag when redirecting standard inputs.

This is my C# application (error checking etc... removed for brevity)

string command = @"FastCGI.exe";

Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(new IPEndPoint(IPAddress.Any, 8221));

// Duplicate the socket handle so that it is inheritable
SafeFileHandle childHandle;
NativeMethods.DuplicateHandle(NativeMethods.GetCurrentProcess(), new SafeFileHandle(listener.Handle, false), NativeMethods.GetCurrentProcess(), out childHandle, 0, true, NativeMethods.DUPLICATE_SAME_ACCESS);

NativeMethods.STARTUPINFO startupInfo = new NativeMethods.STARTUPINFO();
startupInfo.hStdInput = childHandle;

// Uncommenting the following line causes the problem
//startupInfo.dwFlags = NativeMethods.STARTF_USESTDHANDLES;

// Start the child process
NativeMethods.PROCESS_INFORMATION processInformation;
NativeMethods.CreateProcess(null, command, null, null, true, 0, IntPtr.Zero, null, startupInfo, out processInformation);

// To prevent the process closing the socket handle
Console.ReadKey();

My child process is the sample FastCGI application contained in the Windows Azure VS2010 C# code samples, the line that fails is:

BOOL ret = ReadFile( hStdin, pBuffer, dwSize, &nNumberOfBytes, NULL );
if(!ret)
{
    // dw = 87 (ERROR_INVALID_PARAMETER)
    DWORD dw = GetLastError();
}

I'm relatively new to both socket and handle programming, so any insight into why this happens would be much appreciated.

Body:
You might want to try to specify handles for std err and std out as well. These need to be explicitly set when you specify STARTF_USESTDHANDLES.

In unmanaged C/C++ this is done like this:

STARTUPINFO si;
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
...
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = myInheritableHandle;
si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);

Aside from that, I would expect that you need to specify an already connected socket - i.e. you can't just bind.


问:
Write Pandas Dataframe to DBF File?
I'm working with shapefiles, which have the attribute data stored in a DBF file. I need to manipulate the attributes using Pandas, and write the new DBF data back to disk.

Unfortunately Pandas dataframes don't have a df.to_dbf method (whereas R does). I've hunted around but don't seem to see any obvious ways to accomplish this task.

How do I save a pandas dataframe as a DBF file?

答:
you should consider using rpy2 to convert your dataframe to an R object then run something like this:

```<code>from rpy2.robjects import pandas2ri
pandas2ri.activate()
from rpy2.robjects.packages import importr
base = importr('base')
base.write.dbf(df)
</code>```

Should work seamlessly, I hope!

Title: Write Pandas Dataframe to DBF File?

Body:
you should consider using rpy2 to convert your dataframe to an R object then run something like this:

from rpy2.robjects import pandas2ri
pandas2ri.activate()
from rpy2.robjects.packages import importr
base = importr('base')
base.write.dbf(df)

Should work seamlessly, I hope!


问:
Kotlin DSL for creating json objects (without creating garbage)
I am trying to create a DSL for creating JSONObjects. Here is a builder class and a sample usage:

```<code>import org.json.JSONObject

fun json(build: JsonObjectBuilder.() -> Unit): JSONObject {
    val builder = JsonObjectBuilder()
    builder.build()
    return builder.json
}

class JsonObjectBuilder {
    val json = JSONObject()

    infix fun <T> String.To(value: T) {
        json.put(this, value)
    }
}

fun main(args: Array<String>) {
    val jsonObject =
            json {
                "name" To "ilkin"
                "age" To 37
                "male" To true
                "contact" To json {
                    "city" To "istanbul"
                    "email" To "xxx@yyy.com"
                }
            }
    println(jsonObject)
}
</code>```

The output of the above code is :

```<code>{"contact":{"city":"istanbul","email":"xxx@yyy.com"},"name":"ilkin","age":37,"male":true}
</code>```

It works as expected. But it creates an additional JsonObjectBuilder instance every time it creates a json object. Is it possible to write a DSL for creating json objects without extra garbage?

答:
Updated on Jan 11 2023:

Replaced infix fun String.to(json: Json -> Unit) with infix fun String.to(json: Json.() -> Unit) which uses Json block as receiver and invokes after a Json object is created. So no longe need to add Json key inside Json object.

I am not sure if I get the question correctly. You don't want a builder?

```<code>import org.json.JSONArray
import org.json.JSONObject

class Json() : JSONObject() {

    constructor(init: Json.() -> Unit) : this() {
        this.init()
    }

    infix fun String.to(json: Json.() -> Unit) {
        put(this, Json().apply(json))
    }

    infix fun <T> String.to(value: T) {
        put(this, value)
    }

    infix fun <T> String.to(values: List<T>) {
        put(this, JSONArray().apply {
            values.forEach { put(it) }
        })
    }
}

fun main(args: Array<String>) {

    val json = Json {
        "name" to "Roy"
        "body" to {
            "height" to 173
            "weight" to 80
        }
        "cars" to listOf(
            "Tesla"
            "Porsche"
            "BMW"
            "Ferrari"
        )
    }

    println(json)

}
</code>```

You will get

```<code>{
  "name": "Roy",
  "body": {
    "weight": 80,
    "height": 173
  },
  "cars": [
    "Tesla",
    "Porsche",
    "BMW",
    "Ferrari"
  ]
}
</code>```

Body:
I am trying to create a DSL for creating JSONObjects. Here is a builder class and a sample usage:

import org.json.JSONObject

fun json(build: JsonObjectBuilder.() -> Unit): JSONObject {
    val builder = JsonObjectBuilder()
    builder.build()
    return builder.json
}

class JsonObjectBuilder {
    val json = JSONObject()

    infix fun <T> String.To(value: T) {
        json.put(this, value)
    }
}

fun main(args: Array<String>) {
    val jsonObject =
            json {
                "name" To "ilkin"
                "age" To 37
                "male" To true
                "contact" To json {
                    "city" To "istanbul"
                    "email" To "xxx@yyy.com"
                }
            }
    println(jsonObject)
}

The output of the above code is :

{"contact":{"city":"istanbul","email":"xxx@yyy.com"},"name":"ilkin","age":37,"male":true}

It works as expected. But it creates an additional JsonObjectBuilder instance every time it creates a json object. Is it possible to write a DSL for creating json objects without extra garbage?

Body:
Updated on Jan 11 2023:

Replaced infix fun String.to(json: Json -> Unit) with infix fun String.to(json: Json.() -> Unit) which uses Json block as receiver and invokes after a Json object is created. So no longe need to add Json key inside Json object.

I am not sure if I get the question correctly. You don't want a builder?

import org.json.JSONArray
import org.json.JSONObject

class Json() : JSONObject() {

    constructor(init: Json.() -> Unit) : this() {
        this.init()
    }

    infix fun String.to(json: Json.() -> Unit) {
        put(this, Json().apply(json))
    }

    infix fun <T> String.to(value: T) {
        put(this, value)
    }

    infix fun <T> String.to(values: List<T>) {
        put(this, JSONArray().apply {
            values.forEach { put(it) }
        })
    }
}

fun main(args: Array<String>) {

    val json = Json {
        "name" to "Roy"
        "body" to {
            "height" to 173
            "weight" to 80
        }
        "cars" to listOf(
            "Tesla"
            "Porsche"
            "BMW"
            "Ferrari"
        )
    }

    println(json)

}

You will get

{
  "name": "Roy",
  "body": {
    "weight": 80,
    "height": 173
  },
  "cars": [
    "Tesla",
    "Porsche",
    "BMW",
    "Ferrari"
  ]
}

ContentLicense: CC BY-SA 4.0


问:
How to Create Google Cloud Storage Signed Urls on App Engine Python
I couldn't find a simple example on how to implement Google Cloud Storage Signed Urls on Google App Engine with Python. Please write a step by step guide. :)</p>

答:
The other solutions work but there is a simpler way using generate_signed_url. This method does the same thing as @voscausa's answer but is less tedious and has custom exceptions and support for other environments.

```<code>def sign_url(obj, expires_after_seconds=60):

    client = storage.Client()
    default_bucket = '%s.appspot.com' % app_identity.get_application_id()
    bucket = client.get_bucket(default_bucket)
    blob = storage.Blob(obj, bucket)

    expiration_time = int(time.time() + expires_after_seconds)

    url = blob.generate_signed_url(expiration_time)

    return url
</code>```

What vascausa said regarding local development server testing

But if you use the SDK to test the app, you have to use:

--appidentity_email_address

--appidentity_private_key_path

because creating a signed url is not part of the GCS client.

still holds.

Body:
The other solutions work but there is a simpler way using generate_signed_url. This method does the same thing as @voscausa's answer but is less tedious and has custom exceptions and support for other environments.

def sign_url(obj, expires_after_seconds=60):

    client = storage.Client()
    default_bucket = '%s.appspot.com' % app_identity.get_application_id()
    bucket = client.get_bucket(default_bucket)
    blob = storage.Blob(obj, bucket)

    expiration_time = int(time.time() + expires_after_seconds)

    url = blob.generate_signed_url(expiration_time)

    return url

What vascausa said regarding local development server testing

But if you use the SDK to test the app, you have to use:

--appidentity_email_address

--appidentity_private_key_path

because creating a signed url is not part of the GCS client.

still holds.


问:
sqlite python cursor function error
```<code>import sqlite3 as sql
import os

db_folder = "D:/Python/databases/accounts.sqlite"
db = sql.connect(db_folder)
im = sql.Cursor()

im.execute("""CREATE TABLE IF NOT EXISTS 'accounts' (
          id    TEXT  DEFAULT 'account' UNIQUE
          pw    TEXT  DEFAULT 'password
          email TEXT UNIQUE
)
""")

datas = [
  ("eren.arc1","1236"),
  ("ern.arc"),
  (none,none,"erenarici@gmail.com")
]

if not os.path.exists(db_folder):
    for data in datas :
        im.execute("""INSERT INTO 'accounts' VALUES (?,?,?)""",datas)
    db.commit()
</code>```

I ran this code and I got this error:

```<code>File "databases/db4.py", line 6, in <module>
im = sql.Cursor()
TypeError: function takes exactly 1 argument (0 given)
</code>```

What is the problem? I did not see argument frequently in cursor function.
Note: I used cursor() but then I took sqlite3 hasn't got cursor attribute error. Then I changed it to Cursor().

答:
Do:

```<code>import sqlite3 as sql
import os

sqlite_file = "db.sqlite"
conn = sql.connect(sqlite_file)
c = conn.cursor()

c.execute("""CREATE TABLE IF NOT EXISTS accounts (
          id TEXT DEFAULT 'account' UNIQUE,
          pw TEXT DEFAULT 'password',
          email TEXT UNIQUE);""")

items = [
  ("id1", "pw1", "user1@gmail.com"),
  ("id2", "pw2", "user2@gmail.com"),
  ("id3", "pw3", "user3@gmail.com")
]

for item in items:
    c.execute("""INSERT INTO accounts VALUES (?,?,?);""", item)

c.execute("""INSERT INTO accounts(id, email) VALUES ('id4', 'user4@gmail.com');""")
c.execute("""INSERT INTO accounts(email) VALUES ('account@gmail.com');""")

for row in c.execute('SELECT * FROM accounts'):
    print(row)

conn.commit()
conn.close()
</code>```

Output:

```<code>('id1', 'pw1', 'user1@gmail.com')
('id2', 'pw2', 'user2@gmail.com')
('id3', 'pw3', 'user3@gmail.com')
('id4', 'password', 'user4@gmail.com')
('account', 'password', 'account@gmail.com')
</code>```

If you respect the order of each field, you can check the length of the item tuple to do insertions in the loop:

```<code>for item in items:
    if len(item) == 3:
        c.execute("""INSERT INTO accounts VALUES (?,?,?);""", item)
    elif len(item) == 2:
        c.execute("""INSERT INTO accounts(pw, email) VALUES (?,?);""", item)
    elif len(item) == 1:
        c.execute("""INSERT INTO accounts(email) VALUES (?);""", item)
</code>```

But (none, none, 'email') doesn't make sense here, to insert NULL data use the keyword NULL (if python it is None not none also).

Title: sqlite python cursor function error

Body:
import sqlite3 as sql
import os

db_folder = "D:/Python/databases/accounts.sqlite"
db = sql.connect(db_folder)
im = sql.Cursor()

im.execute("""CREATE TABLE IF NOT EXISTS 'accounts' (
          id    TEXT  DEFAULT 'account' UNIQUE
          pw    TEXT  DEFAULT 'password
          email TEXT UNIQUE
)
""")

datas = [
  ("eren.arc1","1236"),
  ("ern.arc"),
  (none,none,"erenarici@gmail.com")
]

if not os.path.exists(db_folder):
    for data in datas :
        im.execute("""INSERT INTO 'accounts' VALUES (?,?,?)""",datas)
    db.commit()

I ran this code and I got this error:

File "databases/db4.py", line 6, in <module>
im = sql.Cursor()
TypeError: function takes exactly 1 argument (0 given)

What is the problem? I did not see argument frequently in cursor function.
Note: I used cursor() but then I took sqlite3 hasn't got cursor attribute error. Then I changed it to Cursor().

Body:
Do:

import sqlite3 as sql
import os

sqlite_file = "db.sqlite"
conn = sql.connect(sqlite_file)
c = conn.cursor()

c.execute("""CREATE TABLE IF NOT EXISTS accounts (
          id TEXT DEFAULT 'account' UNIQUE,
          pw TEXT DEFAULT 'password',
          email TEXT UNIQUE);""")

items = [
  ("id1", "pw1", "user1@gmail.com"),
  ("id2", "pw2", "user2@gmail.com"),
  ("id3", "pw3", "user3@gmail.com")
]

for item in items:
    c.execute("""INSERT INTO accounts VALUES (?,?,?);""", item)

c.execute("""INSERT INTO accounts(id, email) VALUES ('id4', 'user4@gmail.com');""")
c.execute("""INSERT INTO accounts(email) VALUES ('account@gmail.com');""")

for row in c.execute('SELECT * FROM accounts'):
    print(row)

conn.commit()
conn.close()

Output:

('id1', 'pw1', 'user1@gmail.com')
('id2', 'pw2', 'user2@gmail.com')
('id3', 'pw3', 'user3@gmail.com')
('id4', 'password', 'user4@gmail.com')
('account', 'password', 'account@gmail.com')

If you respect the order of each field, you can check the length of the item tuple to do insertions in the loop:

for item in items:
    if len(item) == 3:
        c.execute("""INSERT INTO accounts VALUES (?,?,?);""", item)
    elif len(item) == 2:
        c.execute("""INSERT INTO accounts(pw, email) VALUES (?,?);""", item)
    elif len(item) == 1:
        c.execute("""INSERT INTO accounts(email) VALUES (?);""", item)

But (none, none, 'email') doesn't make sense here, to insert NULL data use the keyword NULL (if python it is None not none also).


问:
How to use nginx to get the post request content，the data enctype is multipart/form-data
I want to use nginx to get the post request content,the data enctype is multipart/form-data. I used the following config,nginx config:

```<code> upstream syy{
     server 201.23.xx.xx;
    }

server {
    listen       443;
    server_name  localhost;

lua_need_request_body on;

    location /test {
        root   html;
        index  index.html index.htm;
        proxy_pass http://syy;
    proxy_buffering off;
    lua_code_cache off;
    content_by_lua_file /usr/local/openresty/luasrc/att.lua;
    }
</code>```

lua file:

```<code>function writefile(filename,info)
local file = assert(io.open(filename,"ab"))
file:write(info)
file:close()
end

ngx.req.read_body()
local value = "/home/tmp/"..os.date("%Y%m%d%H")..".att"
local data = ngx.req.get_post_args()
if data ~= nil then
    if type(data) == "table" then
        writefile(value,table.concat(data,",").."\n")
    else
        writefile(value,data.."\n")
    end
end
</code>```

But when i access the test website, I only got a empty file， like this login.jsp, which is a empty file. and the browser tip me to download login.jsp.

Thx very much！

答:
First of all "proxy_pass" and "content_by_lua_file" are not supposed to be used together. You either use proxy_pass or content_by_lua. This is why the browser is trying to download the file rather than actually executing it.

Not exactly sure what you're trying to achieve but you might wanna use "rewrite_by_lua_file" instead of "content_by_lua_file". At this stage you can do some manipulation before you reverse proxy your request. You can also use "access_by_lua*" for the snippet you use but it all depends what nginx functionality you want to use.

```<code>rewrite_by_lua_file /usr/local/openresty/luasrc/att.lua;
</code>```

Body:
I want to use nginx to get the post request content,the data enctype is multipart/form-data. I used the following config,nginx config:

 upstream syy{
     server 201.23.xx.xx;
    }

server {
    listen       443;
    server_name  localhost;

lua_need_request_body on;

    location /test {
        root   html;
        index  index.html index.htm;
        proxy_pass http://syy;
    proxy_buffering off;
    lua_code_cache off;
    content_by_lua_file /usr/local/openresty/luasrc/att.lua;
    }

lua file:

function writefile(filename,info)
local file = assert(io.open(filename,"ab"))
file:write(info)
file:close()
end

ngx.req.read_body()
local value = "/home/tmp/"..os.date("%Y%m%d%H")..".att"
local data = ngx.req.get_post_args()
if data ~= nil then
    if type(data) == "table" then
        writefile(value,table.concat(data,",").."\n")
    else
        writefile(value,data.."\n")
    end
end

But when i access the test website, I only got a empty file， like this login.jsp, which is a empty file. and the browser tip me to download login.jsp.

Thx very much！

Body:
First of all "proxy_pass" and "content_by_lua_file" are not supposed to be used together. You either use proxy_pass or content_by_lua. This is why the browser is trying to download the file rather than actually executing it.

Not exactly sure what you're trying to achieve but you might wanna use "rewrite_by_lua_file" instead of "content_by_lua_file". At this stage you can do some manipulation before you reverse proxy your request. You can also use "access_by_lua*" for the snippet you use but it all depends what nginx functionality you want to use.

rewrite_by_lua_file /usr/local/openresty/luasrc/att.lua;


问:
Restoring dependency via nuget in VS2017
I created a project of Windows Runtime Component (Universal) type using VS2017. Project file includes package reference:

```<code> <ItemGroup>
    <PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
      <Version>5.2.3</Version>
    </PackageReference>
  </ItemGroup>
</code>```

Everything works fine if this option is enabled: Automatically check for missing packages during build in Visual Studio

But I have some cases (this option is disabled, build via CLI, server CI build) when this dependency is not being restored automatically during build and project.assets.json is missing in the obj folder after build. It causes a lot of errors like this: error CS0518: Predefined type 'System.String' is not defined or imported

Is it possible to make auto restoring of package reference via project file (.csproj)?

Thanks

答: Execute msbuild -t:restore your.sln before building the solution to restore all packages and make sure your CI uses MSBuild 15.x.

Body:
I created a project of Windows Runtime Component (Universal) type using VS2017. Project file includes package reference:

 <ItemGroup>
    <PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
      <Version>5.2.3</Version>
    </PackageReference>
  </ItemGroup>

Everything works fine if this option is enabled: Automatically check for missing packages during build in Visual Studio

But I have some cases (this option is disabled, build via CLI, server CI build) when this dependency is not being restored automatically during build and project.assets.json is missing in the obj folder after build. It causes a lot of errors like this: error CS0518: Predefined type 'System.String' is not defined or imported

Is it possible to make auto restoring of package reference via project file (.csproj)?

Thanks


问:
How do I prevent print screen
I have a requirement that an application I am working on prevent the user from being able to easily capture the contents of the screen.

I have communicated that there is no feasible way to completely prevent this from happening, but I'm looking for methods to introduce some hurdles to the process.

I'm using C#/.NET 2.0 and WinForms

答:
This doesn't really answer the questions, but keep in mind that there exists tools to capture screen, and that a simple camera breaks everything.

I mean ok you "have to", but I would (but I'm young and still student, so I don't know much about what can be said) answer that this is just stupid.

OwnerDisplayName: Grady

Title: How do I prevent print screen

OwnerDisplayName: Aif


问:
bigquery python client.run_async_query gives error: 409 Already Exists
I'm coding a python script that runs a certain SELECT query async.  After the first time running the script, it always errors out after that with the following error:

google.cloud.exceptions.Conflict: 409 Already Exists: Job
  ps-bigdata:vci-temp-sales-query-job  (POST
  https://www.googleapis.com/bigquery/v2/projects/ps-bigdata/jobs)

Here is a code snippet:

```<code>from google.cloud import bigquery

google_auth_json_file = './myprojectauth.json'
client = bigquery.Client.from_service_account_json( google_auth_json_file )

project = 'myProject'
dataset = 'myDataset'
ds = client.dataset(dataset)
query = "SELECT X,y,z FROM mytable;"

#--- Clear/create temp table
temp_table_name = 'myTempTable'
temp_tbl = myCreateTempTableFunction( client, project, dataset, temp_table_name )

#--- Create an async query job
job_name = 'vci-temp-sales-query-job'
job = client.run_async_query(job_name, query)
job.destination = temp_tbl
job.write_disposition = 'WRITE_TRUNCATE'
job.begin()
</code>```

This script fails at the "job.begin()" line.  I didn't know that named jobs live on beyond the end of the session or the execution of the job.  How do I check if a named job already exists, and if it exists, how do I delete the existing named job to create a new one?  Or do I have to create random or unique job names ever time I run an async job?

答:
You need to use a unique job ID, since this is what the metadata for the operation is associated with. Referring to the querying data example, your code could be something like this:</p>

```<code>job_name = 'vci-temp-sales-query-job_{}'.format(uuid.uuid4())
</code>```

Body:
I'm coding a python script that runs a certain SELECT query async.  After the first time running the script, it always errors out after that with the following error:

google.cloud.exceptions.Conflict: 409 Already Exists: Job
  ps-bigdata:vci-temp-sales-query-job  (POST
  https://www.googleapis.com/bigquery/v2/projects/ps-bigdata/jobs)

Here is a code snippet:

from google.cloud import bigquery

google_auth_json_file = './myprojectauth.json'
client = bigquery.Client.from_service_account_json( google_auth_json_file )

project = 'myProject'
dataset = 'myDataset'
ds = client.dataset(dataset)
query = "SELECT X,y,z FROM mytable;"

#--- Clear/create temp table
temp_table_name = 'myTempTable'
temp_tbl = myCreateTempTableFunction( client, project, dataset, temp_table_name )

#--- Create an async query job
job_name = 'vci-temp-sales-query-job'
job = client.run_async_query(job_name, query)
job.destination = temp_tbl
job.write_disposition = 'WRITE_TRUNCATE'
job.begin()

This script fails at the "job.begin()" line.  I didn't know that named jobs live on beyond the end of the session or the execution of the job.  How do I check if a named job already exists, and if it exists, how do I delete the existing named job to create a new one?  Or do I have to create random or unique job names ever time I run an async job?

Body:
You need to use a unique job ID, since this is what the metadata for the operation is associated with. Referring to the querying data example, your code could be something like this:

job_name = 'vci-temp-sales-query-job_{}'.format(uuid.uuid4())


问:
Navigating to another URL during webdriver task
I am trying to log into a website as an admin and then navigate to another page (a portal) which requires this admin login beforehand to display data. I don't think I can access the cookies because of an issue accessing https cookies issue I read up on earlier (correct me if I'm wrong).

So my current solution is to enter the url as soon as the login process is complete and then continue with other tasks. Could you please advise on the methods/functions I can use to do this? If there are better ways to do this, I'd also be happy to hear about those!

```<code>var webdriver = require("selenium-webdriver");
var By = require("selenium-webdriver").By;
var until = require("selenium-webdriver").until;
var assert = require("chai").assert;
var filename = "img";
var fs = require('fs');
var err = "error caught!";
var testName = "get_login_cookies";

var driver = new webdriver.Builder()
    .forBrowser('chrome')
    .build();

describe('email register', function ()  {
    this.timeout(25000);

before(function(done) {
    driver.navigate().to('https://www.perlego.com/#');
    driver.manage().deleteAllCookies;
    driver.manage().window().maximize()
    .then(() => done())
});

it('logs in with admin user and gets cookies', (done) => {

    driver.findElement(By.name('email')).sendKeys("user@example.com");
    driver.findElement(By.css('#password')).sendKeys("examplePassword");
    driver.findElement(By.css('.login-button')).click();

    // some code here to navigate to other page via url

    // runs remainder of tests

});

after(function(done) {
    driver.quit()
    .then(() => done())
});
});
</code>```

答:
So I found that it was as simple as running the driver.navigate() method where I wanted to go to a new page:

driver.navigate().to('https://www.somesite.com/#');

Because of the cookie settings on the site, I was unable to access them with the webdriver, so I had to enter the password each time.

I was tripped up by waiting for ajax calls on the page when trying to select elements, this method helped:

driver.manage().timeouts().implicitlyWait(3000);

Hope this helps someone out there!

Body:
I am trying to log into a website as an admin and then navigate to another page (a portal) which requires this admin login beforehand to display data. I don't think I can access the cookies because of an issue accessing https cookies issue I read up on earlier (correct me if I'm wrong).

So my current solution is to enter the url as soon as the login process is complete and then continue with other tasks. Could you please advise on the methods/functions I can use to do this? If there are better ways to do this, I'd also be happy to hear about those!

var webdriver = require("selenium-webdriver");
var By = require("selenium-webdriver").By;
var until = require("selenium-webdriver").until;
var assert = require("chai").assert;
var filename = "img";
var fs = require('fs');
var err = "error caught!";
var testName = "get_login_cookies";

var driver = new webdriver.Builder()
    .forBrowser('chrome')
    .build();

describe('email register', function ()  {
    this.timeout(25000);

before(function(done) {
    driver.navigate().to('https://www.perlego.com/#');
    driver.manage().deleteAllCookies;
    driver.manage().window().maximize()
    .then(() => done())
});

it('logs in with admin user and gets cookies', (done) => {

    driver.findElement(By.name('email')).sendKeys("user@example.com");
    driver.findElement(By.css('#password')).sendKeys("examplePassword");
    driver.findElement(By.css('.login-button')).click();

    // some code here to navigate to other page via url

    // runs remainder of tests

});

after(function(done) {
    driver.quit()
    .then(() => done())
});
});


问:
CSRF token gets passed in the header when performing POST
I'm setting up VueJS SPA on top of Django. I have Graphene endpoint running on /api and queries in graphiql run fine. I have set up frontend and I'm using Apollo Client to query server. There goes my setup:

```<code>const CSRFtoken = Cookies.get('csrftoken')

const networkInterface = createNetworkInterface({
  uri: '/api',
  transportBatching: true
})

networkInterface.use([{
  applyMiddleware (req, next) {
    if (!req.options.headers) {
      req.options.headers = {}  // Create the header object if needed.
    }
    req.options.headers['X-CSRFToken'] = CSRFtoken
    console.log('applied middleware')
    next()
  }
}])

const apolloClient = new ApolloClient({
  networkInterface,
  connectToDevTools: true
})

Vue.use(VueApollo)

const apolloProvider = new VueApollo({
  defaultClient: apolloClient
})

new Vue({
  el: '#app',
  apolloProvider,
  render: h => h(App)
});
</code>```

My POST requests have the 'X-CSRFToken' header with value provided by Cookies. Screenshot below:

Unfortunately Django forbids access (error 403) with message: "CSRF cookie missing".

I have searched through the web but can't find anything related.

Thanks in advance!

答:
TL;DR: The issue is lack of the cookies in the headers, including csrftoken.

To fix this, append

```<code>  opts: {
    credentials: 'same-origin'
  }
</code>```

to the createNetworkInterface initialization, like below.

```<code>// headers for auth
const networkInterface = createNetworkInterface({
  uri: '//localhost:8000/api',
  transportBatching: true,
  opts: {
    credentials: 'same-origin'
  }
})
</code>```

Long story:

I've been fiddling with this for the last two days, asking around on Django and Apollo community channels. I was really desperate, so I considered switching from Apollo to other GraphQL client. I looked at the reference implementation over at http://graphql.org/graphql-js/graphql-clients/. It looks like this:

```<code>var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open("POST", "/graphql");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
xhr.onload = function () {
  console.log('data returned:', xhr.response);
}
xhr.send(JSON.stringify({query: "{ hello }"}));
</code>```

I have thrown it into my code, added the CSRF token cookie into headers and checked - it worked. I was really happy, but wanted to know why does one work, while other does not. As written above, I have discovered that the Apollo's request lacked Cookies Header. Actually XMLHttpRequest con is that you can't send request without adding Cookies - while Fetch API allows you to do so. And Apollo's based on Fetch API. I checked the documentation of the client and it was there. :)

Body:
I'm setting up VueJS SPA on top of Django. I have Graphene endpoint running on /api and queries in graphiql run fine. I have set up frontend and I'm using Apollo Client to query server. There goes my setup:

const CSRFtoken = Cookies.get('csrftoken')

const networkInterface = createNetworkInterface({
  uri: '/api',
  transportBatching: true
})

networkInterface.use([{
  applyMiddleware (req, next) {
    if (!req.options.headers) {
      req.options.headers = {}  // Create the header object if needed.
    }
    req.options.headers['X-CSRFToken'] = CSRFtoken
    console.log('applied middleware')
    next()
  }
}])

const apolloClient = new ApolloClient({
  networkInterface,
  connectToDevTools: true
})

Vue.use(VueApollo)

const apolloProvider = new VueApollo({
  defaultClient: apolloClient
})

new Vue({
  el: '#app',
  apolloProvider,
  render: h => h(App)
});

My POST requests have the 'X-CSRFToken' header with value provided by Cookies. Screenshot below:

Unfortunately Django forbids access (error 403) with message: "CSRF cookie missing".

I have searched through the web but can't find anything related.

Thanks in advance!

Body:
TL;DR: The issue is lack of the cookies in the headers, including csrftoken.

To fix this, append

  opts: {
    credentials: 'same-origin'
  }

to the createNetworkInterface initialization, like below.

// headers for auth
const networkInterface = createNetworkInterface({
  uri: '//localhost:8000/api',
  transportBatching: true,
  opts: {
    credentials: 'same-origin'
  }
})

Long story:

I've been fiddling with this for the last two days, asking around on Django and Apollo community channels. I was really desperate, so I considered switching from Apollo to other GraphQL client. I looked at the reference implementation over at http://graphql.org/graphql-js/graphql-clients/. It looks like this:

var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open("POST", "/graphql");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
xhr.onload = function () {
  console.log('data returned:', xhr.response);
}
xhr.send(JSON.stringify({query: "{ hello }"}));

I have thrown it into my code, added the CSRF token cookie into headers and checked - it worked. I was really happy, but wanted to know why does one work, while other does not. As written above, I have discovered that the Apollo's request lacked Cookies Header. Actually XMLHttpRequest con is that you can't send request without adding Cookies - while Fetch API allows you to do so. And Apollo's based on Fetch API. I checked the documentation of the client and it was there. :)


问:
GUI Layout of My Text Game
Hi I am trying to work on the GUI of my text based game with a border layout, and I almost have what I am trying to achieve with the GUI.

Here is what I want. I have almost everything down.. besides the Buttons. I want it to look like it does in my sketch.

Can I get any help on how to achieve this?

Here is my class for setting up the GUI:

```<code>package Story1;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;

public class textGUI extends JFrame{
    private JButton button;
    private JTextArea plot;
    private JLabel label;

public textGUI()
{
    createView();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setMinimumSize(new Dimension(400,200));
    setSize(400,200);
    setLocationRelativeTo(null);
    setResizable(true);
    setVisible(true);
}
public void createView()
{
    Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    // PANEL
    JPanel panel = new JPanel();
    panel.setBorder(new EmptyBorder(10,10,10,10));
    panel.setLayout(new BorderLayout());
    getContentPane().add(panel);
    //NORTH
    JPanel panelnorth = new JPanel(new BorderLayout());
    panel.add(panelnorth, BorderLayout.NORTH);
    panelnorth.add(new JLabel("Chapter 1"));
    //

   //TEXTFIELD CENTER
    JTextArea plot = new JTextArea();
    plot.setLineWrap(true);
    plot.setWrapStyleWord(true);
    plot.setEditable(true);
    JScrollPane scrollPane = new JScrollPane(plot);
    panel.add(scrollPane);
    //S
    //SOUTH
    JPanel south = new JPanel();
    panel.add(south, BorderLayout.SOUTH);
    JButton button1 = new JButton("HI");
    JButton button2 = new JButton("Okay");
    JButton button3 = new JButton("Bye");
    button1.setPreferredSize(new Dimension(screenSize.width, 10));
    south.add(button1);
    south.add(button2);
    south.add(button3);

    }
}
</code>```

答:
For your design a GridLayout is likely the best option. In this case the GridLayout should have rows set to 0 (which means any number of rows) and columns to 1 (meaning only 1 column) using the constructor GridLayout(int rows, int cols).

Expanding your source code to demonstrate:

```<code>JPanel south = new JPanel();
south.setLayout(new GridLayout(0, 1));
panel.add(south, BorderLayout.SOUTH);
JButton button1 = new JButton("HI");
JButton button2 = new JButton("Okay");
JButton button3 = new JButton("Bye");
south.add(button1);
south.add(button2);
south.add(button3);
</code>```

Title: GUI Layout of My Text Game

Body:
Hi I am trying to work on the GUI of my text based game with a border layout, and I almost have what I am trying to achieve with the GUI.

Here is what I want. I have almost everything down.. besides the Buttons. I want it to look like it does in my sketch.

Can I get any help on how to achieve this?

Here is my class for setting up the GUI:

package Story1;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;

public class textGUI extends JFrame{
    private JButton button;
    private JTextArea plot;
    private JLabel label;

public textGUI()
{
    createView();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setMinimumSize(new Dimension(400,200));
    setSize(400,200);
    setLocationRelativeTo(null);
    setResizable(true);
    setVisible(true);
}
public void createView()
{
    Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    // PANEL
    JPanel panel = new JPanel();
    panel.setBorder(new EmptyBorder(10,10,10,10));
    panel.setLayout(new BorderLayout());
    getContentPane().add(panel);
    //NORTH
    JPanel panelnorth = new JPanel(new BorderLayout());
    panel.add(panelnorth, BorderLayout.NORTH);
    panelnorth.add(new JLabel("Chapter 1"));
    //

   //TEXTFIELD CENTER
    JTextArea plot = new JTextArea();
    plot.setLineWrap(true);
    plot.setWrapStyleWord(true);
    plot.setEditable(true);
    JScrollPane scrollPane = new JScrollPane(plot);
    panel.add(scrollPane);
    //S
    //SOUTH
    JPanel south = new JPanel();
    panel.add(south, BorderLayout.SOUTH);
    JButton button1 = new JButton("HI");
    JButton button2 = new JButton("Okay");
    JButton button3 = new JButton("Bye");
    button1.setPreferredSize(new Dimension(screenSize.width, 10));
    south.add(button1);
    south.add(button2);
    south.add(button3);

    }
}

Body:
For your design a GridLayout is likely the best option. In this case the GridLayout should have rows set to 0 (which means any number of rows) and columns to 1 (meaning only 1 column) using the constructor GridLayout(int rows, int cols).

Expanding your source code to demonstrate:

JPanel south = new JPanel();
south.setLayout(new GridLayout(0, 1));
panel.add(south, BorderLayout.SOUTH);
JButton button1 = new JButton("HI");
JButton button2 = new JButton("Okay");
JButton button3 = new JButton("Bye");
south.add(button1);
south.add(button2);
south.add(button3);


问:
How to Custom Tab bar item text
I am using five tab bar items in the tab bar,i want to custom the text which is displayed on that.Is it possible.Please help me in this.Thanks in advance

Thanks
ask

答:
You need to make a "TabBarItem" in the view controller in each space.

So in the init function for the root view controller of each tab bar item:

```<code>UIImage* anImage = [UIImage imageNamed:@"tabicon.png"];

UITabBarItem* theItem = [[UITabBarItem alloc] initWithTitle:@"Your custom text" image:anImage tag:0];

self.tabBarItem = theItem;

[theItem release];
</code>```

Title: How to Custom Tab bar item text

Body:
You need to make a "TabBarItem" in the view controller in each space.

So in the init function for the root view controller of each tab bar item:

UIImage* anImage = [UIImage imageNamed:@"tabicon.png"];

UITabBarItem* theItem = [[UITabBarItem alloc] initWithTitle:@"Your custom text" image:anImage tag:0];

self.tabBarItem = theItem;

[theItem release];


问:
Passing an String array to a Prepared Statement Array (JDBC + SQLServer)
I'm trying to pass an String array to a prepared statement, but it's returning this exception:

```<code>java.sql.SQLFeatureNotSupportedException: This operation is not supported.
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.createArrayOf(SQLServerConnection.java:2763)
    at entity.dao.getRecords(Dao.java:168)
    at entity.dao.main(Dao.java:227)
</code>```

my code is:

```<code>public List<Record> getRecords() throws SQLException {
        String sql = "select * from table where clause in (?)";

        PreparedStatement ps = this.connection.prepareStatement(sql);

        List<String> strings = new ArrayList<>();
        strings.add("string1");
        strings.add("string2");
        strings.add("string3");

        Array array = this.connection.createArrayOf("VARCHAR", strings.toArray());

        ps.setArray(1, array);

        ResultSet executeQuery = ps.executeQuery();
        List<Record> records = new ArrayList<Record>();
        Record record;
        while (executeQuery.next()) {
            // ...
        }
        return records;
    }
</code>```

the line of the exception is Array array = this.connection.createArrayOf("VARCHAR", strings.toArray());

it's when i try to create the Array.

I already searched how to pass the Array and everybody tells to do like this, but seems to don't work with SQLServer.

答:
you can use, Alternatively, a createQuery statemen (Entity Manager)</p>

```<code>String sql= "select * from Table table where table.clause IN :clauses";
Query query = em.createQuery(sql, Record.class);

List<String> strings = new ArrayList<>();
        strings.add("string1");
        strings.add("string2");
        strings.add("string3");

query.setParameter("clauses", strings );
List<Record> result= query .getResultList();
</code>```

Body:
I'm trying to pass an String array to a prepared statement, but it's returning this exception:

java.sql.SQLFeatureNotSupportedException: This operation is not supported.
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.createArrayOf(SQLServerConnection.java:2763)
    at entity.dao.getRecords(Dao.java:168)
    at entity.dao.main(Dao.java:227)

my code is:

public List<Record> getRecords() throws SQLException {
        String sql = "select * from table where clause in (?)";

        PreparedStatement ps = this.connection.prepareStatement(sql);

        List<String> strings = new ArrayList<>();
        strings.add("string1");
        strings.add("string2");
        strings.add("string3");

        Array array = this.connection.createArrayOf("VARCHAR", strings.toArray());

        ps.setArray(1, array);

        ResultSet executeQuery = ps.executeQuery();
        List<Record> records = new ArrayList<Record>();
        Record record;
        while (executeQuery.next()) {
            // ...
        }
        return records;
    }

the line of the exception is Array array = this.connection.createArrayOf("VARCHAR", strings.toArray());

it's when i try to create the Array.

I already searched how to pass the Array and everybody tells to do like this, but seems to don't work with SQLServer.

Body:
you can use, Alternatively, a createQuery statemen (Entity Manager)

String sql= "select * from Table table where table.clause IN :clauses";
Query query = em.createQuery(sql, Record.class);

List<String> strings = new ArrayList<>();
        strings.add("string1");
        strings.add("string2");
        strings.add("string3");

query.setParameter("clauses", strings );
List<Record> result= query .getResultList();


问:
listing csv files using python re.match
I have created a small code in python to list csv files in the current directory:

```<code>>>> for i in range(len(os.listdir())):
...     isMatch = re.search(r'\.csv$', os.listdir()[i])
...     if (isMatch):
...             print(os.listdir()[i])
...
HR_data.csv
HR_data2.csv
HR_data_WEKA.csv
WholesaleCustomersData.csv
>>>
</code>```

Is there a more elegant and shorter way to do this, like using lambda expressions???
Thanks very much./

答:
You don't need regex, and glob has overhead. Just use the inbuilt str.endswith function:

```<code>for filename in os.listdir():
    if filename.endswith('.csv'):
        print(filename)
</code>```

Also, it is more efficient to iterate over the elements in a list directly than iterating over the indices and then referencing the list. Especially when you consider, you keep calling os.listdir() everytime you want to access the ith file, which is extremely wasteful.

Here's an elegant alternative with filter:

```<code>for csv_files in filter(lambda x: x.endswith('.csv'), os.listdir()):
    print(csv_files)
</code>```

Works on both python2.x and 3.x.

Title: listing csv files using python re.match

Body:
I have created a small code in python to list csv files in the current directory:

>>> for i in range(len(os.listdir())):
...     isMatch = re.search(r'\.csv$', os.listdir()[i])
...     if (isMatch):
...             print(os.listdir()[i])
...
HR_data.csv
HR_data2.csv
HR_data_WEKA.csv
WholesaleCustomersData.csv
>>>

Is there a more elegant and shorter way to do this, like using lambda expressions???
Thanks very much./

Body:
You don't need regex, and glob has overhead. Just use the inbuilt str.endswith function:

for filename in os.listdir():
    if filename.endswith('.csv'):
        print(filename)

Also, it is more efficient to iterate over the elements in a list directly than iterating over the indices and then referencing the list. Especially when you consider, you keep calling os.listdir() everytime you want to access the ith file, which is extremely wasteful.

Here's an elegant alternative with filter:

for csv_files in filter(lambda x: x.endswith('.csv'), os.listdir()):
    print(csv_files)

Works on both python2.x and 3.x.


问:
Rendering "a" with optional href in React.js
I need to render a table with a link in one of the columns, and searching for a most elegant way to do it. My main problem is - not all table rows are supplied with that link. If link is present - I need that "a" tag rendered. If not - no need for "a" tag at all. Generally speaking I would like react to handle that choice (render vs not render) depending on this.state.

This is what I have at the moment.

```<code>React.createClass({
    getInitialState: function () {
        return {
            pipeline: this.props.data.pipeline,
            liveUrl: this.props.data.liveUrl,
            posted: this.props.data.created,
            expires: this.props.data.end
        };
    },

    render: function () {
        return (
            <tr className="posting-list">
                <td><a href={this.state.liveUrl} target="_blank">{this.state.pipeline}</a></td>
                <td>Posted</td>
                <td>
                    <input className="datepicker" type="text" value={this.state.posted}/>
                </td>
                <td>
                    <input className="datepicker" type="text" value={this.state.expires}/>
                </td>
                <td>UPDATE, DELETE</td>
            </tr>
        );
    }
});
</code>```

This results is DOM element :

XING_batch

This is not acceptable solution for me, because those blank hrefs are still clickable.
I also tried adding some logic to getInitalState(
liveUrl: (this.props.data.liveUrl !== "") ? this.props.data.liveUrl : "javascript:void;",
), which worked fine, but looks weird, and adds errors in console(Uncaught SyntaxError: Unexpected token ;)

The only way I've got left is creating  2 different components for

答:
You can choose the type of component at runtime, as well:
</p>

```<code>import * as React from "react";

const FooBar = props => {
  const Component = props.href ? "a" : "div";

  return (
    <Component href={href}>
      {props.children}
    </Component>
  );
};

<FooBar>Hello</FooBar> // <div>Hello</div>
<FooBar href="/">World</FooBar> // <a href="/">World</a>
</code>```

Body:
I need to render a table with a link in one of the columns, and searching for a most elegant way to do it. My main problem is - not all table rows are supplied with that link. If link is present - I need that "a" tag rendered. If not - no need for "a" tag at all. Generally speaking I would like react to handle that choice (render vs not render) depending on this.state.

This is what I have at the moment.

React.createClass({
    getInitialState: function () {
        return {
            pipeline: this.props.data.pipeline,
            liveUrl: this.props.data.liveUrl,
            posted: this.props.data.created,
            expires: this.props.data.end
        };
    },

    render: function () {
        return (

                {this.state.pipeline}
                Posted

                    <input className="datepicker" type="text" value={this.state.posted}/>

                    <input className="datepicker" type="text" value={this.state.expires}/>

                UPDATE, DELETE

        );
    }
});

This results is DOM element :

XING_batch

This is not acceptable solution for me, because those blank hrefs are still clickable.
I also tried adding some logic to getInitalState(
liveUrl: (this.props.data.liveUrl !== "") ? this.props.data.liveUrl : "javascript:void;",
), which worked fine, but looks weird, and adds errors in console(Uncaught SyntaxError: Unexpected token ;)

The only way I've got left is creating  2 different components for

Body:
You can choose the type of component at runtime, as well:

import * as React from "react";

const FooBar = props => {
  const Component = props.href ? "a" : "div";

  return (
    <Component href={href}>
      {props.children}
    </Component>
  );
};

<FooBar>Hello</FooBar> // <div>Hello</div>
<FooBar href="/">World</FooBar> // <a href="/">World</a>


问:
How can I keep only one summary at a time in an event file?
I have a situation where I only want to store a single tensor at a time. IIUC, the FileWriter appends summaries to the existing event file. Right now, every time I want to write a summary, I do the following in a class init:

```<code>self.WRITER = tf.summary.FileWriter(self.LOGDIR,
                                    max_queue=1,
                                    flush_secs=9999999)
</code>```

and in a class method:

```<code>summary = self.SESSION.run(tf.summary.tensor_summary('frame',
                                                     image_tensor))
self.WRITER.add_summary(summary)
self.WRITER.flush()
self.WRITER.close()
</code>```

With .close(), it only writes once. Without .close(), it appends to the event file. With self.WRITER.reopen() at the beginning of the method, it adds new event files. I would like to have a single event file that is overwritten every time.

Is there any way to do this through TensorFlow, or do I need to remove the old file manually and create a new summary at each iteration?

答:
There is no way to refresh the file with the last event as I see but you can use

```<code>os.remove("path/to/file")
</code>```

on each iteration.

Body:
I have a situation where I only want to store a single tensor at a time. IIUC, the FileWriter appends summaries to the existing event file. Right now, every time I want to write a summary, I do the following in a class init:

self.WRITER = tf.summary.FileWriter(self.LOGDIR,
                                    max_queue=1,
                                    flush_secs=9999999)

and in a class method:

summary = self.SESSION.run(tf.summary.tensor_summary('frame',
                                                     image_tensor))
self.WRITER.add_summary(summary)
self.WRITER.flush()
self.WRITER.close()

With .close(), it only writes once. Without .close(), it appends to the event file. With self.WRITER.reopen() at the beginning of the method, it adds new event files. I would like to have a single event file that is overwritten every time.

Is there any way to do this through TensorFlow, or do I need to remove the old file manually and create a new summary at each iteration?

Body:
There is no way to refresh the file with the last event as I see but you can use

os.remove("path/to/file")

on each iteration.


问:
How to set a function callback to a private function of a class?
I need to set function as a callback for a function that is provided by an API. Now the API provides an example that allowed me to write this code and it works:
In the header file:

```<code>#include <iostream>

int __stdcall newDataAvailable(SampleStruct datum);
class Interface:

public:

    Interface();

    // Connects to the local server. Returns false if it fails.
    bool connectToServer();

private:

};
</code>```

And in the implementation I have:

```<code>Interface::Interface()
{
    iV_SetSampleCallback(newDataAvailable);
}

bool Interface::connectToServer(){

// code to connect to server
}

int __stdcall newDataAvailable(SampleStruct datum){
    std::cout << "New DATA" << std::endl;
    return 0;
}
</code>```

So, so far so good. Now the problem comes when I want to make the function newDataAvailable part of the class. So I copy the header into the private area of the class declaraion, add an Interface:: in the implemetation cpp file and try agai.

However I do not know how to make the connection, as it fails to compile. This is what I've tried:

```<code>iV_SetSampleCallback(&newDataAvailable); // Gives me illegal & operation
iV_SetSampleCallback(Interface::newDataAvailable);  // error: C3867: 'Interface::newDataAvailable': non-standard syntax; use '&' to create a pointer to member
iV_SetSampleCallback(&Interface::newDataAvailable); // error: C2664: 'int iV_SetSampleCallback(pDLLSetSample)': cannot convert argument 1 from 'int (__stdcall Interface::* )(SampleStruct)' to 'pDLLSetSample'
iV_SetSampleCallback(newDataAvailable); // error: C3867: 'Interface::newDataAvailable': non-standard syntax; use '&' to create a pointer to member
</code>```

So what is the proper way to set the callback?

答: You can add newDataAvailable function has part of class by declaring it as static. Once that function has been declared static then you can use it as part of callback function. Not sure if that is your intention.

Body:
I need to set function as a callback for a function that is provided by an API. Now the API provides an example that allowed me to write this code and it works:
In the header file:

#include <iostream>

int __stdcall newDataAvailable(SampleStruct datum);
class Interface:

public:

    Interface();

    // Connects to the local server. Returns false if it fails.
    bool connectToServer();

private:

};

And in the implementation I have:

Interface::Interface()
{
    iV_SetSampleCallback(newDataAvailable);
}

bool Interface::connectToServer(){

// code to connect to server
}

int __stdcall newDataAvailable(SampleStruct datum){
    std::cout << "New DATA" << std::endl;
    return 0;
}

So, so far so good. Now the problem comes when I want to make the function newDataAvailable part of the class. So I copy the header into the private area of the class declaraion, add an Interface:: in the implemetation cpp file and try agai.

However I do not know how to make the connection, as it fails to compile. This is what I've tried:

iV_SetSampleCallback(&newDataAvailable); // Gives me illegal & operation
iV_SetSampleCallback(Interface::newDataAvailable);  // error: C3867: 'Interface::newDataAvailable': non-standard syntax; use '&' to create a pointer to member
iV_SetSampleCallback(&Interface::newDataAvailable); // error: C2664: 'int iV_SetSampleCallback(pDLLSetSample)': cannot convert argument 1 from 'int (__stdcall Interface::* )(SampleStruct)' to 'pDLLSetSample'
iV_SetSampleCallback(newDataAvailable); // error: C3867: 'Interface::newDataAvailable': non-standard syntax; use '&' to create a pointer to member

So what is the proper way to set the callback?


问:
Concurrency in PHP/MYSQL
I have the following situation :

I have a list of items viewed by several users, each item can be acquired by a single user by clicking the button "acquire" in the right of each item, I'm wondering if checking the status of the item (a boolean in items table acquired : true/false) is enough to ensure that an item can't be acquired by more than one user? or is there any practical way to do that in php/mysql ?
Cordially,
Youssef.

答:
In pure php no, as a php page cannot update itself on the fly.

However using AJAX is can be done. Whether it's practical is another story, as it will depend on the number of items you wish to check against. Even then there will always be a delay which will vary depending on the server speed, the users connection speed, etc.

Your best bet would be to have a message saying something like "Checking" once a user has pressed acquire, do the check using AJAX, and on a first come first serve basis whoever got there first will still get the item.

So your next step would be to look up AJAX (Javascript).

The alternative will be to do a full page reload to check if the item is still available, and display a disclaimer beforehand that this will happen. This approach will just take longer than using AJAX due to the full page reload.

Title: Concurrency in PHP/MYSQL


问:
Adobe Brackets + jQuery file type
I've recently started learning jQuery and I ran into the problem that the Brackets editor (my favorite one) does not recognize the syntax of this language and puts JavaScript file type by default, which creates a lot of errors.
How can I deal with it?</p>

答:
I know what you mean... I’ve found that Brackets only recognizes jQuery when you include the library in the file; that is, when you: a) paste the whole library on top of your script (which obviously is inefficient and has a lot of drawbacks) or b) write it in an html file with the script linking to jQuery before the script of your code. Either way, Brackets will understand the syntax as it is now being defined in the same document.
In short, as far as I know, it can only be done in HTML</p>

Title: Adobe Brackets + jQuery file type


问:
ansible module actions without install
I'm writing an Ansible playbook to configure new machines for our developing environment.

If I want to install postgresql using homebrew, I would use Ansible's given homebrew model to achieve this task.

But before I run this task, should I have a task that will install homebrew first?

If this is the case, how can I install homebrew using the command or shell Ansible module, which will normally prompt for a user input during the process of installation?

答:
Yes, you have to install Homebrew first. The homebrew Ansible module documentation is not clear about that; if you check its source code it fails if it can’t find Homebrew and it doesn’t try to install it for you.

There already are answers on how to bypass the prompt in Homebrew’s install script. There are also other ways of installing Homebrew like downloading it as a tarball and un-taring it somewhere (which you can do with the unarchive Ansible module) or cloning its source code using git.

Title: ansible module actions without install


问:
How to manage large MySQL databases (backup)
We have a production MySQL database of about 320GB on disk.

We need to perform regular backups of the dataset but, either mysqldump or "copying table files" are taking hours to complete; moreover, both commands lock the database leading to an unusable website.

At the moment out tables are InnoDB and we have no replication, clustering, master&slave in place.

Is there any way we can perform daily backups without having to take down the website?

答:
And you don't have LVM in place either?  Remember the "Think Ahea..." signs?  Sorry; SOL.

And I guess you are using Windows, so you can't use Percona's XtraBackup?


问:
Where to get more information on Dictionary ADT and Skip List for Java?
I'm trying to go deep into Dictionary ADT and Skip List for Java. My textbook doesn't cover a lot about this and whatever it has covered is very complicated. Which is the best online site to get more information on Dictionary ADT and Skip List for Java. I'm looking for the one which talks visually and gives a lot of examples.</p>

答:
You can download the PDF of William Pugh's original paper describing skip lists and the theory behind it here.

Also, this is a good applet to visualize the operations of a skip list.  It helped me alot when skip lists came up in my data structures class.

Also, the Wikipedia entry has a few good links at the bottom for other implementations and the Java source code.

OwnerDisplayName: askgelal


问:
Assertion Test For Average
I am working on a skeleton provided to write a working implementation.

I must not leave any functions in the skeleton unused. Test that if implementation works.

Specifically -- if I test it, should be able to just press the [Run] button and see convincing evidence that your code works, because of:

a) the categorical reasoning displayed by your tests

b) the line(s) of output in the console log saying "passed" coming from those tests

So far here's my codes:

```<code>function assertEqual(actual, expected, testName) {
if(actual !== expected){
    console.error( "FAIL [" + testName + "] Expected \"" + expected + ", \" but got \"" + actual + "\"");
  } else {
    console.info( "SUCCESS [" + testName + "]");
  }
}

var numbers = [1, 3, 5];

function average(numbers) {
  // process array of numbers
  numbers.reduce(function(total, item){
    return total + item / numbers.length - 1;
  }, 0);
}

function sum(numbers) {
   numbers.reduce(function(total, item){
    return total + item;
  }, 0);
}

var avg = average(numbers);
console.log(avg);

var total = sum(numbers);
console.log(total);

assertEqual(avg, 4, 'it doubles 2 to 4');
assertEqual(sum, 4, 'it doubles 2 to 4');
</code>```

Any idea what am I missing? is this all correct?

答:
Your functions do not return any value, just add return statements like so :</p>

```<code>function average(numbers) {
 // process array of numbers
  return numbers.reduce(function(total, item){
    return total + item / numbers.length - 1;
  }, 0);
}

function sum(numbers) {
  return numbers.reduce(function(total, item){
    return total + item;
  }, 0);
}
</code>```

Title: Assertion Test For Average

Body:
I am working on a skeleton provided to write a working implementation.

I must not leave any functions in the skeleton unused. Test that if implementation works.

Specifically -- if I test it, should be able to just press the [Run] button and see convincing evidence that your code works, because of:

a) the categorical reasoning displayed by your tests

b) the line(s) of output in the console log saying "passed" coming from those tests

So far here's my codes:

function assertEqual(actual, expected, testName) {
if(actual !== expected){
    console.error( "FAIL [" + testName + "] Expected \"" + expected + ", \" but got \"" + actual + "\"");
  } else {
    console.info( "SUCCESS [" + testName + "]");
  }
}

var numbers = [1, 3, 5];

function average(numbers) {
  // process array of numbers
  numbers.reduce(function(total, item){
    return total + item / numbers.length - 1;
  }, 0);
}

function sum(numbers) {
   numbers.reduce(function(total, item){
    return total + item;
  }, 0);
}

var avg = average(numbers);
console.log(avg);

var total = sum(numbers);
console.log(total);

assertEqual(avg, 4, 'it doubles 2 to 4');
assertEqual(sum, 4, 'it doubles 2 to 4');

Any idea what am I missing? is this all correct?

Body:
Your functions do not return any value, just add return statements like so :

function average(numbers) {
 // process array of numbers
  return numbers.reduce(function(total, item){
    return total + item / numbers.length - 1;
  }, 0);
}

function sum(numbers) {
  return numbers.reduce(function(total, item){
    return total + item;
  }, 0);
}


问:
Fast iterative changes in pandas dataframe groups
I have a large pandas dataframe that consists of users, the products that each user bought and product prices.

The code I am using is showed below.

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random

# Create Dataframe randomly
product_list = ['P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8', 'P9', 'P10', 'P11', 'P12']
user_list = ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9', 'U10']
price_list = [50, 90, 100]

# Create random transactions
transactions = pd.DataFrame(np.random.choice(user_list, 200))
transactions['item'] = pd.DataFrame(np.random.choice(product_list, 200))
transactions['quantity'] = 1
transactions['price'] = np.random.choice([50, 90, 100], 200)
transactions.columns = ['user', 'item', 'quantity', 'price']
transactions['suggested_price'] = 0

# Create groups to apply suggested discount
grouped = transactions.groupby(["user", "item"])

# Apply suggested discount
for key, group in grouped:
    transactions.set_value(
        group.index, 'suggested_discount', np.random.random())
</code>```

My biggest problem with this code is the performance of the last block of code that applies the suggested discount to each user (customer). The original dataframe has over 6 million rows.

Also, one thing I noticed is that the slowest step is when I change the value of the groups, i.e., the line:

```<code>transactions.set_value(
            group.index, 'suggested_discount', np.random.random())
</code>```

In the original code there are other steps before this line of code.

I was not expecting that changing the values of the group columns would be so slow. Is there a better, faster implementation?

Thanks!

答:
Let's say that instead of np.random.random() you have a function that takes arguments from the price and suggested price columns, you should try to either use apply or transform or agg to those columns. Scalar operations instead of for loop will be much quicker.

For example, first set the user and item fields as indexes, then you can directly set a value from the grouped data to that new dataframe:

```<code>tr=transactions.set_index(["user","item"])
tr["suggested discount"]=transactions.groupby(["user", "item"])[["price","suggested_price"]].apply(pd.Series.sum)
</code>```

Anyhow, the key is not using a for loop.

Body:
I have a large pandas dataframe that consists of users, the products that each user bought and product prices.

The code I am using is showed below.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random

# Create Dataframe randomly
product_list = ['P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8', 'P9', 'P10', 'P11', 'P12']
user_list = ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9', 'U10']
price_list = [50, 90, 100]

# Create random transactions
transactions = pd.DataFrame(np.random.choice(user_list, 200))
transactions['item'] = pd.DataFrame(np.random.choice(product_list, 200))
transactions['quantity'] = 1
transactions['price'] = np.random.choice([50, 90, 100], 200)
transactions.columns = ['user', 'item', 'quantity', 'price']
transactions['suggested_price'] = 0

# Create groups to apply suggested discount
grouped = transactions.groupby(["user", "item"])

# Apply suggested discount
for key, group in grouped:
    transactions.set_value(
        group.index, 'suggested_discount', np.random.random())

My biggest problem with this code is the performance of the last block of code that applies the suggested discount to each user (customer). The original dataframe has over 6 million rows.

Also, one thing I noticed is that the slowest step is when I change the value of the groups, i.e., the line:

transactions.set_value(
            group.index, 'suggested_discount', np.random.random())

In the original code there are other steps before this line of code.

I was not expecting that changing the values of the group columns would be so slow. Is there a better, faster implementation?

Thanks!

Body:
Let's say that instead of np.random.random() you have a function that takes arguments from the price and suggested price columns, you should try to either use apply or transform or agg to those columns. Scalar operations instead of for loop will be much quicker.

For example, first set the user and item fields as indexes, then you can directly set a value from the grouped data to that new dataframe:

tr=transactions.set_index(["user","item"])
tr["suggested discount"]=transactions.groupby(["user", "item"])[["price","suggested_price"]].apply(pd.Series.sum)

Anyhow, the key is not using a for loop.


问:
laravel framework : is it safe to move index.php from public folder to the project root?
i know the public folder is there for a reason , but i have to upload a laravel project on a shared hosting and i dont have access to server to change the host root to public_html/public so it have to load from public_html

so i've moved index.php and htaccss from public to root and it works fine , but now anyone can directly access project files models / controller / etc.... im not sure if it's harmful but i know its not super safe !

so is it safe to do this ?  any other option beside getting a vps ?

pleas note im just a programmer and it's not my decision where to upload the project so pleas dont talk about how cheap and easy is to get a vps these days !

答:
To answer your question, no.  It isn't safe.  Depending on how your server is set up a malicious user may be able to download your PHP files as text files and read them... including things like DB passwords and SQL query structures.  That's bad.  An axiom of web programming is "never trust anybody, not even yourself."  That includes your server setup.  Best practice is to move all principle PHP files outside the web root.

If you cannot do that, your only option is to push all the files down one level inside the web root (e.g., /web_root/secure_directories/.) and use .htaccess to stop everyone but localhost from looking in that directory.  Your .htaccess file would look like this:

```<code>order deny,allow
deny from all
allow from 127.0.0.1
</code>```

Theoretically, if all your principle PHP files are in one subfolder (which may then contain many more subfolders), then you only need do this for the "top" folder.

Note that it's ideal to gain access to a directory outside of your web root simply because .htaccess functions slow your server down.  It won't be noticable if you don't have a lot of visitors... but it will when you do.

Body:
To answer your question, no.  It isn't safe.  Depending on how your server is set up a malicious user may be able to download your PHP files as text files and read them... including things like DB passwords and SQL query structures.  That's bad.  An axiom of web programming is "never trust anybody, not even yourself."  That includes your server setup.  Best practice is to move all principle PHP files outside the web root.

If you cannot do that, your only option is to push all the files down one level inside the web root (e.g., /web_root/secure_directories/.) and use .htaccess to stop everyone but localhost from looking in that directory.  Your .htaccess file would look like this:

order deny,allow
deny from all
allow from 127.0.0.1

Theoretically, if all your principle PHP files are in one subfolder (which may then contain many more subfolders), then you only need do this for the "top" folder.

Note that it's ideal to gain access to a directory outside of your web root simply because .htaccess functions slow your server down.  It won't be noticable if you don't have a lot of visitors... but it will when you do.


问:
Save compressed files into s3 and load in Athena
Hi I am writing some program that will write in some files (with more processes at the time) like:

```<code>with gzip.open('filename.gz', 'a') as f:
    f.write(json.dumps(some dictionary) + '\n')
    f.flush()
</code>```

After writing finishes I upload files with:

```<code>s3.meta.client(filename, bucket, destination, filename without .gz)
</code>```

Than I want to query data from Athena, after MSCK REPAIR everything seems fine but when I try to select data my rows are empty. Does anyone know what am I doing wrong?

EDIT: My mistake. I have forgot to add ContentType parameter to 'text/plain'

答:
I suggest you break the problem into several parts.

First, create a single JSON file that is not gzipped. Store it in Amazon S3, then use Athena to query it.

Once that works, manually gzip the file from the command-line (rather than programmatically), put the file in S3 and use Athena to query it.

If that works, use your code to programmatically gzip it, and try it again.

If that works with a single file, try it with multiple files.

All of the above can be tested with the same command in Athena -- you're simply substituting the source file.

This way, you'll know which part of the process is upsetting Athena without compounding the potential causes.

Body:
Hi I am writing some program that will write in some files (with more processes at the time) like:

with gzip.open('filename.gz', 'a') as f:
    f.write(json.dumps(some dictionary) + '\n')
    f.flush()

After writing finishes I upload files with:

s3.meta.client(filename, bucket, destination, filename without .gz)

Than I want to query data from Athena, after MSCK REPAIR everything seems fine but when I try to select data my rows are empty. Does anyone know what am I doing wrong?

EDIT: My mistake. I have forgot to add ContentType parameter to 'text/plain'