问:
backward count in a numpy array
Let's suppose I have a series of integer values arranged in a numpy array like this.

```<code>nan = np.nan
arr = np.array([3, nan, nan, nan, 5, nan, nan, nan, nan, nan])
</code>```

nan values should be filled with backward count from the first not null value to zero.

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

答:
IMO, the simplest pandas way of doing this is using groupby and cumcount with ascending=False:

```<code>s = pd.Series(np.cumsum(~np.isnan(arr)))
s.groupby(s).cumcount(ascending=False)

0    3
1    2
2    1
3    0
4    5
5    4
6    3
7    2
8    1
9    0
dtype: int64
</code>```

Title: backward count in a numpy array

Body:
Let's suppose I have a series of integer values arranged in a numpy array like this.

nan = np.nan
arr = np.array([3, nan, nan, nan, 5, nan, nan, nan, nan, nan])

nan values should be filled with backward count from the first not null value to zero.

[3, 2, 1, 0, 5, 4, 3, 2, 1, 0]

Body:
IMO, the simplest pandas way of doing this is using groupby and cumcount with ascending=False:

s = pd.Series(np.cumsum(~np.isnan(arr)))
s.groupby(s).cumcount(ascending=False)

0    3
1    2
2    1
3    0
4    5
5    4
6    3
7    2
8    1
9    0
dtype: int64


来源: stackexchange

问:
TypeError: unhashable type: 'Node'
I have this code that finds shortest and quickest path between a source and destination

```<code>class Node(object):
    def __init__(self, ID, name, power, generation):
        """
        Creates Node Object

        Requires: (id = int), (name = string), (power = int), (generation = int)
        """
        self.id = ID
        self.name = name
        self.power = power
        self.generation = generation

    def getId(self):
        """
        Gets id atribute.
        """
        return self.id

    def getName(self):
        """
        Get name atribute.
        """
        return self.name

    def getPower(self):
        """
        Get power atribute.
        """
        return self.power

    def getGeneration(self):
        """
        Get generation atribute.
        """
        return self.generation

    def allInfo(self):
        '''
        Gives a representation of each node atribiutes
        '''
        return "ID: " + str(self.id) + " | NAME: " + self.name + " | POWER: " + str(self.power) + " | GENERATION: " + str(self.generation)

    def __str__(self):
        return self.name

    def __eq__(self, other):
        '''
        Sets node if equal to other id if is an instance
        '''
        if isinstance(other, Node):
            return self.id == other.id
        return False```

```

<p>class Digraph(object):</p>

```def __init__(self):
    """
    Nodes is a list of the nodes in the graph.

    Edges is a dict mapping each node to a list of its children.
    """

    self.nodes = []
    self.edges = {}

def addNode(self, node):
    """
    Adds the nodes.
    """
    if node in self.nodes:
        raise ValueError('Duplicate node')
    else:
        self.nodes.append(node)
        self.edges[node] = []
```

<p>def main(args):
    '''
    Main function that receives args as the files given in the shell to iniciate program operation
    Requires:
    args is the older for the multiple files given to be read
    Ensures:
    Creates the output file with the stations time connections
    '''</p>

```stations = []
conns = []

file_in = open(args[1], "r")
for line in file_in:
    if (line[0] != "#"):
        station_info = line.split(", ")
        stations.append(Node(int(station_info[0]),
                             station_info[1],
                             int(station_info[2]),
                             int(station_info[3])))
        conns.append(line.split("(")[1].split(", "))

g = Digraph()

for station in stations:
    g.addNode(station)

aux = 0

for station in stations:
    for s in conns[aux]:
        # por \r\n em mac
        pos = (int(s.replace("\n", ""))) - 1
        g.addEdge(Edge(station, stations[int(pos)]))
    aux += 1
file_in.close()

file_in = open(args[2], "r")
maxTest = len(file_in.readlines())
file_in.close()

file_in = open(args[2], "r")
file_out = open(args[3], "w")

count = 0
for line in file_in:
    line = line.replace("\n", "")
    stationNames = line.split(" ")
    stop = False
    stationA = findStation(stations, stationNames[0])

    if stationA == None:
        file_out.write(stationNames[0] + " out of the network\n")
        stop = True

    stationB = findStation(stations, stationNames[1])
    if stationB == None:
        file_out.write(stationNames[1] + " out of the network\n")
        stop = True

    if stationA == stationB:
        file_out.write("Trying to connect same station (" + stationA.getName() + ", " + stationB.getName() + ")\n")
        stop = True

    if not stop:
        file_out.write(str(search(g, stationA, stationB)) + "\n")

    count += 1
    percentage = round(count * 100 / maxTest, 1)
    sys.stdout.write("\r     Progress: " + str(percentage) + "%     |     ")
    sys.stdout.write("Tested: " + str(count) + " of " + str(maxTest) + " connections!")
    sys.stdout.flush()

sys.stdout.write("\n")

file_in.close()
file_out.close()
```

```
but i'm getting this error

    C:\Users\André Ramos\Desktop\Project\Project\relayStationsGroup12>python
    relayStations.py inputFile1.txt inputFile2.txt out.txt

    ##########################  Relay Stations  ############################

    RelayStations is running...

    Traceback (most recent call last):
      File "relayStations.py", line 339, in <module>
       main(sys.argv)
      File "relayStations.py", line 270, in main
       g.addNode(station)
      File "relayStations.py", line 113, in addNode
       self.edges[node] = ()
    TypeError: unhashable type: 'Node'
```

答:
Your nodes are instances of custom Node class:

```<code>Node(int(station_info[0]),
     station_info[1],
     int(station_info[2]),
     int(station_info[3]))
</code>```

But Python dictionaries need their keys to be hashable:

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__()  method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their id().

So if you want to use your Nodes as dictionary keys, you have to implement __hash__ and __eq__ magic methods for them.

ContentLicense: CC BY-SA 4.0

Title: TypeError: unhashable type: 'Node'

Body:
I have this code that finds shortest and quickest path between a source and destination

class Node(object):
    def __init__(self, ID, name, power, generation):
        """
        Creates Node Object

        Requires: (id = int), (name = string), (power = int), (generation = int)
        """
        self.id = ID
        self.name = name
        self.power = power
        self.generation = generation

    def getId(self):
        """
        Gets id atribute.
        """
        return self.id

    def getName(self):
        """
        Get name atribute.
        """
        return self.name

    def getPower(self):
        """
        Get power atribute.
        """
        return self.power

    def getGeneration(self):
        """
        Get generation atribute.
        """
        return self.generation

    def allInfo(self):
        '''
        Gives a representation of each node atribiutes
        '''
        return "ID: " + str(self.id) + " | NAME: " + self.name + " | POWER: " + str(self.power) + " | GENERATION: " + str(self.generation)

    def __str__(self):
        return self.name

    def __eq__(self, other):
        '''
        Sets node if equal to other id if is an instance
        '''
        if isinstance(other, Node):
            return self.id == other.id
        return False```

class Digraph(object):

def __init__(self):
    """
    Nodes is a list of the nodes in the graph.

    Edges is a dict mapping each node to a list of its children.
    """

    self.nodes = []
    self.edges = {}

def addNode(self, node):
    """
    Adds the nodes.
    """
    if node in self.nodes:
        raise ValueError('Duplicate node')
    else:
        self.nodes.append(node)
        self.edges[node] = []

def main(args):
    '''
    Main function that receives args as the files given in the shell to iniciate program operation
    Requires:
    args is the older for the multiple files given to be read
    Ensures:
    Creates the output file with the stations time connections
    '''

stations = []
conns = []

file_in = open(args[1], "r")
for line in file_in:
    if (line[0] != "#"):
        station_info = line.split(", ")
        stations.append(Node(int(station_info[0]),
                             station_info[1],
                             int(station_info[2]),
                             int(station_info[3])))
        conns.append(line.split("(")[1].split(", "))

g = Digraph()

for station in stations:
    g.addNode(station)

aux = 0

for station in stations:
    for s in conns[aux]:
        # por \r\n em mac
        pos = (int(s.replace("\n", ""))) - 1
        g.addEdge(Edge(station, stations[int(pos)]))
    aux += 1
file_in.close()

file_in = open(args[2], "r")
maxTest = len(file_in.readlines())
file_in.close()

file_in = open(args[2], "r")
file_out = open(args[3], "w")

count = 0
for line in file_in:
    line = line.replace("\n", "")
    stationNames = line.split(" ")
    stop = False
    stationA = findStation(stations, stationNames[0])

    if stationA == None:
        file_out.write(stationNames[0] + " out of the network\n")
        stop = True

    stationB = findStation(stations, stationNames[1])
    if stationB == None:
        file_out.write(stationNames[1] + " out of the network\n")
        stop = True

    if stationA == stationB:
        file_out.write("Trying to connect same station (" + stationA.getName() + ", " + stationB.getName() + ")\n")
        stop = True

    if not stop:
        file_out.write(str(search(g, stationA, stationB)) + "\n")

    count += 1
    percentage = round(count * 100 / maxTest, 1)
    sys.stdout.write("\r     Progress: " + str(percentage) + "%     |     ")
    sys.stdout.write("Tested: " + str(count) + " of " + str(maxTest) + " connections!")
    sys.stdout.flush()

sys.stdout.write("\n")

file_in.close()
file_out.close()

but i'm getting this error

    C:\Users\André Ramos\Desktop\Project\Project\relayStationsGroup12>python
    relayStations.py inputFile1.txt inputFile2.txt out.txt

    ##########################  Relay Stations  ############################

    RelayStations is running...

    Traceback (most recent call last):
      File "relayStations.py", line 339, in <module>
       main(sys.argv)
      File "relayStations.py", line 270, in main
       g.addNode(station)
      File "relayStations.py", line 113, in addNode
       self.edges[node] = ()
    TypeError: unhashable type: 'Node'

Body:
Your nodes are instances of custom Node class:

Node(int(station_info[0]),
     station_info[1],
     int(station_info[2]),
     int(station_info[3]))

But Python dictionaries need their keys to be hashable:

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__()  method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their id().

So if you want to use your Nodes as dictionary keys, you have to implement __hash__ and __eq__ magic methods for them.


问:
Cannot get ASP.Net to serve any pages under IIS6
I am trying to set up another instance of a live website for a customer to evalulate, however i am unable to get the server to serve up any ASP.NET pages at all.

I know this is normally a bit of a noob question, but i have set up these servers a hundred times and know all the usual gotchas, i have done all of the following to no avail, and for my example i have created a simple test page that writes out hello world, and i'm still unable to get anything to serve..

This is windows server 2003 R2 SPII

I have registered ASP.NET using aspnet_regiis.exe -i

I have enabled the web service extensions

I have created it as a virtual directory, and created the application

I have set the version of ASP.NET for my virtual directory to use

I have even created a new App Pool and given it administrator permissions.

I have run Auth Diag From Microsoft, i get and error from the authentication check, but it is blank

I have given full control to the everyone group for the folder

I have tried creating a new website with a different port, same problem

In fiddler i get the following repsonse when loading an asp.net page :

```<code>HTTP/1.1 504 Fiddler - Receive Failure
Content-Type: text/html
Connection: close
Timestamp: 09:43:01:0634

ReadResponse() failed: The server did not return a response for this request.
</code>```

Looking at the IIS logs, i dont see any entries for any of the ASP.NET requests unless i turn on windows authentication, then i see

```<code>2011-04-12 08:13:23 W3SVC1 10.4.3.16 GET /test/Test.aspx - 80 - 10.2.16.17 Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+5.1;+Trident/4.0;+GTB6.6;+.NET+CLR+1.1.4322;+.NET+CLR+2.0.50727;+.NET+CLR+3.0.4506.2152;+.NET+CLR+3.5.30729;+InfoPath.2;+.NET4.0C;+.NET4.0E) - 401 2 2148074254

2011-04-12 08:13:26 W3SVC1 10.4.3.16 GET /test/Test.aspx - 80 - 10.2.16.17 Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+5.1;+Trident/4.0;+GTB6.6;+.NET+CLR+1.1.4322;+.NET+CLR+2.0.50727;+.NET+CLR+3.0.4506.2152;+.NET+CLR+3.5.30729;+InfoPath.2;+.NET4.0C;+.NET4.0E) - 401 1 0
</code>```

HTML Pages serve up just fine, i'm stumped and about to get the server re-built as i have wasted long enough on this..

Any ideas :( ?

答:
Have you checked the windows event log for information that may lead to what is causing this?

You could also try removing the application role and adding it again encase there was an issue when originally setting it up.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to set up another instance of a live website for a customer to evalulate, however i am unable to get the server to serve up any ASP.NET pages at all.

I know this is normally a bit of a noob question, but i have set up these servers a hundred times and know all the usual gotchas, i have done all of the following to no avail, and for my example i have created a simple test page that writes out hello world, and i'm still unable to get anything to serve..

This is windows server 2003 R2 SPII

I have registered ASP.NET using aspnet_regiis.exe -i

I have enabled the web service extensions

I have created it as a virtual directory, and created the application

I have set the version of ASP.NET for my virtual directory to use

I have even created a new App Pool and given it administrator permissions.

I have run Auth Diag From Microsoft, i get and error from the authentication check, but it is blank

I have given full control to the everyone group for the folder

I have tried creating a new website with a different port, same problem

In fiddler i get the following repsonse when loading an asp.net page :

HTTP/1.1 504 Fiddler - Receive Failure
Content-Type: text/html
Connection: close
Timestamp: 09:43:01:0634

ReadResponse() failed: The server did not return a response for this request.

Looking at the IIS logs, i dont see any entries for any of the ASP.NET requests unless i turn on windows authentication, then i see

2011-04-12 08:13:23 W3SVC1 10.4.3.16 GET /test/Test.aspx - 80 - 10.2.16.17 Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+5.1;+Trident/4.0;+GTB6.6;+.NET+CLR+1.1.4322;+.NET+CLR+2.0.50727;+.NET+CLR+3.0.4506.2152;+.NET+CLR+3.5.30729;+InfoPath.2;+.NET4.0C;+.NET4.0E) - 401 2 2148074254

2011-04-12 08:13:26 W3SVC1 10.4.3.16 GET /test/Test.aspx - 80 - 10.2.16.17 Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+5.1;+Trident/4.0;+GTB6.6;+.NET+CLR+1.1.4322;+.NET+CLR+2.0.50727;+.NET+CLR+3.0.4506.2152;+.NET+CLR+3.5.30729;+InfoPath.2;+.NET4.0C;+.NET4.0E) - 401 1 0

HTML Pages serve up just fine, i'm stumped and about to get the server re-built as i have wasted long enough on this..

Any ideas :( ?


问:
Chessboard distance in the image matrix
Given an image matrix, how can I get the locations of the pixels whose chessboard distances from pixel A is less than D. I need to performed this for all pixels.

Using the MATLAB function bwdist I couldn't provide desired result. What's the solution?

```<code>[D,idx] = bwdist(Img,'chessboard');
</code>```

答:
"The aim is to access the location of the pixels whose chessboard distances from pixel A is less than D. The process should be
  performed for all pixels..."

Since D is creating a square selection area, just use simple maths..

For example: if D is 3 then from the [x,y] position of pixel A...

```<code>//# we minus D by 1 since you want less than D (not equal / higher)

Start-X = pixelA.x - (D-1); //from the left
End-X = pixelA.y + (D-1); //to the right

Start-Y = pixelA.y - (D-1); //from the top
End-Y = pixelA.y + (D-1); //to the bottom
</code>```

That will give you a square perimeter that represents your required selection area.

Look at this example image below:

 Each square is a pixel. If the "crown" icon represents pixel A and D is 3 (where your "less than D" means D has a maximum length of 2 pixels), can you see how the pseudo-code above applies?

Title: Chessboard distance in the image matrix

Body:
Given an image matrix, how can I get the locations of the pixels whose chessboard distances from pixel A is less than D. I need to performed this for all pixels.

Using the MATLAB function bwdist I couldn't provide desired result. What's the solution?

[D,idx] = bwdist(Img,'chessboard');

Body:
"The aim is to access the location of the pixels whose chessboard distances from pixel A is less than D. The process should be
  performed for all pixels..."

Since D is creating a square selection area, just use simple maths..

For example: if D is 3 then from the [x,y] position of pixel A...

//# we minus D by 1 since you want less than D (not equal / higher)

Start-X = pixelA.x - (D-1); //from the left
End-X = pixelA.y + (D-1); //to the right

Start-Y = pixelA.y - (D-1); //from the top
End-Y = pixelA.y + (D-1); //to the bottom

That will give you a square perimeter that represents your required selection area.

Look at this example image below:

 Each square is a pixel. If the "crown" icon represents pixel A and D is 3 (where your "less than D" means D has a maximum length of 2 pixels), can you see how the pseudo-code above applies?


问:
How do I get constraints on a SQL Server table column
I have a column called MealType (VARCHAR) in my table with a CHECK constraint for {"Veg", "NonVeg", "Vegan"}

That'll take care of insertion.

I'd like to display these options for selection, but I couldn't figure out the SQL query to find out the constraints of a particular column in a table.

From a first glance at system tables in SQL Server, it seems like I'll need to use SQL Server's API to get the info. I was hoping for a SQL query itself to get it.

答:
You can use

```<code>sp_helpconstraint 'tableName', 'nomsg'
</code>```

to get all the constraints for the table.

"sp_help" return far more information.

Body:
You can use

sp_helpconstraint 'tableName', 'nomsg'

to get all the constraints for the table.

"sp_help" return far more information.


问:
I would like to replace the default image on the Homepage slideshow with the .SVG file that I have created
I have created a .SVG file on Adobe Illustrator.
I  would like to replace the default image on the Homepage slideshow with the .SVG file that I have created. I am using the Shopify platform.
Any support would be greatly appreciated. Thank you,</p>

答:
Remove the  tag with the default image you do not like. Paste in the  code you do like. Usually your home page is in index.liquid template.

1:1 swap out!


问:
No functions in C# DLL with RGiesecke.DllExport
I am trying to make a DLL in C# for use in a couple other languages.  I found RGiesecke's DllExport but it doesn't seem to work.  It builds just fine and makes a dll, but when I open it in Dependency Walker it doesn't show any functions, and my calling code can't find them either.

I created a new "Class Library" project (VS 2013) and then installed "Unmanaged Exports (DllExport for .Net)" from NuGet.  Are there any project settings I need?

Here is my code.

```<code>using System;
using System.Collections.Generic;
using System.Text;
using RGiesecke.DllExport;

namespace ToolServiceDLL
{
    public class Class1
    {
      [DllExport("addUp", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
      public static double addUp(double num1, double num2)
      {
        return num1 + num2;
      }

      [DllExport("get5", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
      public static int get5()
      {
        return 5;
      }
    }
}
</code>```

答:
This is a good question and worked for me. Just took a bit more time than it should due to the Python side where I made a mistake. Here is the working code in Python3

import sys
import clr
sys.path.insert(0,'C:\\your_path\\Py2NetComm\\bin\\Debug')
clr.AddReference("Py2NetComm")
import ToolServiceDLL as p2n
ret = p2n.Class1.addUp(2,3)
print("addUp:", ret)

Body:
I am trying to make a DLL in C# for use in a couple other languages.  I found RGiesecke's DllExport but it doesn't seem to work.  It builds just fine and makes a dll, but when I open it in Dependency Walker it doesn't show any functions, and my calling code can't find them either.

I created a new "Class Library" project (VS 2013) and then installed "Unmanaged Exports (DllExport for .Net)" from NuGet.  Are there any project settings I need?

Here is my code.

using System;
using System.Collections.Generic;
using System.Text;
using RGiesecke.DllExport;

namespace ToolServiceDLL
{
    public class Class1
    {
      [DllExport("addUp", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
      public static double addUp(double num1, double num2)
      {
        return num1 + num2;
      }

      [DllExport("get5", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
      public static int get5()
      {
        return 5;
      }
    }
}


问:
Increase numbers in col Y by 1 every time numbers in col X increases by 24
I want to increase my variables in column Y by 1 every time my column X increases by another 24. I have displayed the output I'm trying to create in column Y below.</p>

```<code>x<-c(5,10,15,20,25,27,29,42,47,49,50,60)
y<-c(1,1,1,1,2,2,2,2,2,3,3,3)
df<-data.frame(x,y)
</code>```

答:
The answer is</p>

```<code>floor(df$x/24) + 1
</code>```

Body:
I want to increase my variables in column Y by 1 every time my column X increases by another 24. I have displayed the output I'm trying to create in column Y below.

x<-c(5,10,15,20,25,27,29,42,47,49,50,60)
y<-c(1,1,1,1,2,2,2,2,2,3,3,3)
df<-data.frame(x,y)

Body:
The answer is

floor(df$x/24) + 1


问:
Python random.shuffle() on a list of lists returns a list of identical lists
In my script I need to generate a simple list of [1,2,3,4] values and then shuffle each one of those lists inside this list individually. I used random.shuffle() function which works fine on single arrays, but when I try to use it in a for loop the output is a list of shuffled arrays, but all of them identical:

[3, 1, 2, 4]

  [3, 1, 2, 4]

  [3, 1, 2, 4]

  etc...

I have tried running the script with different python versions (2.7, 3.6) but the problem persists.

Here is a simplified code that represents the issue:

```<code>import random

numbers_list = [1,2,3,4]
#make a list of 10 numbers_list
list_of_lists = [numbers_list]*10

#shuffle every list inside list_of_lists
for i in list_of_lists:
    random.shuffle(i)

#print every list from list_of_lists
for a in list_of_lists:
    print(a)
</code>```

Running the script multiple times results in different lists, but they always consist of a repeated one array. What can I do to fix it? Is it an issue with random.shuffle() or my script? What am I doing wrong?

答:
Culprit is there:

```<code>numbers_list = [1,2,3,4]
#make a list of 10 numbers_list
list_of_lists = [numbers_list]*10
</code>```

as now list_of_lists is in fact ONE list repeated 10 times, you could avoid that using .copy method as already shown or by replacing:

```<code>list_of_lists = [numbers_list]*10
</code>```

with

```<code>list_of_lists = [list(numbers_list) for _ in range(10)]
</code>```

or

```<code>list_of_lists = [numbers_list[:] for _ in range(10)]
</code>```

First one might be readed I want 10 times new list based on numbers_list and second harness so-called slicing.

Body:
In my script I need to generate a simple list of [1,2,3,4] values and then shuffle each one of those lists inside this list individually. I used random.shuffle() function which works fine on single arrays, but when I try to use it in a for loop the output is a list of shuffled arrays, but all of them identical:

[3, 1, 2, 4]

  [3, 1, 2, 4]

  [3, 1, 2, 4]

  etc...

I have tried running the script with different python versions (2.7, 3.6) but the problem persists.

Here is a simplified code that represents the issue:

import random

numbers_list = [1,2,3,4]
#make a list of 10 numbers_list
list_of_lists = [numbers_list]*10

#shuffle every list inside list_of_lists
for i in list_of_lists:
    random.shuffle(i)

#print every list from list_of_lists
for a in list_of_lists:
    print(a)

Running the script multiple times results in different lists, but they always consist of a repeated one array. What can I do to fix it? Is it an issue with random.shuffle() or my script? What am I doing wrong?

Body:
Culprit is there:

numbers_list = [1,2,3,4]
#make a list of 10 numbers_list
list_of_lists = [numbers_list]*10

as now list_of_lists is in fact ONE list repeated 10 times, you could avoid that using .copy method as already shown or by replacing:

list_of_lists = [numbers_list]*10

with

list_of_lists = [list(numbers_list) for _ in range(10)]

or

list_of_lists = [numbers_list[:] for _ in range(10)]

First one might be readed I want 10 times new list based on numbers_list and second harness so-called slicing.


问:
Use NumberFormatter with C format (e.g. "%6.3f")
Are there any extra functions to use the NumberFormatter (Swift 5) with a String that describes a C format?

Example: 12.3456 (Float) with "%6.3f" (C format as String) should turn into 12.345 (also Float)

Unfortunately Apple's documentation doesn't provide any examples.

I'm aware of maximumIntegerDigits and maximumFractionDigits and I know that you can use "%6.3" with NSLog and String(format: .......) but is there a function for NumberFormatter that turns the number directly into a Float or Double (not into a String), using the specified C format?

答:
If you need to use printf-style format strings, I would not suggest using NumberFormatter. It’s not designed for that. Just use String(format:_:). You appear to be reluctant to do that, but it’s not clear why.

So I might suggest:

```<code>func convert(format: String, _ value: Float) -> Float? {
    let string = String(format: format, value)
    return Float(string)
}
</code>```

You said:

Example: 12.3456 (Float) with "%6.3f" (C format as String) should turn into 12.345 (also Float)

Just to be clear, the following will produce 12.346, not 12.345. The printf-style format strings round, not truncate.

```<code>let value: Float = 12.3456
print(convert(format: "%6.3f", value) ?? "Unable to convert")
</code>```

By the way, if you want accurate representation of the value represented by the printf-style format, rather than generating a floating point type, you could generate a Decimal:

```<code>func convert(format: String, _ value: Double) -> Decimal? {
    let string = String(format: format, value)
    return Decimal(string: string)
}
</code>```

It just depends upon what you’re doing with this final result. I’ve also changed this to use Double, as it is very easy to exceed the meager 7 decimal digit precision permitted by Float.

Body:
If you need to use printf-style format strings, I would not suggest using NumberFormatter. It’s not designed for that. Just use String(format:_:). You appear to be reluctant to do that, but it’s not clear why.

So I might suggest:

func convert(format: String, _ value: Float) -> Float? {
    let string = String(format: format, value)
    return Float(string)
}

You said:

Example: 12.3456 (Float) with "%6.3f" (C format as String) should turn into 12.345 (also Float)

Just to be clear, the following will produce 12.346, not 12.345. The printf-style format strings round, not truncate.

let value: Float = 12.3456
print(convert(format: "%6.3f", value) ?? "Unable to convert")

By the way, if you want accurate representation of the value represented by the printf-style format, rather than generating a floating point type, you could generate a Decimal:

func convert(format: String, _ value: Double) -> Decimal? {
    let string = String(format: format, value)
    return Decimal(string: string)
}

It just depends upon what you’re doing with this final result. I’ve also changed this to use Double, as it is very easy to exceed the meager 7 decimal digit precision permitted by Float.


问:
@wraps() not behaving isn't returning the original functions values
I've written a fairly basic decorator:

```<code>def test_speed(f, *args, **kwargs):
    """This decorator will print out the time taken for input function to run."""

    @wraps(f)
    def wrapper():
        """Wrapper function returned by the outer function."""
        start = time.time()
        to_return = f(*args, **kwargs)
        end = time.time()
        print(f"The function {__name__} completed in {end-start} seconds.")

        return to_return
    return wrapper

</code>```

In a python script called decorators in a project called tools. I've added this project to my configuration in a second project which I'm using to practice using the multiprocessing module. I wrote some test functions to check the speed of multiprocessing some loops:

```<code>""" A script to practice using multiprocessing effectively in python."""

from decorators import *
from multiprocessing import *

def _loop(i, process_number):
    for i in range(i):
        if i % 500 == 0:
            print(f'{i} iterations of loop {process_number}.')

def serial_looping():

    _loop(10000, 'one')
    _loop(10000, 'two')
    _loop(10000, 'three')

@test_speed
def parallel_looping():
    loop_one = Process(target=_loop, args=(10000, 'one'))
    loop_two = Process(target=_loop, args=(10000, 'two'))
    loop_three = Process(target=_loop, args=(10000, 'three'))

if __name__ == '__main__':
    serial_looping()
    parallel_looping()

def serial_looping():

    _loop(10000, 'one')
    _loop(10000, 'two')
    _loop(10000, 'three')

@test_speed
def parallel_looping():
    loops = []
    loops.append(Process(target=_loop, args=(10000, 'one')))
    loops.append(Process(target=_loop, args=(10000, 'two')))
    loops.append(Process(target=_loop, args=(10000, 'three')))
    for loop in loops:
        loop.start()
        print('loop')

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

My issue is that when the wrapped function is called, in place of name it is stating the wrapper's project name, decorator, like so:

The function decorators completed in 5.841255187988281e-05 seconds.

surely this should read:
The function serial_looping completed in 5.841255187988281e-05 seconds.

答:
You should call __name__ on the function f:

print(f"The function {f.__name__} completed in {end-start} seconds.")

The reason is that __name__, by default refers to the enclosing function; I don't think @wraps overrides this behavior; it cannot know what precisely you intend to print.

Body:
I've written a fairly basic decorator:

def test_speed(f, *args, **kwargs):
    """This decorator will print out the time taken for input function to run."""

    @wraps(f)
    def wrapper():
        """Wrapper function returned by the outer function."""
        start = time.time()
        to_return = f(*args, **kwargs)
        end = time.time()
        print(f"The function {__name__} completed in {end-start} seconds.")

        return to_return
    return wrapper

In a python script called decorators in a project called tools. I've added this project to my configuration in a second project which I'm using to practice using the multiprocessing module. I wrote some test functions to check the speed of multiprocessing some loops:

""" A script to practice using multiprocessing effectively in python."""

from decorators import *
from multiprocessing import *

def _loop(i, process_number):
    for i in range(i):
        if i % 500 == 0:
            print(f'{i} iterations of loop {process_number}.')

def serial_looping():

    _loop(10000, 'one')
    _loop(10000, 'two')
    _loop(10000, 'three')

@test_speed
def parallel_looping():
    loop_one = Process(target=_loop, args=(10000, 'one'))
    loop_two = Process(target=_loop, args=(10000, 'two'))
    loop_three = Process(target=_loop, args=(10000, 'three'))

if __name__ == '__main__':
    serial_looping()
    parallel_looping()

def serial_looping():

    _loop(10000, 'one')
    _loop(10000, 'two')
    _loop(10000, 'three')

@test_speed
def parallel_looping():
    loops = []
    loops.append(Process(target=_loop, args=(10000, 'one')))
    loops.append(Process(target=_loop, args=(10000, 'two')))
    loops.append(Process(target=_loop, args=(10000, 'three')))
    for loop in loops:
        loop.start()
        print('loop')

if __name__ == '__main__':
    serial_looping()
    parallel_looping()

My issue is that when the wrapped function is called, in place of name it is stating the wrapper's project name, decorator, like so:

The function decorators completed in 5.841255187988281e-05 seconds.

surely this should read:
The function serial_looping completed in 5.841255187988281e-05 seconds.


问:
PHP - Pack array with binary data
There is a service (php) which sends an image to a client (php).

```<code>header('Content-Type: image/png');
readfile($image);
</code>```

What if it is needed to send not only an image but some data with it.

```<code>$arrayToSend = [
    'image' => file_get_contents($image),
    'some_data' => [
        'a' => 1,
        'b' => 2
    ]
];
</code>```

How the service can pack $arrayToSend so that the client can unpack it?

Without converting image to base64 (because of too large size).

答:
Maybe you could pass some_data-a and some_data-b as headers? For example, as a cookie.

You can help yourself with this document: https://developer.mozilla.org/pl/docs/Web/HTTP/Headers for more information about headers.

Title: PHP - Pack array with binary data

Body:
There is a service (php) which sends an image to a client (php).

header('Content-Type: image/png');
readfile($image);

What if it is needed to send not only an image but some data with it.

$arrayToSend = [
    'image' => file_get_contents($image),
    'some_data' => [
        'a' => 1,
        'b' => 2
    ]
];

How the service can pack $arrayToSend so that the client can unpack it?

Without converting image to base64 (because of too large size).


问:
Image src in Inspect Element showing up as [object Object]
I am trying to get the image to show up in my Section from my .json file. So, as always I added a prop to the component and parsed the values of the .json file which is config.dog.src . I console print this and the value comes out perfectly with dog.png in console. However, in the code in inspect element it shows [object Object]. Any idea?

I have tried changed the .json file around, and hard coding but that defeats the purpose of the .json file so dont really want to do that.

```<code>dog:{
    src: "dog.png"
}

<DogComponent src={config.dog.src} />
</code>```

Console inspect element shows the following:

Expected output should be:

答:
Sounds like you may be missing the file-loader for webpack. Add this to your webpack config module section, and make sure you are importing the image via resolvable path and it should work:

```<code>{
  test: /\.(jpe?g|png)$/i,
  include: path.resolve(__dirname, './'),
  loaders: ['file-loader']
}
</code>```

Body:
I am trying to get the image to show up in my Section from my .json file. So, as always I added a prop to the component and parsed the values of the .json file which is config.dog.src . I console print this and the value comes out perfectly with dog.png in console. However, in the code in inspect element it shows [object Object]. Any idea?

I have tried changed the .json file around, and hard coding but that defeats the purpose of the .json file so dont really want to do that.

dog:{
    src: "dog.png"
}

<DogComponent src={config.dog.src} />

Console inspect element shows the following:

Expected output should be:

Body:
Sounds like you may be missing the file-loader for webpack. Add this to your webpack config module section, and make sure you are importing the image via resolvable path and it should work:

{
  test: /\.(jpe?g|png)$/i,
  include: path.resolve(__dirname, './'),
  loaders: ['file-loader']
}


问:
Using Django signals to identify a present user session
i want to use django signals to identify if a user is logged-in twice and if so, revoke his first session so that only one user session can be present at once.

i used the following example but it seems that my signals.py does not even gets reconcnized and i dont know why.

Example:
How to prevent multiple login in Django

accounts/signals.py

```<code>from django.contrib.auth import user_logged_in
from django.dispatch.dispatcher import receiver
from django.contrib.sessions.models import Session
from .models import UserSession

@receiver(user_logged_in)
def remove_other_sessions(sender, user, request, **kwargs):
    # remove other sessions
    Session.objects.filter(usersession__user=user).delete()

    # save current session
    request.session.save()

    # create a link from the user to the current session (for later removal)
    UserSession.objects.get_or_create(
        user=user,
        session=Session.objects.get(pk=request.session.session_key)
    )
</code>```

accounts/models.py

```<code># Model to store the list of logged in users
class UserSession(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    session = models.OneToOneField(Session, on_delete=models.CASCADE)
</code>```

accounts/apps.py

```<code>from django.apps import AppConfig

class AccountsConfig(AppConfig):
    name = 'Accounts'

    def ready(self):
        import Accounts.signals
</code>```

but for some reason nothing gets written onto the database for that table.

do i maybe miss something here, this is the very first time i get in touch with signals so i might missed something at the configuration.

答:
Try this,

```<code>default_app_config = 'Accounts.apps.AccountsConfig'
</code>```

Add this line in __init__.py file of your apps.py file directory.

Body:
i want to use django signals to identify if a user is logged-in twice and if so, revoke his first session so that only one user session can be present at once.

i used the following example but it seems that my signals.py does not even gets reconcnized and i dont know why.

Example:
How to prevent multiple login in Django

accounts/signals.py

from django.contrib.auth import user_logged_in
from django.dispatch.dispatcher import receiver
from django.contrib.sessions.models import Session
from .models import UserSession

@receiver(user_logged_in)
def remove_other_sessions(sender, user, request, **kwargs):
    # remove other sessions
    Session.objects.filter(usersession__user=user).delete()

    # save current session
    request.session.save()

    # create a link from the user to the current session (for later removal)
    UserSession.objects.get_or_create(
        user=user,
        session=Session.objects.get(pk=request.session.session_key)
    )

accounts/models.py

# Model to store the list of logged in users
class UserSession(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    session = models.OneToOneField(Session, on_delete=models.CASCADE)

accounts/apps.py

from django.apps import AppConfig

class AccountsConfig(AppConfig):
    name = 'Accounts'

    def ready(self):
        import Accounts.signals

but for some reason nothing gets written onto the database for that table.

do i maybe miss something here, this is the very first time i get in touch with signals so i might missed something at the configuration.

Body:
Try this,

default_app_config = 'Accounts.apps.AccountsConfig'

Add this line in __init__.py file of your apps.py file directory.


问:
VBA: Error handling with labels and "On Error GoTo"
I have multiple procedures that look like the one below. The code itself is functional and does what it is supposed to do, but now I have one question and one problem regarding error handling:

How to use On Error GoTo 0:

The error which is causing me trouble occurrs in the line mySlide.Shapes.PasteSpecial DataType:=ppPasteEnhancedMetafile. It's my understanding that On Error GoTo 0 resets the error handling to the default behavior in VBA, meaning I should get the error displayed in the normal VBA-way. So I used it twice here: once directly after the line with which I paste what I copied and once directly after calling the ErrorHandler1 (and 2). Does this make sense? My reasoning was that with On Error GoTo ErrorHandler1 I only want to trap error -2147188160 and in the rest of the code I want the normal VBA error messages. Errors aren't that likely to occur there because there isn't a lot of code, but still.

```<code> Sub SubSlide1(wsKAP As Worksheet)

    Set mySlide = myPresentation.Slides(1)

RepeatOnError1:
    Set rng = wsKAP.Range("AC2:AN29")
    rng.Copy
    DoEvents
    On Error GoTo ErrorHandler1
    mySlide.Shapes.PasteSpecial DataType:=ppPasteEnhancedMetafile
    On Error GoTo 0
    Set myShape = mySlide.Shapes(mySlide.Shapes.Count)
    With myShape
        .Left = 20
        .Top = 48
        .Width = 623
    End With

RepeatOnError2:
    wsKAP.Columns("K:M").EntireColumn.Hidden = False
    On Error GoTo 0
    Set rng = wsKAP.Range("A187:V199")
    rng.Copy
    DoEvents
    On Error GoTo ErrorHandler2
    mySlide.Shapes.PasteSpecial DataType:=ppPasteEnhancedMetafile
    Set myShape = mySlide.Shapes(mySlide.Shapes.Count)
    With myShape
        .Left = 20
        .Top = 363
        .Width = 663
    End With
    wsKAP.Columns("K:M").EntireColumn.Hidden = True
    Application.CutCopyMode = False

    Exit Sub

ErrorHandler1:
    On Error GoTo 0
    If Err.Number = -2147188160 Then
        Call ErrorHandling(1)
    Else
        MsgBox "Fehler: " & Err.Number & ": " & Err.Description & vbNewLine & "Makro wird weiter ausgeführt."
    End If
    Resume RepeatOnError1

ErrorHandler2:
    On Error GoTo 0
    If Err.Number = -2147188160 Then
        Call ErrorHandling(2)
    Else
        MsgBox "Fehler: " & Err.Number & ": " & Err.Description & vbNewLine & "Makro wird weiter ausgeführt."
    End If
    Resume RepeatOnError2
End Sub

Sub ErrorHandling(Number As Long)
    If ErrorCount(Number) > 10 Then
        MsgBox "Too many errors (-2147188160) in ErrorCount(" & Number & "). Canceling."
        End
    End If

    ErrorCount(Number) = ErrorCount(Number) + 1
    Debug.Print "ErrorCount" & Number & " is " & ErrorCount(Number)
End Sub
</code>```

Sometimes when I run my code a MsgBox pops up: "Error: 0. Procedure will continue." (this has occured in the procedure you see here as well as in the other procedures, which are structurally the same). This means the else-statement in ErrorHandler1 gets triggered. My intention with the else was to let me know about any error that gets caught up in GoTo ErrorHandler1, but isn't -2147188160. As far as I know "Error 0" means there isn't an error, so how does VBA end up there?

edit: I've rearranged it now and added an End. I moved the Resume statement because otherwise I have the potential of an endless-error loop.

```<code>ErrorHandler1:

    If Err.Number = -2147188160 Then
        Call ErrorHandling(1)
        Resume RepeatOnError1
    Else
        MsgBox "Fehler: " & Err.Number & ": " & Err.Description & vbNewLine & "Makro wird weiter ausgeführt."
        End
    End If
    On Error GoTo 0

ErrorHandler2:

    If Err.Number = -2147188160 Then
        Call ErrorHandling(2)
        Resume RepeatOnError2
    Else
        MsgBox "Fehler: " & Err.Number & ": " & Err.Description & vbNewLine & "Makro wird weiter ausgeführt."
        End
    End If
    On Error GoTo 0

End Sub
</code>```

答:
```<code>On Error GoTo 0
If Err.Number = -2147188160 Then
</code>```

On Error Go To 0 also "clears" any current error. So you are clearing it before checking if it is equal to -2147188160. Re-arrange those statements and see if that works better:

```<code>If Err.Number = -2147188160 Then
    On Error GoTo 0
</code>```

Body:
I have multiple procedures that look like the one below. The code itself is functional and does what it is supposed to do, but now I have one question and one problem regarding error handling:

How to use On Error GoTo 0:

The error which is causing me trouble occurrs in the line mySlide.Shapes.PasteSpecial DataType:=ppPasteEnhancedMetafile. It's my understanding that On Error GoTo 0 resets the error handling to the default behavior in VBA, meaning I should get the error displayed in the normal VBA-way. So I used it twice here: once directly after the line with which I paste what I copied and once directly after calling the ErrorHandler1 (and 2). Does this make sense? My reasoning was that with On Error GoTo ErrorHandler1 I only want to trap error -2147188160 and in the rest of the code I want the normal VBA error messages. Errors aren't that likely to occur there because there isn't a lot of code, but still.

 Sub SubSlide1(wsKAP As Worksheet)

    Set mySlide = myPresentation.Slides(1)

RepeatOnError1:
    Set rng = wsKAP.Range("AC2:AN29")
    rng.Copy
    DoEvents
    On Error GoTo ErrorHandler1
    mySlide.Shapes.PasteSpecial DataType:=ppPasteEnhancedMetafile
    On Error GoTo 0
    Set myShape = mySlide.Shapes(mySlide.Shapes.Count)
    With myShape
        .Left = 20
        .Top = 48
        .Width = 623
    End With

RepeatOnError2:
    wsKAP.Columns("K:M").EntireColumn.Hidden = False
    On Error GoTo 0
    Set rng = wsKAP.Range("A187:V199")
    rng.Copy
    DoEvents
    On Error GoTo ErrorHandler2
    mySlide.Shapes.PasteSpecial DataType:=ppPasteEnhancedMetafile
    Set myShape = mySlide.Shapes(mySlide.Shapes.Count)
    With myShape
        .Left = 20
        .Top = 363
        .Width = 663
    End With
    wsKAP.Columns("K:M").EntireColumn.Hidden = True
    Application.CutCopyMode = False

    Exit Sub

ErrorHandler1:
    On Error GoTo 0
    If Err.Number = -2147188160 Then
        Call ErrorHandling(1)
    Else
        MsgBox "Fehler: " & Err.Number & ": " & Err.Description & vbNewLine & "Makro wird weiter ausgeführt."
    End If
    Resume RepeatOnError1

ErrorHandler2:
    On Error GoTo 0
    If Err.Number = -2147188160 Then
        Call ErrorHandling(2)
    Else
        MsgBox "Fehler: " & Err.Number & ": " & Err.Description & vbNewLine & "Makro wird weiter ausgeführt."
    End If
    Resume RepeatOnError2
End Sub

Sub ErrorHandling(Number As Long)
    If ErrorCount(Number) > 10 Then
        MsgBox "Too many errors (-2147188160) in ErrorCount(" & Number & "). Canceling."
        End
    End If

    ErrorCount(Number) = ErrorCount(Number) + 1
    Debug.Print "ErrorCount" & Number & " is " & ErrorCount(Number)
End Sub

Sometimes when I run my code a MsgBox pops up: "Error: 0. Procedure will continue." (this has occured in the procedure you see here as well as in the other procedures, which are structurally the same). This means the else-statement in ErrorHandler1 gets triggered. My intention with the else was to let me know about any error that gets caught up in GoTo ErrorHandler1, but isn't -2147188160. As far as I know "Error 0" means there isn't an error, so how does VBA end up there?

edit: I've rearranged it now and added an End. I moved the Resume statement because otherwise I have the potential of an endless-error loop.

ErrorHandler1:

    If Err.Number = -2147188160 Then
        Call ErrorHandling(1)
        Resume RepeatOnError1
    Else
        MsgBox "Fehler: " & Err.Number & ": " & Err.Description & vbNewLine & "Makro wird weiter ausgeführt."
        End
    End If
    On Error GoTo 0

ErrorHandler2:

    If Err.Number = -2147188160 Then
        Call ErrorHandling(2)
        Resume RepeatOnError2
    Else
        MsgBox "Fehler: " & Err.Number & ": " & Err.Description & vbNewLine & "Makro wird weiter ausgeführt."
        End
    End If
    On Error GoTo 0

End Sub

Body:
On Error GoTo 0
If Err.Number = -2147188160 Then

On Error Go To 0 also "clears" any current error. So you are clearing it before checking if it is equal to -2147188160. Re-arrange those statements and see if that works better:

If Err.Number = -2147188160 Then
    On Error GoTo 0


问:
Change number of decimals in Woocommerce cart totals
In Woocommerce, I've set the number of decimal to 7 on in Woocommerce general settings, so I can display the product price like this $0.0453321.

I'm wondering if I can set/round the cart total to only 2 decimals (something like this $2.34)?

答:
In my case I needed to keep 3 decimal places "visible" throughout the site but approximate only the grand total to 2 decimal places (with a zero for the third decimal place) because my payment gateway accepted only 2 significant digits after the decimal.

```<code>Prices displayed as: 0.336
Taxes: 0.017
But grand total needed to be: 0.350 (instead of 0.353)
</code>```

I ended up not using the code because it was so horrific but you can say it was a mental excercise:

```<code>add_filter( 'wc_get_price_decimals', 'change_prices_decimals', 20, 1 );
function change_prices_decimals( $decimals ){

    if( is_cart() || is_checkout() )
    {
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,0);
        $length = count($trace);
        for ($i = 0; $i < $length; $i++)
        {
            if($trace[$i]["function"] == "set_total"){
                $decimals = 2;
                return $decimals;
            }
        }
    }

    return $decimals;
}
</code>```

Body:
In my case I needed to keep 3 decimal places "visible" throughout the site but approximate only the grand total to 2 decimal places (with a zero for the third decimal place) because my payment gateway accepted only 2 significant digits after the decimal.

Prices displayed as: 0.336
Taxes: 0.017
But grand total needed to be: 0.350 (instead of 0.353)

I ended up not using the code because it was so horrific but you can say it was a mental excercise:

add_filter( 'wc_get_price_decimals', 'change_prices_decimals', 20, 1 );
function change_prices_decimals( $decimals ){

    if( is_cart() || is_checkout() )
    {
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,0);
        $length = count($trace);
        for ($i = 0; $i < $length; $i++)
        {
            if($trace[$i]["function"] == "set_total"){
                $decimals = 2;
                return $decimals;
            }
        }
    }

    return $decimals;
}


问:
Laravel cookie::forget doesn't work?
I have this code:

```<code>Cookie::forget('vendor');
return Redirect::route('vendor_login');
</code>```

What it is supposed to do, is remove the vendor cookie and redirect you to the login page. However, it doesn't actually delete the cookie. From my understanding, I would expect it to send a setcookie header for vendor with a value of null and a negative time. It doesn't send the setcookie header at all. Why is this?

This works perfectly:

```<code>Cookie::queue('paddle_vendor', null, -1);
return Redirect::route('vendor_login');
</code>```

答:
The default laravel

```<code>  Cookie::queue(
   Cookie::forget('name')
      ) ;
</code>```

Should work perfectly fine if you have not done any changes on your
      session.php
        config file.
Check it out and you should be good to go.

Title: Laravel cookie::forget doesn't work?

Body:
I have this code:

Cookie::forget('vendor');
return Redirect::route('vendor_login');

What it is supposed to do, is remove the vendor cookie and redirect you to the login page. However, it doesn't actually delete the cookie. From my understanding, I would expect it to send a setcookie header for vendor with a value of null and a negative time. It doesn't send the setcookie header at all. Why is this?

This works perfectly:

Cookie::queue('paddle_vendor', null, -1);
return Redirect::route('vendor_login');

Body:
The default laravel

  Cookie::queue(
   Cookie::forget('name')
      ) ;

Should work perfectly fine if you have not done any changes on your
      session.php
        config file.
Check it out and you should be good to go.


问:
Disassemble x86 code in a program at a specific address
Is there any x86 disassembler framework that can be used to analyze code from a specific address in a program, as in:

```<code>info = disassemble(  startAddress , stopAddress)
</code>```

It should show every instruction and its operands and any other info that is good for analysis but it should have also fast mode where it isn't so important to obtain that much info for each instruction, but only for some of them that can be specified.

答: Try BeaEngine </p>

ContentLicense: CC BY-SA 2.5

Body:
Is there any x86 disassembler framework that can be used to analyze code from a specific address in a program, as in:

info = disassemble(  startAddress , stopAddress)

It should show every instruction and its operands and any other info that is good for analysis but it should have also fast mode where it isn't so important to obtain that much info for each instruction, but only for some of them that can be specified.

Body: Try BeaEngine


问:
SSH to Google Compute instance using NodeJS, without gcloud
I'm trying to create a SSH tunnel into a compute instance, from an environment that doesn't have gcloud installed (App Engine Standard NodeJS Environment).

What are the steps needed to do that? How does gcloud compute ssh command does it? Is there a NodeJS library that already does it?

答:
"gcloud compute ssh" generates persistent SSH keys for the user. The public key is stored in project or instance SSH keys metadata, and the Guest Environment creates the necessary local user and places ~/.ssh/authorized_keys in its home directory.
You can manually add your public key to the instance, and then connect to it via ssh using a node ssh library1.
Or you can set a startup script for the instance when you are creating it2.
As Cloud Ace pointed out, you can use the ssh2 module3 for node.js compatibility.


问:
PHP Gives Me Wrong Result Of Subtraction With Floating Number
I have this code :

```<code><?php

$a = 991.3;

$float = floor($a);
$float = $a - $float;

echo $float;
</code>```

it gives me this as result:

```<code>0.29999999999995
</code>```

why not 0.3? and how to get 0.3 instead of 0.29999999999995?

答:
This is because PHP's precision with floating point numbers is not exact. This is warned of in the php manual entry about floating point number.

If you want mathematical precision for different operations, you must use PHP's bcmath extension. I bet it must be compiled already in your PHP installation, but if not, you can always google how to install it. :)

These are the functions you want to use.

Body:
I have this code :

<?php

$a = 991.3;

$float = floor($a);
$float = $a - $float;

echo $float;

it gives me this as result:

0.29999999999995

why not 0.3? and how to get 0.3 instead of 0.29999999999995?


问:
How to call a variable from a matrix... from a list?
Basically, it's in the title.
With more details though, I have four parameters set that need to be organised in matrices, that I organised in a list (Alphaset), each having 4 variables. But I need to call in specific variables into a loop where it will go through an equation and should give me a plot.

Me and my poor knowledge of R tried different combination that resulted in being inefficient, such as "Alphaset[2,1,1]" or "Alphaset[2(1,1)]"
(this is an exemple where I want to display the variable that's first row first column of the second matrix).

```<code>#Parameters set on types (lambda 1, lambda 2, alphas)

Lambda1set<-c(5,5,3,3.2)
Lambda2set<-c(4,4,5,3)
Alphaset<-list(matrix(c(0.01, 0.007, 0.0045, 0.01),ncol = 2, byrow = TRUE),
            matrix(c(0.01, 0.003, 0.007, 0.01),ncol = 2, byrow = TRUE),
            matrix(c(0.01, 0.0055, 0.003, 0.01),ncol = 2, byrow = TRUE),
            matrix(c(0.005, 0.005, 0.0045, 0.004),ncol = 2, byrow = TRUE))

#Creating vectors
TimeVec<-seq(0,years,1)
N1<-matrix(0,4,years+1)
N2<-matrix(0,4,years+1)

#INITIALIZATION
N0 <- 40
N1[1] <-N0
N2[1] <-N0

for (t in 1:years){
  for(i in 1:4){
  N1[i,t+1]<-(Lambda1set[i]*N1[i,t])/(1+alphs[1,1]*N1[i,t]+alphs[1,2]*N2[i,t])
  N2[i,t+1]<-(lambda2set[i]*N2[i,t])/(1+alphs[2,1]*N1[i,t]+alphs[2,2]*N2[i,t])
  }
}

plot(TimeVec,N1,type="l",xlab='Time (years)',ylab='Population Density',col='blue',
     lwd = 2,ylim = c(0,400))
</code>```

Here you can see in the equations the "alphs[..,..]" are supposed to represent which variable from each i matrices I want to use.

But how do I call them in regard to my list of matrices ?

答:
Like this?

```<code>years <- 10
Lambda1set<-c(5,5,3,3.2)
Lambda2set<-c(4,4,5,3)
Alphaset<-list(matrix(c(0.01, 0.007, 0.0045, 0.01),ncol = 2, byrow = TRUE),
               matrix(c(0.01, 0.003, 0.007, 0.01),ncol = 2, byrow = TRUE),
               matrix(c(0.01, 0.0055, 0.003, 0.01),ncol = 2, byrow = TRUE),
               matrix(c(0.005, 0.005, 0.0045, 0.004),ncol = 2, byrow = TRUE))
dat <- lapply(1:length(Alphaset), function(i) {
  list(Lambda1=Lambda1set[i], Lambda2=Lambda2set[i], alphs=Alphaset[[i]])
})

#Creating vectors
TimeVec<-seq(0,years,1)
N1<-matrix(0,4,years+1)
N2<-matrix(0,4,years+1)

#INITIALIZATION
N0 <- 40

require(dplyr)
require(ggplot2)
lapply(seq_along(dat), function(i) {
  dati <- dat[[i]]
  N1 <- array(N0, dim=c(years+1))
  N2 <- array(N0, dim=c(years+1))
  for (t in 1:years) {
    N1[t+1]<-(dati$Lambda1*N1[t])/(1+dati$alphs[1,1]*N1[t]+dati$alphs[1,2]*N2[t])
    N2[t+1]<-(dati$Lambda2*N2[t])/(1+dati$alphs[2,1]*N1[t]+dati$alphs[2,2]*N2[t])
  }
  return(data.frame(i=i, Time=TimeVec, N1=N1, N2=N2))
}) %>%
  bind_rows() %>%
  mutate(i=factor(i)) %>%
  gather("Variable", "Value", -Time, -i) %>%
  ggplot(aes(x=Time, y=Value, color=Variable)) +
    geom_line() +
    ylab("Population Density") +
    theme_bw() +
    facet_grid(i~.)
</code>```

Body:
Basically, it's in the title.
With more details though, I have four parameters set that need to be organised in matrices, that I organised in a list (Alphaset), each having 4 variables. But I need to call in specific variables into a loop where it will go through an equation and should give me a plot.

Me and my poor knowledge of R tried different combination that resulted in being inefficient, such as "Alphaset[2,1,1]" or "Alphaset[2(1,1)]"
(this is an exemple where I want to display the variable that's first row first column of the second matrix).

#Parameters set on types (lambda 1, lambda 2, alphas)

Lambda1set<-c(5,5,3,3.2)
Lambda2set<-c(4,4,5,3)
Alphaset<-list(matrix(c(0.01, 0.007, 0.0045, 0.01),ncol = 2, byrow = TRUE),
            matrix(c(0.01, 0.003, 0.007, 0.01),ncol = 2, byrow = TRUE),
            matrix(c(0.01, 0.0055, 0.003, 0.01),ncol = 2, byrow = TRUE),
            matrix(c(0.005, 0.005, 0.0045, 0.004),ncol = 2, byrow = TRUE))

#Creating vectors
TimeVec<-seq(0,years,1)
N1<-matrix(0,4,years+1)
N2<-matrix(0,4,years+1)

#INITIALIZATION
N0 <- 40
N1[1] <-N0
N2[1] <-N0

for (t in 1:years){
  for(i in 1:4){
  N1[i,t+1]<-(Lambda1set[i]*N1[i,t])/(1+alphs[1,1]*N1[i,t]+alphs[1,2]*N2[i,t])
  N2[i,t+1]<-(lambda2set[i]*N2[i,t])/(1+alphs[2,1]*N1[i,t]+alphs[2,2]*N2[i,t])
  }
}

plot(TimeVec,N1,type="l",xlab='Time (years)',ylab='Population Density',col='blue',
     lwd = 2,ylim = c(0,400))

Here you can see in the equations the "alphs[..,..]" are supposed to represent which variable from each i matrices I want to use.

But how do I call them in regard to my list of matrices ?

Body:
Like this?

years <- 10
Lambda1set<-c(5,5,3,3.2)
Lambda2set<-c(4,4,5,3)
Alphaset<-list(matrix(c(0.01, 0.007, 0.0045, 0.01),ncol = 2, byrow = TRUE),
               matrix(c(0.01, 0.003, 0.007, 0.01),ncol = 2, byrow = TRUE),
               matrix(c(0.01, 0.0055, 0.003, 0.01),ncol = 2, byrow = TRUE),
               matrix(c(0.005, 0.005, 0.0045, 0.004),ncol = 2, byrow = TRUE))
dat <- lapply(1:length(Alphaset), function(i) {
  list(Lambda1=Lambda1set[i], Lambda2=Lambda2set[i], alphs=Alphaset[[i]])
})

#Creating vectors
TimeVec<-seq(0,years,1)
N1<-matrix(0,4,years+1)
N2<-matrix(0,4,years+1)

#INITIALIZATION
N0 <- 40

require(dplyr)
require(ggplot2)
lapply(seq_along(dat), function(i) {
  dati <- dat[[i]]
  N1 <- array(N0, dim=c(years+1))
  N2 <- array(N0, dim=c(years+1))
  for (t in 1:years) {
    N1[t+1]<-(dati$Lambda1*N1[t])/(1+dati$alphs[1,1]*N1[t]+dati$alphs[1,2]*N2[t])
    N2[t+1]<-(dati$Lambda2*N2[t])/(1+dati$alphs[2,1]*N1[t]+dati$alphs[2,2]*N2[t])
  }
  return(data.frame(i=i, Time=TimeVec, N1=N1, N2=N2))
}) %>%
  bind_rows() %>%
  mutate(i=factor(i)) %>%
  gather("Variable", "Value", -Time, -i) %>%
  ggplot(aes(x=Time, y=Value, color=Variable)) +
    geom_line() +
    ylab("Population Density") +
    theme_bw() +
    facet_grid(i~.)


答:
You can use this PHP functions for doing operations with precisions number.</p>

```<code><?php

$a = '1.234';
$b = '5';

echo bcsub($a, $b);     // -3
echo bcsub($a, $b, 4);  // -3.7660

?>
</code>```

Title: PHP Gives Me Wrong Result Of Subtraction With Floating Number

Body:
You can use this PHP functions for doing operations with precisions number.

<?php

$a = '1.234';
$b = '5';

echo bcsub($a, $b);     // -3
echo bcsub($a, $b, 4);  // -3.7660

?>


问:
LLBGen 5.3 & MS SQL Server 2012: paging query but no OFFSET xxx FETCH in generated SQL
```<code>collection.GetMulti(filter, 0, sorter, relations, path, 1, 10);
</code>```

Generated SQL:

```<code>    SELECT
        ...
    FROM
        ((((
                        [NewsDB].[dbo].[Article]
                        INNER JOIN [NewsDB].[dbo].[OnlineArticle] ON [NewsDB].[dbo].[Article].[ArticleID] = [NewsDB].[dbo].[OnlineArticle].[OnlineArticleID]
                        )
                    INNER JOIN [NewsDB].[dbo].[CategoryOnlineArticle] ON [NewsDB].[dbo].[OnlineArticle].[OnlineArticleID] = [NewsDB].[dbo].[CategoryOnlineArticle].[OnlineArticleID]
                    )
                INNER JOIN [NewsDB].[dbo].[Category] ON [NewsDB].[dbo].[Category].[CategoryID] = [NewsDB].[dbo].[CategoryOnlineArticle].[CategoryID]
                )
            LEFT JOIN [NewsDB].[dbo].[OldOnlineArticle] ON [NewsDB].[dbo].[OnlineArticle].[OnlineArticleID] = [NewsDB].[dbo].[OldOnlineArticle].[OnlineArticleID]
        )
    WHERE
        (
            (
                (
                    [NewsDB].[dbo].[Article].[IsDeleted] = @p1
                    AND [NewsDB].[dbo].[Article].[IsArchive] = @p2
                    AND [NewsDB].[dbo].[Article].[NavigateType] = @p3
                    AND [NewsDB].[dbo].[Article].[Status] = @p4
                    AND [NewsDB].[dbo].[OnlineArticle].[IsOnlinePublished] = @p5
                    AND [NewsDB].[dbo].[OnlineArticle].[OnlinePublishDateUtc] <= @p6
                )
                AND [NewsDB].[dbo].[OnlineArticle].[SiteNewsPortalID] = @p7
                AND [NewsDB].[dbo].[Category].[IsDeleted] = @p8
                AND [NewsDB].[dbo].[Category].[IsEnable] = @p9
                AND [NewsDB].[dbo].[Category].[CategoryType] = @p10
                AND [NewsDB].[dbo].[Category].[CategoryID] = @p11
            )
        AND ( [NewsDB].[dbo].[OnlineArticle].[OnlineArticleID] IS NOT NULL ))
    ORDER BY
        [NewsDB].[dbo].[OnlineArticle].[RefreshDateUtc] DESC,
        [NewsDB].[dbo].[OnlineArticle].[OnlinePublishDateUtc] DESC
</code>```

I don't see OFFSET xxx FETCH xxx in generated SQL.

I also set compatible level to SqlServerCompatibilityLevel.SqlServer2005.

How to make OFFSET xxx FETCH available in generated SQL? Please help.

答:
OFFSET/FETCH is used when compatibility level is set to SqlServer2012. See more info at The SQL differences per compatibility mode.

Where are you looking the Generated SQL? Make sure you are viewing the final query to execute, as you may be seeing the query just before the paging in built.

And finally, there are some situations where is not possible to make the paging at server side level, so it's performed in client's side with a data reader. Quoting the documentation:

Paging in general happens on the server, however the LLBLGen Pro
  runtime framework switches to client-side paging at the datareader
  level if the paging query can't be generated without causing errors on
  the server. This happens if a DISTINCT violating construct is present
  in the SQL query, e.g. a type that's not to be used with DISTINCT or
  an order by on a field that's not in the projection. The
  datareader-level paging is efficient (it discards any rows before the
  page to read and stops reading data once the page to read is fully
  read) however can be slower than a server-side paging query.

To determine whether the framework switched to client-side paging /
  distinct filtering / row limiting, it will append to the SQL query
  output to the ORMQueryExecution tracer a string which signals this:
  "Requires client side paging", "Requires client side distinct
  filtering" and "Requires client side limiting", if the
  ORMQueryExecution tracer is set to level 4 (verbose)

Hope that helps. BTW, you can use the LLBLGen Pro Forums

Body:
collection.GetMulti(filter, 0, sorter, relations, path, 1, 10);

Generated SQL:

    SELECT
        ...
    FROM
        ((((
                        [NewsDB].[dbo].[Article]
                        INNER JOIN [NewsDB].[dbo].[OnlineArticle] ON [NewsDB].[dbo].[Article].[ArticleID] = [NewsDB].[dbo].[OnlineArticle].[OnlineArticleID]
                        )
                    INNER JOIN [NewsDB].[dbo].[CategoryOnlineArticle] ON [NewsDB].[dbo].[OnlineArticle].[OnlineArticleID] = [NewsDB].[dbo].[CategoryOnlineArticle].[OnlineArticleID]
                    )
                INNER JOIN [NewsDB].[dbo].[Category] ON [NewsDB].[dbo].[Category].[CategoryID] = [NewsDB].[dbo].[CategoryOnlineArticle].[CategoryID]
                )
            LEFT JOIN [NewsDB].[dbo].[OldOnlineArticle] ON [NewsDB].[dbo].[OnlineArticle].[OnlineArticleID] = [NewsDB].[dbo].[OldOnlineArticle].[OnlineArticleID]
        )
    WHERE
        (
            (
                (
                    [NewsDB].[dbo].[Article].[IsDeleted] = @p1
                    AND [NewsDB].[dbo].[Article].[IsArchive] = @p2
                    AND [NewsDB].[dbo].[Article].[NavigateType] = @p3
                    AND [NewsDB].[dbo].[Article].[Status] = @p4
                    AND [NewsDB].[dbo].[OnlineArticle].[IsOnlinePublished] = @p5
                    AND [NewsDB].[dbo].[OnlineArticle].[OnlinePublishDateUtc] <= @p6
                )
                AND [NewsDB].[dbo].[OnlineArticle].[SiteNewsPortalID] = @p7
                AND [NewsDB].[dbo].[Category].[IsDeleted] = @p8
                AND [NewsDB].[dbo].[Category].[IsEnable] = @p9
                AND [NewsDB].[dbo].[Category].[CategoryType] = @p10
                AND [NewsDB].[dbo].[Category].[CategoryID] = @p11
            )
        AND ( [NewsDB].[dbo].[OnlineArticle].[OnlineArticleID] IS NOT NULL ))
    ORDER BY
        [NewsDB].[dbo].[OnlineArticle].[RefreshDateUtc] DESC,
        [NewsDB].[dbo].[OnlineArticle].[OnlinePublishDateUtc] DESC

I don't see OFFSET xxx FETCH xxx in generated SQL.

I also set compatible level to SqlServerCompatibilityLevel.SqlServer2005.

How to make OFFSET xxx FETCH available in generated SQL? Please help.


问:
"class, interface, or enum expected" error when trying to create package
I'm trying to declare a package in a file as follows:

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

package rtg;

public class Generate
{
    // ...
}
</code>```

But I'm getting an error when I try to compile this:

```<code>Generate.java:3: class, interface, or enum expected package rtg;
</code>```

Why am I getting this error?

答: The pacakge declaration must be the first thing in a Java file (apart from comments). You can't put the imports above it.</p>

Body:
I'm trying to declare a package in a file as follows:

import java.util.*;

package rtg;

public class Generate
{
    // ...
}

But I'm getting an error when I try to compile this:

Generate.java:3: class, interface, or enum expected package rtg;

Why am I getting this error?


问:
How to detect if Windows 10 is in tablet mode with Delphi?
How would someone detect when a user enters tablet mode on a Windows 10 device with Delphi code?

Can someone show a code example for this?

I don't want to detect if the user has a tablet or not. I simply want to see whether they're in tablet mode or not. What would be the best way to do this?

答:
I deleted the previous variant (based on [SO]: How can I detect when Windows 10 enters tablet mode in a Windows Forms application? (@CheeseLover's answer) (pointed out by @Remko's comment)) because it's a totally different scenario (doesn't have anything to do with Win running on desktop).

I spent some time on [MS.DevBlogs]: Raymond - How can I detect whether my PC is in tablet mode? (pointed out in @RitaHan-MSFT's answer (+1)), and clearly, that's the way to go.

I don't know how to "translate" the code into Delphi, as many years passed since I wrote significant amounts of code in it (but I'm sure it's possible), so I did the next best thing: wrote a C++ .dll (containing a modified / improved version of Raymond's code) that is called from Delphi.

Note: VStudio is required to build the .dll, I used 2015 Community Edition, which is free and can be downloaded from [VStudio]: Visual Studio 2015 and other Products (you need an MS account though).

dll.cpp:

#include <wrl/client.h>
#include <windows.ui.viewmanagement.h>
#include <UIViewSettingsInterop.h>
#include <wrl/wrappers/corewrappers.h>

namespace WRL = Microsoft::WRL;
namespace VM = ABI::Windows::UI::ViewManagement;

class Backend {
public:
    static Backend &instance() {
        static Backend m_instance;
        return m_instance;
    }

    WRL::ComPtr<IUIViewSettingsInterop> interop() { return m_interop; }

private:
    Backend() {
        HRESULT res = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
        m_comInit = (res == S_OK) || (res == S_FALSE);
        if (m_comInit || (res == RPC_E_CHANGED_MODE)) {
            res = Windows::Foundation::GetActivationFactory(WRL::Wrappers::HStringReference(
                RuntimeClass_Windows_UI_ViewManagement_UIViewSettings).Get(), &m_interop);
        }
    }

    Backend(const Backend &other) = delete;
    Backend &operator =(const Backend &other) = delete;

    ~Backend() {
        if (m_interop) { m_interop.Reset(); }
        if (m_comInit) { CoUninitialize(); }
    }

    bool m_comInit = false;
    WRL::ComPtr<IUIViewSettingsInterop> m_interop = nullptr;
};

/*!
    Gets Tablet mode value.
    \param hwnd Window handle to get the mode for
    \returns:
         1 - Tablet mode ON
         0 - Tablet mode OFF
        -X - Error
*/
extern "C" __declspec(dllexport) int GetTabletMode(HWND hwnd) {
    WRL::ComPtr<IUIViewSettingsInterop> interop = Backend::instance().interop();
    if (!interop) { return -3; }

    WRL::ComPtr<VM::IUIViewSettings> viewSettings;
    HRESULT res = interop->GetForWindow(hwnd != NULL ? hwnd : GetConsoleWindow(), IID_PPV_ARGS(&viewSettings));
    if (!viewSettings) { return -2; }

    VM::UserInteractionMode currentMode;
    res = viewSettings->get_UserInteractionMode(&currentMode);

    int ret = -1;
    switch (currentMode) {
        case VM::UserInteractionMode_Mouse: ret = 0; break;
        case VM::UserInteractionMode_Touch: ret = 1; break;
        default: ret = -1;
    }

    viewSettings.Reset();
    return ret;
}
```

<p>Below is the <em>Delphi</em> relevant code (only the unit, as the rest can easily be manufactured, and there's no point placing it all here).</p>

<p><em>Unit0.pas</em>:</p>

<pre class="lang-pascal prettyprint-override"><code>unit Unit0;

interface

uses
    Forms, Dialogs, Controls, StdCtrls, Classes;

type
    TForm0 = class(TForm)
    CheckButton: TButton;
        procedure CheckButtonClick(Sender: TObject);
    private
        { Private declarations }
    public
        { Public declarations }
end;

var
    Form0: TForm0;

    function GetTabletMode(hwnd: THandle): Integer cdecl; external 'TabletUtils.dll';

implementation

{$R *.dfm}

procedure TForm0.CheckButtonClick(Sender: TObject);
var
    TabletModeStr: String;
begin
    case GetTabletMode(Self.Handle) of
        0 : TabletModeStr := 'OFF';
        1 : TabletModeStr := 'ON';
        else TabletModeStr := 'ERROR';
    end;
    MessageDlg('Tablet Mode: ' + TabletModeStr, mtInformation, [mbOK], 0);
end;

end.
</code>```

Output:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q056321591]> sopr.bat
*** Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ***

[prompt]> "c:\Install\x86\Microsoft\Visual Studio Community\2015\vc\vcvarsall.bat" x86

[prompt]> dir /b
App0.cfg
App0.dof
App0.dpr
App0.exe
App0.res
dll.cpp
other
Unit0.dcu
Unit0.ddp
Unit0.dfm
Unit0.pas

[prompt]> cl /nologo /DDLL /DNDEBUG /DUSRDLL /D_WINDOWS /MT dll.cpp  /link /NOLOGO /DLL /OUT:TabletUtils.dll ole32.lib runtimeobject.lib
dll.cpp
   Creating library TabletUtils.lib and object TabletUtils.exp

[prompt]> dir /b
App0.cfg
App0.dof
App0.dpr
App0.exe
App0.res
dll.cpp
dll.obj
other
TabletUtils.dll
TabletUtils.exp
TabletUtils.lib
Unit0.dcu
Unit0.ddp
Unit0.dfm
Unit0.pas

[prompt]> App0.exe

[prompt]>
```

In the screenshot below, I ran the application:

On my laptop (Win 10) with Desktop mode (right side)

On a Win 10 VM with Tablet mode (left side). Note that I had to copy:

App0.exe

TabletUtils.dll

Body:
I deleted the previous variant (based on [SO]: How can I detect when Windows 10 enters tablet mode in a Windows Forms application? (@CheeseLover's answer) (pointed out by @Remko's comment)) because it's a totally different scenario (doesn't have anything to do with Win running on desktop).

I spent some time on [MS.DevBlogs]: Raymond - How can I detect whether my PC is in tablet mode? (pointed out in @RitaHan-MSFT's answer (+1)), and clearly, that's the way to go.

I don't know how to "translate" the code into Delphi, as many years passed since I wrote significant amounts of code in it (but I'm sure it's possible), so I did the next best thing: wrote a C++ .dll (containing a modified / improved version of Raymond's code) that is called from Delphi.

Note: VStudio is required to build the .dll, I used 2015 Community Edition, which is free and can be downloaded from [VStudio]: Visual Studio 2015 and other Products (you need an MS account though).

dll.cpp:

#include <wrl/client.h>
#include <windows.ui.viewmanagement.h>
#include <UIViewSettingsInterop.h>
#include <wrl/wrappers/corewrappers.h>

namespace WRL = Microsoft::WRL;
namespace VM = ABI::Windows::UI::ViewManagement;

class Backend {
public:
    static Backend &instance() {
        static Backend m_instance;
        return m_instance;
    }

    WRL::ComPtr<IUIViewSettingsInterop> interop() { return m_interop; }

private:
    Backend() {
        HRESULT res = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
        m_comInit = (res == S_OK) || (res == S_FALSE);
        if (m_comInit || (res == RPC_E_CHANGED_MODE)) {
            res = Windows::Foundation::GetActivationFactory(WRL::Wrappers::HStringReference(
                RuntimeClass_Windows_UI_ViewManagement_UIViewSettings).Get(), &m_interop);
        }
    }

    Backend(const Backend &other) = delete;
    Backend &operator =(const Backend &other) = delete;

    ~Backend() {
        if (m_interop) { m_interop.Reset(); }
        if (m_comInit) { CoUninitialize(); }
    }

    bool m_comInit = false;
    WRL::ComPtr<IUIViewSettingsInterop> m_interop = nullptr;
};

/*!
    Gets Tablet mode value.
    \param hwnd Window handle to get the mode for
    \returns:
         1 - Tablet mode ON
         0 - Tablet mode OFF
        -X - Error
*/
extern "C" __declspec(dllexport) int GetTabletMode(HWND hwnd) {
    WRL::ComPtr<IUIViewSettingsInterop> interop = Backend::instance().interop();
    if (!interop) { return -3; }

    WRL::ComPtr<VM::IUIViewSettings> viewSettings;
    HRESULT res = interop->GetForWindow(hwnd != NULL ? hwnd : GetConsoleWindow(), IID_PPV_ARGS(&viewSettings));
    if (!viewSettings) { return -2; }

    VM::UserInteractionMode currentMode;
    res = viewSettings->get_UserInteractionMode(&currentMode);

    int ret = -1;
    switch (currentMode) {
        case VM::UserInteractionMode_Mouse: ret = 0; break;
        case VM::UserInteractionMode_Touch: ret = 1; break;
        default: ret = -1;
    }

    viewSettings.Reset();
    return ret;
}

Below is the Delphi relevant code (only the unit, as the rest can easily be manufactured, and there's no point placing it all here).

Unit0.pas:

unit Unit0;

interface

uses
    Forms, Dialogs, Controls, StdCtrls, Classes;

type
    TForm0 = class(TForm)
    CheckButton: TButton;
        procedure CheckButtonClick(Sender: TObject);
    private
        { Private declarations }
    public
        { Public declarations }
end;

var
    Form0: TForm0;

    function GetTabletMode(hwnd: THandle): Integer cdecl; external 'TabletUtils.dll';

implementation

{$R *.dfm}

procedure TForm0.CheckButtonClick(Sender: TObject);
var
    TabletModeStr: String;
begin
    case GetTabletMode(Self.Handle) of
        0 : TabletModeStr := 'OFF';
        1 : TabletModeStr := 'ON';
        else TabletModeStr := 'ERROR';
    end;
    MessageDlg('Tablet Mode: ' + TabletModeStr, mtInformation, [mbOK], 0);
end;

end.

Output:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q056321591]> sopr.bat
*** Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ***

[prompt]> "c:\Install\x86\Microsoft\Visual Studio Community\2015\vc\vcvarsall.bat" x86

[prompt]> dir /b
App0.cfg
App0.dof
App0.dpr
App0.exe
App0.res
dll.cpp
other
Unit0.dcu
Unit0.ddp
Unit0.dfm
Unit0.pas

[prompt]> cl /nologo /DDLL /DNDEBUG /DUSRDLL /D_WINDOWS /MT dll.cpp  /link /NOLOGO /DLL /OUT:TabletUtils.dll ole32.lib runtimeobject.lib
dll.cpp
   Creating library TabletUtils.lib and object TabletUtils.exp

[prompt]> dir /b
App0.cfg
App0.dof
App0.dpr
App0.exe
App0.res
dll.cpp
dll.obj
other
TabletUtils.dll
TabletUtils.exp
TabletUtils.lib
Unit0.dcu
Unit0.ddp
Unit0.dfm
Unit0.pas

[prompt]> App0.exe

[prompt]>

In the screenshot below, I ran the application:

On my laptop (Win 10) with Desktop mode (right side)

On a Win 10 VM with Tablet mode (left side). Note that I had to copy:

App0.exe

TabletUtils.dll


问:
How to have Applescript shut down confirmation dialog in frontmost
I have a simple applescript, compiled as application, that allows user to choose between restart, shut down, etc.

It's very simple and works fine, but the confirmation dialog sent by the OS "are you sure you want to shut down your computer now" with the timer is not the frontmost window, so user have to click inside this dialog to activate, and then click the button he wants.

If this confirmation dialog would be the frontmost window, a simple enter key would confirm the choice. Any idea about how to bring this confirmation dialog to top?

```<code>tell application "Finder"
set userChoice to my getChoixUser("list") -- choose from list

try
    if (userChoice contains "Veille") then -- sleep
        tell application "Finder" to sleep
    else if (userChoice contains "Eteindre") then -- shut down
        tell application "loginwindow" to «event aevtrsdn»
    else if (userChoice contains "Redémarrer") then -- restart
        tell application "loginwindow" to «event aevtrrst»
    else if (userChoice contains "économiseur") then -- screen saver
        tell application "System Events" to start current screen saver
    end if

on error errMsg
    beep
    tell application "Finder" to display dialog errMsg buttons {"OK"} default button 1 with title scriptName with icon 0
end try
</code>```

end tell

答:
Remove the enclosing Finder tell block and activate the window with GUI scripting

```<code>set userChoice to getChoixUser("list") -- choose from list

try
    if (userChoice contains "Veille") then -- sleep
        tell application "Finder" to sleep
    else if (userChoice contains "Eteindre") then -- shut down
        tell application "loginwindow" to «event aevtrsdn»
        focusLoginWindow()
    else if (userChoice contains "Redémarrer") then -- restart
        tell application "loginwindow" to «event aevtrrst»
        focusLoginWindow()
    else if (userChoice contains "économiseur") then -- screen saver
        tell application "System Events" to start current screen saver
    end if

on error errMsg
    beep
    tell application "Finder" to display dialog errMsg buttons {"OK"} default button 1 with title scriptName with icon 0
end try

on focusLoginWindow()
    tell application "System Events" to tell process "loginwindow"
        repeat until exists window 1
            delay 0.2
        end repeat
        set attribute "AXFocused" of window 1 to true
    end tell
end focusLoginWindow
</code>```

Body:
I have a simple applescript, compiled as application, that allows user to choose between restart, shut down, etc.

It's very simple and works fine, but the confirmation dialog sent by the OS "are you sure you want to shut down your computer now" with the timer is not the frontmost window, so user have to click inside this dialog to activate, and then click the button he wants.

If this confirmation dialog would be the frontmost window, a simple enter key would confirm the choice. Any idea about how to bring this confirmation dialog to top?

tell application "Finder"
set userChoice to my getChoixUser("list") -- choose from list

try
    if (userChoice contains "Veille") then -- sleep
        tell application "Finder" to sleep
    else if (userChoice contains "Eteindre") then -- shut down
        tell application "loginwindow" to «event aevtrsdn»
    else if (userChoice contains "Redémarrer") then -- restart
        tell application "loginwindow" to «event aevtrrst»
    else if (userChoice contains "économiseur") then -- screen saver
        tell application "System Events" to start current screen saver
    end if

on error errMsg
    beep
    tell application "Finder" to display dialog errMsg buttons {"OK"} default button 1 with title scriptName with icon 0
end try

end tell

Body:
Remove the enclosing Finder tell block and activate the window with GUI scripting

set userChoice to getChoixUser("list") -- choose from list

try
    if (userChoice contains "Veille") then -- sleep
        tell application "Finder" to sleep
    else if (userChoice contains "Eteindre") then -- shut down
        tell application "loginwindow" to «event aevtrsdn»
        focusLoginWindow()
    else if (userChoice contains "Redémarrer") then -- restart
        tell application "loginwindow" to «event aevtrrst»
        focusLoginWindow()
    else if (userChoice contains "économiseur") then -- screen saver
        tell application "System Events" to start current screen saver
    end if

on error errMsg
    beep
    tell application "Finder" to display dialog errMsg buttons {"OK"} default button 1 with title scriptName with icon 0
end try

on focusLoginWindow()
    tell application "System Events" to tell process "loginwindow"
        repeat until exists window 1
            delay 0.2
        end repeat
        set attribute "AXFocused" of window 1 to true
    end tell
end focusLoginWindow


问:
doctrine odm annotations or composer autoload.php not working?
I'm trying to use Doctrine MongoDB ODM 2.0 beta on a project with the Yii2 framework, with composer version 1.8.4 and PHP 7.2, but I keep getting the error Fatal error: Uncaught Error: Call to a member function add() on boolean where the code runs $loader->add('Documents', __DIR__);

bootstrap.php file (in DIR/bootstrap.php):

```<code><?php

use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\ODM\MongoDB\Configuration;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;

if ( ! file_exists($file = 'C:/path/to/vendor/autoload.php')) {
    throw new RuntimeException('Install dependencies to run this script.');
}

$loader = require_once $file;
$loader->add('Documents', __DIR__);

AnnotationRegistry::registerLoader([$loader, 'loadClass']);

$config = new Configuration();
$config->setProxyDir(__DIR__ . '/Proxies');
$config->setProxyNamespace('Proxies');
$config->setHydratorDir(__DIR__ . '/Hydrators');
$config->setHydratorNamespace('Hydrators');
$config->setDefaultDB('fsa');
$config->setMetadataDriverImpl(AnnotationDriver::create(__DIR__ . '/Documents'));

$dm = DocumentManager::create(null, $config);
</code>```

I already tried looking at How to properly Autoload Doctrine ODM annotations? and Laravel & Couchdb-ODM - The annotation "@Doctrine\ODM\CouchDB\Mapping\Annotations\Document" does not exist, or could not be auto-loaded and a host of other threads I can't quite recall for help, but I couldn't figure out a solution.

I also tried commenting out the lines below

```<code>if ( ! file_exists($file = 'C:/path/to/vendor/autoload.php')) {
    throw new RuntimeException('Install dependencies to run this script.');
}

$loader = require_once $file;
$loader->add('Documents', __DIR__);

AnnotationRegistry::registerLoader([$loader, 'loadClass']);
</code>```

and ran composer dump-autoload and on command line it returned Generated autoload files containing 544 classes, but then I got the problem

[Semantical Error] The annotation "@Doctrine\ODM\MongoDB\Mapping\Annotations\Document" in class Documents\Message does not exist, or could not be auto-loaded.

So the annotations are not auto-loading, and I have no idea how to fix that.
In the model I have:

```<code><?php

namespace Documents;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use \Doctrine\ODM\MongoDB\Mapping\Annotations\Document;

/** @ODM\Document */
class Message
{
    /** @ODM\Id */
    private $id;

    /** @ODM\Field(type="int") */
    private $sender_id;
...
</code>```

I also posted a thread on github at https://github.com/doctrine/mongodb-odm/issues/1976.  One commenter stated that "By default, the composer autoload file returns the autoloader in question, which seems to not be the case for you."  How can I fix that?  The only information I can find online is to put (inside composer.json) the lines:

```<code>    "autoload": {
        "psr-4": {
            "Class\\": "src/"
        }
    },
</code>```

but then what class should I be loading?

I'm very confused and being pretty new to all these tools (mongodb, yii2, etc.) doesn't help at all.  I'm not sure what other information would be helpful else I would post it.

Thanks in advance.

答: So turns out that the problem (as was mentioned in https://github.com/doctrine/mongodb-odm/issues/1976) was that autoload.php was required twice - once in bootstrap.php and once in web/index.php (of the framework).  After the require line in index.php was removed, everything worked fine.

Body:
I'm trying to use Doctrine MongoDB ODM 2.0 beta on a project with the Yii2 framework, with composer version 1.8.4 and PHP 7.2, but I keep getting the error Fatal error: Uncaught Error: Call to a member function add() on boolean where the code runs $loader->add('Documents', __DIR__);

bootstrap.php file (in DIR/bootstrap.php):

<?php

use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\ODM\MongoDB\Configuration;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;

if ( ! file_exists($file = 'C:/path/to/vendor/autoload.php')) {
    throw new RuntimeException('Install dependencies to run this script.');
}

$loader = require_once $file;
$loader->add('Documents', __DIR__);

AnnotationRegistry::registerLoader([$loader, 'loadClass']);

$config = new Configuration();
$config->setProxyDir(__DIR__ . '/Proxies');
$config->setProxyNamespace('Proxies');
$config->setHydratorDir(__DIR__ . '/Hydrators');
$config->setHydratorNamespace('Hydrators');
$config->setDefaultDB('fsa');
$config->setMetadataDriverImpl(AnnotationDriver::create(__DIR__ . '/Documents'));

$dm = DocumentManager::create(null, $config);

I already tried looking at How to properly Autoload Doctrine ODM annotations? and Laravel & Couchdb-ODM - The annotation "@Doctrine\ODM\CouchDB\Mapping\Annotations\Document" does not exist, or could not be auto-loaded and a host of other threads I can't quite recall for help, but I couldn't figure out a solution.

I also tried commenting out the lines below

if ( ! file_exists($file = 'C:/path/to/vendor/autoload.php')) {
    throw new RuntimeException('Install dependencies to run this script.');
}

$loader = require_once $file;
$loader->add('Documents', __DIR__);

AnnotationRegistry::registerLoader([$loader, 'loadClass']);

and ran composer dump-autoload and on command line it returned Generated autoload files containing 544 classes, but then I got the problem

[Semantical Error] The annotation "@Doctrine\ODM\MongoDB\Mapping\Annotations\Document" in class Documents\Message does not exist, or could not be auto-loaded.

So the annotations are not auto-loading, and I have no idea how to fix that.
In the model I have:

<?php

namespace Documents;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use \Doctrine\ODM\MongoDB\Mapping\Annotations\Document;

/** @ODM\Document */
class Message
{
    /** @ODM\Id */
    private $id;

    /** @ODM\Field(type="int") */
    private $sender_id;
...

I also posted a thread on github at https://github.com/doctrine/mongodb-odm/issues/1976.  One commenter stated that "By default, the composer autoload file returns the autoloader in question, which seems to not be the case for you."  How can I fix that?  The only information I can find online is to put (inside composer.json) the lines:

    "autoload": {
        "psr-4": {
            "Class\\": "src/"
        }
    },

but then what class should I be loading?

I'm very confused and being pretty new to all these tools (mongodb, yii2, etc.) doesn't help at all.  I'm not sure what other information would be helpful else I would post it.

Thanks in advance.


问:
User Approval by email showing outputs but not updating records in database
I am currently working on a project where I need to get a user to sign up and then an email is sent to the website administrator's email with an approval link (containing the php page below, user email and sha512). When the approval link is clicked, it's meant to Update the table with the corresponding email and change isApproved to 1, but it does nothing other than printing the echos.

I tried changing the SQL commands, adding the ` around the names, looking it up on w3schools, stackoverflow and other forums and found nothing.

```<code><?php
    $hash = $_GET['h'];
    $email = $_GET['e'];

    if($hash == hash('sha512', 'ACCEPT')){
    $host = "redacted";
    $dbUsername = "redacted";
    $dbPassword = "redacted";
    $dbname = "redacted";
    //create connection
    $conn = mysqli_connect($host, $dbUsername, $dbPassword, $dbname);
    if (mysqli_connect_error())
    {
        die('Connect Error('. mysqli_connect_errno().')'.mysqli_connect_error());
    }
    else
    {
        $sql = "UPDATE `User` SET `isApproved`='1' WHERE `User`.`email`=$email";
        echo("approved");
    }
?>
</code>```

All I see when opening the website is "approved", which is what i expected, but the records in the database remain unchanged.

答:
I think you didn't run execute command.</p>

```<code>    $conn = mysqli_connect($host, $dbUsername, $dbPassword, $dbname);
    ....
    $sql = "UPDATE `User` SET `isApproved`='1' WHERE `User`.`email`=$email";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_execute($stmt);
</code>```

Body:
I am currently working on a project where I need to get a user to sign up and then an email is sent to the website administrator's email with an approval link (containing the php page below, user email and sha512). When the approval link is clicked, it's meant to Update the table with the corresponding email and change isApproved to 1, but it does nothing other than printing the echos.

I tried changing the SQL commands, adding the ` around the names, looking it up on w3schools, stackoverflow and other forums and found nothing.

<?php
    $hash = $_GET['h'];
    $email = $_GET['e'];

    if($hash == hash('sha512', 'ACCEPT')){
    $host = "redacted";
    $dbUsername = "redacted";
    $dbPassword = "redacted";
    $dbname = "redacted";
    //create connection
    $conn = mysqli_connect($host, $dbUsername, $dbPassword, $dbname);
    if (mysqli_connect_error())
    {
        die('Connect Error('. mysqli_connect_errno().')'.mysqli_connect_error());
    }
    else
    {
        $sql = "UPDATE `User` SET `isApproved`='1' WHERE `User`.`email`=$email";
        echo("approved");
    }
?>

All I see when opening the website is "approved", which is what i expected, but the records in the database remain unchanged.

Body:
I think you didn't run execute command.

    $conn = mysqli_connect($host, $dbUsername, $dbPassword, $dbname);
    ....
    $sql = "UPDATE `User` SET `isApproved`='1' WHERE `User`.`email`=$email";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_execute($stmt);


问:
increment date by one month
Let's say I have a date in the following format: 2010-12-11 (year-mon-day)

With PHP, I want to increment the date by one month, and I want the year to be automatically incremented, if necessary (i.e. incrementing from December 2012 to January 2013).

Regards.

答:
All presented solutions are not working properly.

strtotime() and DateTime::add or DateTime::modify give sometime invalid results.

Examples:

- 31.08.2019 + 1 month gives 01.10.2019 instead 30.09.2019

- 29.02.2020 + 1 year gives 01.03.2021 instead 28.02.2021

(tested on PHP 5.5, PHP 7.3)

Below is my function based on idea posted by Angelo that solves the problem:

```<code>// $time - unix time or date in any format accepted by strtotime() e.g. 2020-02-29
// $days, $months, $years - values to add
// returns new date in format 2021-02-28
function addTime($time, $days, $months, $years)
{
    // Convert unix time to date format
    if (is_numeric($time))
    $time = date('Y-m-d', $time);

    try
    {
        $date_time = new DateTime($time);
    }
    catch (Exception $e)
    {
        echo $e->getMessage();
        exit;
    }

    if ($days)
    $date_time->add(new DateInterval('P'.$days.'D'));

    // Preserve day number
    if ($months or $years)
    $old_day = $date_time->format('d');

    if ($months)
    $date_time->add(new DateInterval('P'.$months.'M'));

    if ($years)
    $date_time->add(new DateInterval('P'.$years.'Y'));

    // Patch for adding months or years
    if ($months or $years)
    {
        $new_day = $date_time->format("d");

        // The day is changed - set the last day of the previous month
        if ($old_day != $new_day)
        $date_time->sub(new DateInterval('P'.$new_day.'D'));
    }
    // You can chage returned format here
    return $date_time->format('Y-m-d');
}
</code>```

Usage examples:

```<code>echo addTime('2020-02-29', 0, 0, 1); // add 1 year (result: 2021-02-28)
echo addTime('2019-08-31', 0, 1, 0); // add 1 month (result: 2019-09-30)
echo addTime('2019-03-15', 12, 2, 1); // add 12 days, 2 months, 1 year (result: 2019-09-30)
</code>```

Title: increment date by one month

Body:
All presented solutions are not working properly.

strtotime() and DateTime::add or DateTime::modify give sometime invalid results.

Examples:

- 31.08.2019 + 1 month gives 01.10.2019 instead 30.09.2019

- 29.02.2020 + 1 year gives 01.03.2021 instead 28.02.2021

(tested on PHP 5.5, PHP 7.3)

Below is my function based on idea posted by Angelo that solves the problem:

// $time - unix time or date in any format accepted by strtotime() e.g. 2020-02-29
// $days, $months, $years - values to add
// returns new date in format 2021-02-28
function addTime($time, $days, $months, $years)
{
    // Convert unix time to date format
    if (is_numeric($time))
    $time = date('Y-m-d', $time);

    try
    {
        $date_time = new DateTime($time);
    }
    catch (Exception $e)
    {
        echo $e->getMessage();
        exit;
    }

    if ($days)
    $date_time->add(new DateInterval('P'.$days.'D'));

    // Preserve day number
    if ($months or $years)
    $old_day = $date_time->format('d');

    if ($months)
    $date_time->add(new DateInterval('P'.$months.'M'));

    if ($years)
    $date_time->add(new DateInterval('P'.$years.'Y'));

    // Patch for adding months or years
    if ($months or $years)
    {
        $new_day = $date_time->format("d");

        // The day is changed - set the last day of the previous month
        if ($old_day != $new_day)
        $date_time->sub(new DateInterval('P'.$new_day.'D'));
    }
    // You can chage returned format here
    return $date_time->format('Y-m-d');
}

Usage examples:

echo addTime('2020-02-29', 0, 0, 1); // add 1 year (result: 2021-02-28)
echo addTime('2019-08-31', 0, 1, 0); // add 1 month (result: 2019-09-30)
echo addTime('2019-03-15', 12, 2, 1); // add 12 days, 2 months, 1 year (result: 2019-09-30)