问:
Numeral or Categorical split?
I am building a decision tree classifier and I found this method for calculating information gain.
 This may be a silly question, but I am wondering if the split in this method is for numeral or
 categorical attributes? I'm confused because I thought a threshold (median) was used for numeral
 splits, but this method uses String values.

Any help is appreciated.

Here is the code:

```<code>    public static double getInfoGain(int f, ArrayList<String[]> dataSubset) {
            double entropyBefore = getEntropy(dataSubset); //Entropy before split
            if(entropyBefore != 0){ // Calculate information gain if entropy is not 0
                String threshold = thresholdMap.get(f); // Get threshold value of the feature
                ArrayList<String[]> leftData = new ArrayList<String[]>();
                ArrayList<String[]> rightData = new ArrayList<String[]>();
                for(String[] d : dataSubset) {
                    if(d[f].equals(threshold)) {
                        leftData.add(d); // If feature value of data == threshold, add it to leftData
                    } else {
                        rightData.add(d); // If feature value of data != threshold, add it to leftData
                    }
                }
                if(leftData.size() > 0 && rightData.size() > 0) {
                    double leftProb = (double)leftData.size()/dataSubset.size();
                    double rightProb = (double)rightData.size()/dataSubset.size();
                    double entropyLeft = getEntropy(leftData); //Entropy after split - left
                    double entropyRight = getEntropy(rightData); //Entropy after split - right
                    double gain = entropyBefore - (leftProb * entropyLeft) - (rightProb * entropyRight);
                    return gain;
                } else { // If entropy = 0 on either subsets of data, return 0
                    return 0;
                }
            } else { // If entropy = 0 before split, return 1
                return -1;
            }
        }
</code>```

答:
Although the code you pointed at uses the terminology of thresholds, if you look at the comments, it is using them in a categorical or binary way.

```<code>if(d[f].equals(threshold)) {
   leftData.add(d); // If feature value of data == threshold, add it to leftData
} else {
   rightData.add(d); // If feature value of data != threshold, add it to leftData
}
</code>```

I would strongly recommend looking at the algorithms from a textbook or Wikipedia as a reference instead of going directly to code. Or, if you find yourself needing code examples, I would look for repositories on Github that are of higher quality (three dimensions).

You want to study code with a clear license. In many places, not having a license is equivalent to being proprietary, despite Github's implied Open-Source nature, that's just not legally accurate.

You want to study code that people use. There are many more decision tree algorithm implementations on github that have more than zero stars and issues.

Failing that, you want to study code that has tests (an indication and a chance to test if it actually works for yourself).

Ideally, you want many indications of trust. If I go to github, search for decision tree, check Java, sort by most stars, I'd look at one of sanity/quickml or saebyn/java-decision-tree myself.

Title: Numeral or Categorical split?

Body:
I am building a decision tree classifier and I found this method for calculating information gain.
 This may be a silly question, but I am wondering if the split in this method is for numeral or
 categorical attributes? I'm confused because I thought a threshold (median) was used for numeral
 splits, but this method uses String values.

Any help is appreciated.

Here is the code:

    public static double getInfoGain(int f, ArrayList<String[]> dataSubset) {
            double entropyBefore = getEntropy(dataSubset); //Entropy before split
            if(entropyBefore != 0){ // Calculate information gain if entropy is not 0
                String threshold = thresholdMap.get(f); // Get threshold value of the feature
                ArrayList<String[]> leftData = new ArrayList<String[]>();
                ArrayList<String[]> rightData = new ArrayList<String[]>();
                for(String[] d : dataSubset) {
                    if(d[f].equals(threshold)) {
                        leftData.add(d); // If feature value of data == threshold, add it to leftData
                    } else {
                        rightData.add(d); // If feature value of data != threshold, add it to leftData
                    }
                }
                if(leftData.size() > 0 && rightData.size() > 0) {
                    double leftProb = (double)leftData.size()/dataSubset.size();
                    double rightProb = (double)rightData.size()/dataSubset.size();
                    double entropyLeft = getEntropy(leftData); //Entropy after split - left
                    double entropyRight = getEntropy(rightData); //Entropy after split - right
                    double gain = entropyBefore - (leftProb * entropyLeft) - (rightProb * entropyRight);
                    return gain;
                } else { // If entropy = 0 on either subsets of data, return 0
                    return 0;
                }
            } else { // If entropy = 0 before split, return 1
                return -1;
            }
        }

Body:
Although the code you pointed at uses the terminology of thresholds, if you look at the comments, it is using them in a categorical or binary way.

if(d[f].equals(threshold)) {
   leftData.add(d); // If feature value of data == threshold, add it to leftData
} else {
   rightData.add(d); // If feature value of data != threshold, add it to leftData
}

I would strongly recommend looking at the algorithms from a textbook or Wikipedia as a reference instead of going directly to code. Or, if you find yourself needing code examples, I would look for repositories on Github that are of higher quality (three dimensions).

You want to study code with a clear license. In many places, not having a license is equivalent to being proprietary, despite Github's implied Open-Source nature, that's just not legally accurate.

You want to study code that people use. There are many more decision tree algorithm implementations on github that have more than zero stars and issues.

Failing that, you want to study code that has tests (an indication and a chance to test if it actually works for yourself).

Ideally, you want many indications of trust. If I go to github, search for decision tree, check Java, sort by most stars, I'd look at one of sanity/quickml or saebyn/java-decision-tree myself.


来源: stackexchange

问:
Error in mediactrl_am.cpp while building wxwidgets 3.0.3 with llvm 5.0.0 target x86_64-w64-windows-gnu
I'v recently compiled wxWidgets 3.0.3 with mingw-w64 7.2.0, but due some problems with exception handling now I'm trying recompile them with llvm 5.0.0 (using x86_64-w64-windows-gnu target, standard library from mingw-w64 7.2.0, 64 bit, seh, posix threads) which has not those problems.

I have not find instructions how to build current stable version (3.0.3) of wxWidgets with Clang on Windows. So I'm trying a command like

```<code>mingw32-make.exe -f makefile.gcc MONOLITHIC=1 SHARED=1 BUILD=debug CXXFLAGS=" -fexceptions -fasynchronous-unwind-tables -fnon-call-exceptions -std=gnu++11 -pthread " LDFLAGS=" -fexceptions -fasynchronous-unwind-tables -fnon_call_exceptions -pthread "  CC="clang -target x86_64-w64-windows-gnu" CXX="clang++ -target x86_64-w64-windows-gnu" COMPILER_PREFIX="clang"
</code>```

in ..\build\msw subdirectory to build one of the possible configurations.

(With mingw-w64 I used also LDFLAGS=" -Wl,--allow-multiple-definition ", possible here will be problems with multiple symbols too. I've also pathched source code as I had problems with wxPrintf)

The first error I have:

```<code>../../src/msw/mediactrl_am.cpp:2234:10: error: case value evaluates to
      4294966687, which cannot be narrowed to type 'DISPID' (aka 'long')
      [-Wc++11-narrowing]
    case 0xfffffd9f: // readystatechange in IActiveMovie2 and IMediaPlayer
         ^
1 error generated.
</code>```

My account on wxWidgets forum not activated yet, so I ask here.

May be somebody knows correct way how to repair this issue?

答:
The obvious fix for this particular problem seems to be to replace this value with -609.

However I need to warn you that, to the best of my knowledge, nobody has compiled wxMSW using clang so far (even though clang can be used for compiling wxGTK and wxOSX, of course), so you may well run into other, less trivial, problems later. I'd also recommend trying to compile the latest git master instead of 3.0.3 as any non-trivial changes that might be required for clang build are unlikely to be done in the stable 3.0 branch.

ContentLicense: CC BY-SA 3.0

Body:
I'v recently compiled wxWidgets 3.0.3 with mingw-w64 7.2.0, but due some problems with exception handling now I'm trying recompile them with llvm 5.0.0 (using x86_64-w64-windows-gnu target, standard library from mingw-w64 7.2.0, 64 bit, seh, posix threads) which has not those problems.

I have not find instructions how to build current stable version (3.0.3) of wxWidgets with Clang on Windows. So I'm trying a command like

mingw32-make.exe -f makefile.gcc MONOLITHIC=1 SHARED=1 BUILD=debug CXXFLAGS=" -fexceptions -fasynchronous-unwind-tables -fnon-call-exceptions -std=gnu++11 -pthread " LDFLAGS=" -fexceptions -fasynchronous-unwind-tables -fnon_call_exceptions -pthread "  CC="clang -target x86_64-w64-windows-gnu" CXX="clang++ -target x86_64-w64-windows-gnu" COMPILER_PREFIX="clang"

in ..\build\msw subdirectory to build one of the possible configurations.

(With mingw-w64 I used also LDFLAGS=" -Wl,--allow-multiple-definition ", possible here will be problems with multiple symbols too. I've also pathched source code as I had problems with wxPrintf)

The first error I have:

../../src/msw/mediactrl_am.cpp:2234:10: error: case value evaluates to
      4294966687, which cannot be narrowed to type 'DISPID' (aka 'long')
      [-Wc++11-narrowing]
    case 0xfffffd9f: // readystatechange in IActiveMovie2 and IMediaPlayer
         ^
1 error generated.

My account on wxWidgets forum not activated yet, so I ask here.

May be somebody knows correct way how to repair this issue?


问:
Lag in updating UI with databinding due to calling an async method?
In a Xamarin.Forms app I'm binding a boolean Upvoted property to an Image's Source property (through a converter), to switch between two icons, indicating whether the user has upvoted for a picture or not, I'm sending the Upvoted value along with the UserId and ImageId to  the server, then I update the icon, that causes a little lag for the icon to change

the first (slow) version of my method:

```<code>private async void OnVoting(ImageVotingModel image)
     {
          if (await SendVote(image)) //is responsible for updating database, it returns true only when the voting is updated successfully
             Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;
     }
</code>```

and then I changed to this:

```<code> private async void OnVoting(ImageVotingModel image)
        {
            if (IsBusy)// it's true when there is a work being done on server
                return;
            Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted; //with data-binding, once the Upvoted change the icon should be updated
            if (!await SendVote(image))
                Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;

        }
</code>```

the line:

```<code>Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;
</code>```

is supposed to update the UI immediately through the databinding:

```<code> <Image Source="{Binding UpVoted, Converter={StaticResource boolToImage}}"/>
</code>```

so what I was expecting is that the image will be updated immediately (like when I commented out the code that calls SendVote ::

```<code>private async void OnVoting(ImageVotingModel image)
        {
            if (IsBusy)// it's true when there is a work being done on server
                return;
            Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted; //with data-binding, once the Upvoted change the icon is updated
           // if (!await SendVote(image))
             //   Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;

        }
</code>```

but the problem still there, the UI lags like it's waiting the server to finish updating its data.

答:
The important piece of information needed here is what SendVote does.  It may or may not block the caller's thread, regardless of whether you call it using await.

I'm not certain, but your confusion may come from thinking that await by itself causes the SendVote method to run on a separate thread.  Rather, the await keyword only affects how the remainder of the method is scheduled upon completion of the specified Task (Task<bool> in your case).

Body:
In a Xamarin.Forms app I'm binding a boolean Upvoted property to an Image's Source property (through a converter), to switch between two icons, indicating whether the user has upvoted for a picture or not, I'm sending the Upvoted value along with the UserId and ImageId to  the server, then I update the icon, that causes a little lag for the icon to change

the first (slow) version of my method:

private async void OnVoting(ImageVotingModel image)
     {
          if (await SendVote(image)) //is responsible for updating database, it returns true only when the voting is updated successfully
             Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;
     }

and then I changed to this:

 private async void OnVoting(ImageVotingModel image)
        {
            if (IsBusy)// it's true when there is a work being done on server
                return;
            Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted; //with data-binding, once the Upvoted change the icon should be updated
            if (!await SendVote(image))
                Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;

        }

the line:

Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;

is supposed to update the UI immediately through the databinding:

 <Image Source="{Binding UpVoted, Converter={StaticResource boolToImage}}"/>

so what I was expecting is that the image will be updated immediately (like when I commented out the code that calls SendVote ::

private async void OnVoting(ImageVotingModel image)
        {
            if (IsBusy)// it's true when there is a work being done on server
                return;
            Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted; //with data-binding, once the Upvoted change the icon is updated
           // if (!await SendVote(image))
             //   Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;

        }

but the problem still there, the UI lags like it's waiting the server to finish updating its data.


问:
What type of NoSQL database is best suited to store hierarchical data?
What type of NoSQL database is best suited to store hierarchical data?

Say for example I want to store posts of a forum with a tree structure:

```<code>original post
 + re: original post
 + re: original post
   + re2: original post
     + re3: original post
   + re2: original post
</code>```

答:
What you possibly need is a document-oriented database like MongoDB or CouchDB.

See examples of different techniques which allow you to store hierarchical data in MongoDB:
http://www.mongodb.org/display/DOCS/Trees+in+MongoDB

Body:
What type of NoSQL database is best suited to store hierarchical data?

Say for example I want to store posts of a forum with a tree structure:

original post
 + re: original post
 + re: original post
   + re2: original post
     + re3: original post
   + re2: original post

ContentLicense: CC BY-SA 2.5


问:
BST using modules - OCaml
I am trying to create module/interface (i dont exactly know how its called, i am new to the language) for basic operations on BST in OCaml. My goal is to have an implementation that lets me doing something like this:

```<code>T.create();;
T.push(2);;
T.push(3);;
T.push(5);;
</code>```

in order to get a bst tree consisting of 2,3,5.

But at the moment to achieve this i have to write something like this:

```<code> let teeBst = T.push(2)(T.push(3)(T.push(5)(T.create())));;
</code>```

So when I am checking/using my code I have to do it like this:

```<code>    let tee2 = T.push(2)(T.push(3)(T.push(5)(T.create())));;
    T.postorder(tee2);;
</code>```

The output is fine:

```<code> # val tee2 : T.bt = <abstr>
 # - : int list = [2; 3; 5]
</code>```

But, as I said before, I would like to achieve this doing as below:

```<code>T.push(2);;
T.push(3);;
T.push(5);;
T.postorder();;
</code>```

(I realise this requires some changes to my postorder function but the one I am currently using is a temporary one so I can check the tree I have atm )

Below is my implementation. If you see the solution, please let me know ;)

```<code>   module type Tree =
    sig
        type bt
        val create: unit -> bt
        val push: int -> bt -> bt
        val find: int -> bt -> bool
        val preorder: bt -> int list
        val postorder: bt -> int list
        val inorder: bt -> int list
    end;;

module T : Tree =
    struct
        type bt = E | B of bt * int * bt
        let create () = E
        let rec push x = function
            | E -> B(E, x, E)
            | B (l, y, r) when x<y -> B(push x l, y, r)
            | B (l, y, r) when x>y -> B(l, y, push x r)
            | xs -> xs;;

        let rec find x = function
            | E -> false
            | B(l, y,_) when x< y -> find x l
            | B(_,y,r) when x>y -> find x r
            | _ -> true;;

        let rec preorder = function
            | B(l,v,r) -> v::(preorder r) @ (preorder l)
            | E -> [];;

        let rec inorder = function
            | B(l,v,r) ->(inorder r) @ v::(inorder l)
            | E -> []

        let rec postorder = function
            | B(l,v,r) -> (postorder r) @ (postorder l) @ [v]
            | E -> []
    end;;
</code>```

答:
It seems like you want modules to be classes, but I'd advise you to consider more idiomatic solutions. Have you considered using the pipe operator?

```<code>T.create()
|> T.push(2)
|> T.push(3)
|> T.push(5)
|> T.postorder;;
</code>```

Or with local open (which makes more sense if you have a module with a longer name than just T of course) you can even do

```<code>T.(
  create()
  |> push(2)
  |> push(3)
  |> push(5)
  |> postorder
);
</code>```

What you're asking for would require introducing global mutable state, which isn't just "some changes" but an entirely different paradigm. And one that is generally frowned upon because it makes your code unpredictable and hard to debug since it relies on state that might change at any moment from anywhere.

Another possibility is to actually use classes, since OCaml has those too. Then you'd still have mutable state, but it would at least be contained.

Title: BST using modules - OCaml

Body:
I am trying to create module/interface (i dont exactly know how its called, i am new to the language) for basic operations on BST in OCaml. My goal is to have an implementation that lets me doing something like this:

T.create();;
T.push(2);;
T.push(3);;
T.push(5);;

in order to get a bst tree consisting of 2,3,5.

But at the moment to achieve this i have to write something like this:

 let teeBst = T.push(2)(T.push(3)(T.push(5)(T.create())));;

So when I am checking/using my code I have to do it like this:

    let tee2 = T.push(2)(T.push(3)(T.push(5)(T.create())));;
    T.postorder(tee2);;

The output is fine:

 # val tee2 : T.bt = <abstr>
 # - : int list = [2; 3; 5]

But, as I said before, I would like to achieve this doing as below:

T.push(2);;
T.push(3);;
T.push(5);;
T.postorder();;

(I realise this requires some changes to my postorder function but the one I am currently using is a temporary one so I can check the tree I have atm )

Below is my implementation. If you see the solution, please let me know ;)

   module type Tree =
    sig
        type bt
        val create: unit -> bt
        val push: int -> bt -> bt
        val find: int -> bt -> bool
        val preorder: bt -> int list
        val postorder: bt -> int list
        val inorder: bt -> int list
    end;;

module T : Tree =
    struct
        type bt = E | B of bt * int * bt
        let create () = E
        let rec push x = function
            | E -> B(E, x, E)
            | B (l, y, r) when x<y -> B(push x l, y, r)
            | B (l, y, r) when x>y -> B(l, y, push x r)
            | xs -> xs;;

        let rec find x = function
            | E -> false
            | B(l, y,_) when x< y -> find x l
            | B(_,y,r) when x>y -> find x r
            | _ -> true;;

        let rec preorder = function
            | B(l,v,r) -> v::(preorder r) @ (preorder l)
            | E -> [];;

        let rec inorder = function
            | B(l,v,r) ->(inorder r) @ v::(inorder l)
            | E -> []

        let rec postorder = function
            | B(l,v,r) -> (postorder r) @ (postorder l) @ [v]
            | E -> []
    end;;

Body:
It seems like you want modules to be classes, but I'd advise you to consider more idiomatic solutions. Have you considered using the pipe operator?

T.create()
|> T.push(2)
|> T.push(3)
|> T.push(5)
|> T.postorder;;

Or with local open (which makes more sense if you have a module with a longer name than just T of course) you can even do

T.(
  create()
  |> push(2)
  |> push(3)
  |> push(5)
  |> postorder
);

What you're asking for would require introducing global mutable state, which isn't just "some changes" but an entirely different paradigm. And one that is generally frowned upon because it makes your code unpredictable and hard to debug since it relies on state that might change at any moment from anywhere.

Another possibility is to actually use classes, since OCaml has those too. Then you'd still have mutable state, but it would at least be contained.


答:
I found out 2 ways of doing this:

A. Using 2 queries to the database

 - update the Old Exp Date with the Expired date value from table

 - update the Expired date with the new value from the API

B. Using a single query

- you can try to set both fields at once but you should test it

- it is like SET Old Exp Date =  Expired date, Expired date = API_VALUE

Some implementations don't have the same UPDATE order:

sql-update-order-of-evaluation

You should test it to see how it works on your system. If it works then you should decide if there is any risk of portability issues.

Kind Regards,

Lin

Title: How to update new value to current field and transfer current value to old field?

Body:
I have a MySQL table that updates from an API daily, but now I want to track a specific field that has been updated from the API. I want to update the row with the current field(value) change and keep the old field(value) in another field.
Could somebody please point me in the right direction and what would be the best practice for this?

Table (original)

---------------------------------
|ID | Input Date | Expired Date |
---------------------------------
| 2 | 2017-05-17 | 2017-12-19   |
---------------------------------
| 3 | 2017-07-09 | 2018-05-19   |
---------------------------------

Table when updated (current)

---------------------------------
|ID | Input Date | Expired Date |
---------------------------------
| 2 | 2017-05-17 | 2018-05-28   |  <----- ID 2: Expired Date updated
---------------------------------
| 3 | 2017-07-09 | 2018-05-19   |
---------------------------------

Table updated and keeps old field value

------------------------------------------------
|ID | Input Date | Expired Date | Old Exp Date |
------------------------------------------------
| 2 | 2017-05-17 | 2018-05-28   | 2017-12-19   |
------------------------------------------------
| 3 | 2017-07-09 | 2018-05-19   |              |
------------------------------------------------

I hope this made sense a little, please help..Thank you so much:)


问:
elisp implementation of the "uniq -c" Unix command to count unique lines
If there is a data in region:

```
flower
park
flower
stone
flower
stone
stone
flower
```

M-x some-command should give me in different buffer:

```
4 flower
2 stone
1 park
```

This data can then be sorted by frequency or item.

答:
I suppose a common method would be to just hash the strings and then print the contents. This approach can be easily accomplished in emacs.

```<code>;; See the emacs manual for creating a hash table test
;; https://www.gnu.org/software/emacs/manual/html_node/elisp/Defining-Hash.html
(defun case-fold-string= (a b)
  (eq t (compare-strings a nil nil b nil nil t)))
(defun case-fold-string-hash (a)
  (sxhash (upcase a)))

(define-hash-table-test 'case-fold
  'case-fold-string= 'case-fold-string-hash)

(defun uniq (beg end)
  "Print counts of strings in region."
  (interactive "r")
  (let ((h (make-hash-table :test 'case-fold))
        (lst (split-string (buffer-substring-no-properties beg end) "\n"
                           'omit-nulls " "))
        (output-func (if current-prefix-arg 'insert 'princ)))
    (dolist (str lst)
      (puthash str (1+ (gethash str h 0)) h))
    (maphash (lambda (key val)
               (apply output-func (list (format "%d: %s\n" val key))))
             h)))
</code>```

Output when selecting that text

```<code>4: flower
1: park
3: stone
</code>```

Body:
If there is a data in region:

flower
park
flower
stone
flower
stone
stone
flower

M-x some-command should give me in different buffer:

4 flower
2 stone
1 park

This data can then be sorted by frequency or item.

Body:
I suppose a common method would be to just hash the strings and then print the contents. This approach can be easily accomplished in emacs.

;; See the emacs manual for creating a hash table test
;; https://www.gnu.org/software/emacs/manual/html_node/elisp/Defining-Hash.html
(defun case-fold-string= (a b)
  (eq t (compare-strings a nil nil b nil nil t)))
(defun case-fold-string-hash (a)
  (sxhash (upcase a)))

(define-hash-table-test 'case-fold
  'case-fold-string= 'case-fold-string-hash)

(defun uniq (beg end)
  "Print counts of strings in region."
  (interactive "r")
  (let ((h (make-hash-table :test 'case-fold))
        (lst (split-string (buffer-substring-no-properties beg end) "\n"
                           'omit-nulls " "))
        (output-func (if current-prefix-arg 'insert 'princ)))
    (dolist (str lst)
      (puthash str (1+ (gethash str h 0)) h))
    (maphash (lambda (key val)
               (apply output-func (list (format "%d: %s\n" val key))))
             h)))

Output when selecting that text

4: flower
1: park
3: stone


问:
Using a static class as an input parameter on another class
I have no idea if this is possible but it feels like it should be from using C# up to this point.

I want to have a bunch of static classes that contain 'set values' for users of the library to send into another class as parameter.

So this is where I was headed but I can't figure it out.  This below is just an example of what I was thinking so don't try and work out 'why' :-)

First - The Class that will be called

```<code>public class myClass
    {
        public bool isError { private set; get; }

        public DataTable output { private set; get; }

        public String filename { set; private get; }

        public settingModule settings { set; private get; }

        public static void execute()
        {

            //Call Private 'getTheData'
            //set isError accordingly
            //Load output

        }

        private static DataTable getTheData()
        {
            //Open and read file for 'fileName'

            //Use settings.startingRow
            //Use settings.fileType
            //User settings.skipEmpty

            //Do some stuff

            return Datatable from workings

        }

    }
</code>```

Second - The Class I want to user to pass

```<code>public static class settingMobule
    {
        public static class fileTypeA
        {
            public static int startingRow = 1;
            public static String fileType = "txt";
            public static bool skipEmpty = true;
        }

        public static class fileTypeB
        {
            public static int startingRow = 10;
            public static String fileType = "csv";
            public static bool skipEmpty = false;
        }

        public static class fileTypeC
        {
            public static int startingRow = 3;
            public static String fileType = "hex";
            public static bool skipEmpty = true;
        }

    }
</code>```

Lastly the way I want to be able to call it

```<code>myClass test = new myClass();

test.filename = "c:\\temp\\test.txt;

test.settings = settingModule.fileTypeA;

test.execute();

if(test.isError == false

{
DataTable myTable = test.output;
test.dispose()
}
</code>```

Thanks in advance... and yes, "your nuts there is a much better way" is a perfectly valid answer :-)

I would also LOVE to know how to add a .dispose() to my code, it's not something i have got to yet but while I am here... :-D

答:
Unfortunately in C# static classes are extremely limited in what they will allow you to do.

However, with Reflection and Types, you can do something similar, but I don't think you should.

```<code>void Main() {
    var test = new MyClass(typeof(settingModule.fileTypeB));
    Console.WriteLine(test.StartingRow);
}

public class MyClass {
    Type SettingsClass { get; set; }

    public MyClass(Type sc) {
        SettingsClass = sc;
    }

    public int StartingRow {
        get {
            return (int)SettingsClass.GetField("startingRow", BindingFlags.Static | BindingFlags.Public).GetValue(null);
        }
    }
}

public static class settingModule {
    public static class fileTypeA {
        public static int startingRow = 1;
        public static String fileType = "txt";
        public static bool skipEmpty = true;
    }

    public static class fileTypeB {
        public static int startingRow = 10;
        public static String fileType = "csv";
        public static bool skipEmpty = false;
    }

    public static class fileTypeC {
        public static int startingRow = 3;
        public static String fileType = "hex";
        public static bool skipEmpty = true;
    }

}
</code>```

I think what you should do is create instances of a subclass and pass that:

```<code>void Main() {
    var test = new MyClass();
    test.Settings = settingModule.fileTypeA;
    Console.WriteLine(test.Settings.startingRow);
}

public class MyClass {
    public settingModule.settingsSet Settings { get; set; }

}

public static class settingModule {
    public class settingsSet {
        public readonly int startingRow;
        public readonly string fileType;
        public readonly bool skipEmpty;
        public settingsSet(int sr, string ft, bool se) {
            startingRow = sr;
            fileType = ft;
            skipEmpty = se;
        }
    }

    public static settingsSet fileTypeA = new settingsSet(1, "txt", true);
    public static settingsSet fileTypeB = new settingsSet(10, "csv", false);
    public static settingsSet fileTypeC = new settingsSet(3, "hex", true);
}
</code>```

You can even make it written more like your static class:

```<code>public static class settingModule {
    public struct settingsSet {
        public int startingRow;
        public string fileType;
        public bool skipEmpty;
    }

    public static readonly settingsSet fileTypeA = new settingsSet {
        startingRow = 1,
        fileType = "txt",
        skipEmpty = true
    };

    public static readonly settingsSet fileTypeB = new settingsSet {
        startingRow = 10,
        fileType = "csv",
        skipEmpty = false
    };

    public static readonly settingsSet fileTypeC = new settingsSet {
        startingRow = 3,
        fileType = "hex",
        skipEmpty = true
    };
}
</code>```

Body:
I have no idea if this is possible but it feels like it should be from using C# up to this point.

I want to have a bunch of static classes that contain 'set values' for users of the library to send into another class as parameter.

So this is where I was headed but I can't figure it out.  This below is just an example of what I was thinking so don't try and work out 'why' :-)

First - The Class that will be called

public class myClass
    {
        public bool isError { private set; get; }

        public DataTable output { private set; get; }

        public String filename { set; private get; }

        public settingModule settings { set; private get; }

        public static void execute()
        {

            //Call Private 'getTheData'
            //set isError accordingly
            //Load output

        }

        private static DataTable getTheData()
        {
            //Open and read file for 'fileName'

            //Use settings.startingRow
            //Use settings.fileType
            //User settings.skipEmpty

            //Do some stuff

            return Datatable from workings

        }

    }

Second - The Class I want to user to pass

public static class settingMobule
    {
        public static class fileTypeA
        {
            public static int startingRow = 1;
            public static String fileType = "txt";
            public static bool skipEmpty = true;
        }

        public static class fileTypeB
        {
            public static int startingRow = 10;
            public static String fileType = "csv";
            public static bool skipEmpty = false;
        }

        public static class fileTypeC
        {
            public static int startingRow = 3;
            public static String fileType = "hex";
            public static bool skipEmpty = true;
        }

    }

Lastly the way I want to be able to call it

myClass test = new myClass();

test.filename = "c:\\temp\\test.txt;

test.settings = settingModule.fileTypeA;

test.execute();

if(test.isError == false

{
DataTable myTable = test.output;
test.dispose()
}

Thanks in advance... and yes, "your nuts there is a much better way" is a perfectly valid answer :-)

I would also LOVE to know how to add a .dispose() to my code, it's not something i have got to yet but while I am here... :-D

Body:
Unfortunately in C# static classes are extremely limited in what they will allow you to do.

However, with Reflection and Types, you can do something similar, but I don't think you should.

void Main() {
    var test = new MyClass(typeof(settingModule.fileTypeB));
    Console.WriteLine(test.StartingRow);
}

public class MyClass {
    Type SettingsClass { get; set; }

    public MyClass(Type sc) {
        SettingsClass = sc;
    }

    public int StartingRow {
        get {
            return (int)SettingsClass.GetField("startingRow", BindingFlags.Static | BindingFlags.Public).GetValue(null);
        }
    }
}

public static class settingModule {
    public static class fileTypeA {
        public static int startingRow = 1;
        public static String fileType = "txt";
        public static bool skipEmpty = true;
    }

    public static class fileTypeB {
        public static int startingRow = 10;
        public static String fileType = "csv";
        public static bool skipEmpty = false;
    }

    public static class fileTypeC {
        public static int startingRow = 3;
        public static String fileType = "hex";
        public static bool skipEmpty = true;
    }

}

I think what you should do is create instances of a subclass and pass that:

void Main() {
    var test = new MyClass();
    test.Settings = settingModule.fileTypeA;
    Console.WriteLine(test.Settings.startingRow);
}

public class MyClass {
    public settingModule.settingsSet Settings { get; set; }

}

public static class settingModule {
    public class settingsSet {
        public readonly int startingRow;
        public readonly string fileType;
        public readonly bool skipEmpty;
        public settingsSet(int sr, string ft, bool se) {
            startingRow = sr;
            fileType = ft;
            skipEmpty = se;
        }
    }

    public static settingsSet fileTypeA = new settingsSet(1, "txt", true);
    public static settingsSet fileTypeB = new settingsSet(10, "csv", false);
    public static settingsSet fileTypeC = new settingsSet(3, "hex", true);
}

You can even make it written more like your static class:

public static class settingModule {
    public struct settingsSet {
        public int startingRow;
        public string fileType;
        public bool skipEmpty;
    }

    public static readonly settingsSet fileTypeA = new settingsSet {
        startingRow = 1,
        fileType = "txt",
        skipEmpty = true
    };

    public static readonly settingsSet fileTypeB = new settingsSet {
        startingRow = 10,
        fileType = "csv",
        skipEmpty = false
    };

    public static readonly settingsSet fileTypeC = new settingsSet {
        startingRow = 3,
        fileType = "hex",
        skipEmpty = true
    };
}


问:
How to generate thumbnails from a PDF document with iPhone SDK?
I have read the Apple PDF documentation with Quartz.

But I do not know how to generate the thumbnails from a PDF document...

Any idea/sample code ?

答:
Here is my sample code.</p>

```<code>NSURL* pdfFileUrl = [NSURL fileURLWithPath:finalPath];
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfFileUrl);
CGPDFPageRef page;

CGRect aRect = CGRectMake(0, 0, 70, 100); // thumbnail size
UIGraphicsBeginImageContext(aRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
UIImage* thumbnailImage;

NSUInteger totalNum = CGPDFDocumentGetNumberOfPages(pdf);

for(int i = 0; i < totalNum; i++ ) {

    CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0.0, aRect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextSetGrayFillColor(context, 1.0, 1.0);
    CGContextFillRect(context, aRect);

    // Grab the first PDF page
    page = CGPDFDocumentGetPage(pdf, i + 1);
    CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, aRect, 0, true);
    // And apply the transform.
    CGContextConcatCTM(context, pdfTransform);

    CGContextDrawPDFPage(context, page);

    // Create the new UIImage from the context
    thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();

    //Use thumbnailImage (e.g. drawing, saving it to a file, etc)

    CGContextRestoreGState(context);

}

UIGraphicsEndImageContext();
CGPDFDocumentRelease(pdf);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is my sample code.

NSURL* pdfFileUrl = [NSURL fileURLWithPath:finalPath];
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfFileUrl);
CGPDFPageRef page;

CGRect aRect = CGRectMake(0, 0, 70, 100); // thumbnail size
UIGraphicsBeginImageContext(aRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
UIImage* thumbnailImage;

NSUInteger totalNum = CGPDFDocumentGetNumberOfPages(pdf);

for(int i = 0; i < totalNum; i++ ) {

    CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0.0, aRect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextSetGrayFillColor(context, 1.0, 1.0);
    CGContextFillRect(context, aRect);

    // Grab the first PDF page
    page = CGPDFDocumentGetPage(pdf, i + 1);
    CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, aRect, 0, true);
    // And apply the transform.
    CGContextConcatCTM(context, pdfTransform);

    CGContextDrawPDFPage(context, page);

    // Create the new UIImage from the context
    thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();

    //Use thumbnailImage (e.g. drawing, saving it to a file, etc)

    CGContextRestoreGState(context);

}

UIGraphicsEndImageContext();
CGPDFDocumentRelease(pdf);


问:
How do I fix an empty organization list in the Fabric Unity plugin during preparation?
Backstory:  I have had an existing Fabric account, with access to a previous team's title.  Said title was built in C++ for Android and for iOS natively, not Unity.  I've since moved to a new title, at a new studio, under the same parent organization - so I've kept my email address, etc.

I've been tasked with investigating Crashlytics integration into my current title (built in Unity), since I had prior experience at my old studio.  I'm following the documentation at https://docs.fabric.io/unity/crashlytics/installation.html.  I've downloaded the Fabric plugin, and included it in our existing project.  However, when I attempted to "Prepare Fabric", the resulting window ("Please select your organization") initially had no results.  I then created a new organization, at which point that window had two button options, one for the old studio and one for the new.

Neither button seemed to have any functionality when clicked.  Working under the assumption that I was getting some pollution from my old organization, I removed myself from it (so I am ostensibly only in my new organization, and in fact am both an admin and the only current member).  That just returned the selection window to the point of having no options again.

Trying to access the Fabric dashboard just gets me an onboarding screen, with no access to either the dashboard or my organization.  From there, I can begin the package download process again, but can go no further.  The standard 'gear' icon I'm used to seeing for user account settings is now just a power-button icon which I can use to log off.  (Logging off and back on does not fix the problem, though).

What step(s) am I missing?  Is my account borked due to membership in a prior organization?  How do I get back on track?

Thanks!

答:
After taking this offline, Mike from Fabric was able to help me figure this out.  Ultimately the problem boiled down to the fact that I was attempting to include the Fabric plugin at a different location in our project.  Moving the plugin to a home directly under the root /Assets folder fixed all the issues, and I'm now unblocked moving forward.

Thanks again, Mike!


问:
Matrix containing integers instead of doubles in Matlab
I have a large vector containing integers (length: 230 400, int8) which I rearrange into a 3-dimensional matrix (rows: 240, cols: 320, depth: 3). When this has been done the new matrix contains doubles instead of ints (according to Matlab Workspace).

The whole operation takes 0.3 seconds, which is to long for my purposes.

Is Matlab converting the ints in the array to doubles before putting them in the matrix?
Can this be avoided to speed it up?

Some code:

```<code>   tic;
   A=zeros(240,320,3);
   %A is matrix, B is vector.

   for i=1:240
       for j=1:320
           A(i,j,:)=B(1+(j-1)*3+(i-1)*320*3:3+(j-1)*3+(i-1)*320*3);
       end
   end

   toc;
</code>```

Thanks!

答:
Try initializing your matrix with</p>

```<code>A=zeros(240, 320, 3, 'int8')
</code>```

Body:
I have a large vector containing integers (length: 230 400, int8) which I rearrange into a 3-dimensional matrix (rows: 240, cols: 320, depth: 3). When this has been done the new matrix contains doubles instead of ints (according to Matlab Workspace).

The whole operation takes 0.3 seconds, which is to long for my purposes.

Is Matlab converting the ints in the array to doubles before putting them in the matrix?
Can this be avoided to speed it up?

Some code:

   tic;
   A=zeros(240,320,3);
   %A is matrix, B is vector.

   for i=1:240
       for j=1:320
           A(i,j,:)=B(1+(j-1)*3+(i-1)*320*3:3+(j-1)*3+(i-1)*320*3);
       end
   end

   toc;

Thanks!

Body:
Try initializing your matrix with

A=zeros(240, 320, 3, 'int8')


问:
How do declare an array in C++ as a parameter?
I am working with propriety code in my iOS project and all I have access to is the header files for my project. How do you declare an array in C++ so that it will return an array when I make a call?

Here's the header file method,

```<code> short WI_GetIDsFromList(int32_t module, int32_t *idsArray, uint32_t *count);
</code>```

How do you declare an array to received an array of in32_t? I keep getting a parameter error for returnedIdsArray when I make this call? It works perfectly fine for count? I tried making it into a pointer but it did not work?

```<code>    //Array of ID's
    int32_t returnedIdsArray[] = {};

    // Array of ID's count
    uint32_t count;

 rc += WI_GetIDsFromList(mod, returnedIdsArray, &count);
</code>```

Another Example

```<code>short dpCount;

//Get number of data points from the device
WI_GetDatapointCount(modIDHDS, &dpCount);

//dpCount now has returned value of method WI_GetDatapointCount
NSLog@"%d", int(dpCount);
</code>```

答:
I guess that what you are trying to do is to have the function output a set of int values where the length is not known at compile-time.

In C++ an array has a fixed size that must be known at compile-time.  The concept of "runtime-sized array" is called vector in C++.

Also, it is more natural to use the return value for values being returned. Your code could look like:

```<code>std::vector<int> WI_GetIDsFromList(int32_t mod);
</code>```

and the calling code could be:

```<code>auto values = WI_GetIDsFromList(mod);
</code>```

Body:
I am working with propriety code in my iOS project and all I have access to is the header files for my project. How do you declare an array in C++ so that it will return an array when I make a call?

Here's the header file method,

 short WI_GetIDsFromList(int32_t module, int32_t *idsArray, uint32_t *count);

How do you declare an array to received an array of in32_t? I keep getting a parameter error for returnedIdsArray when I make this call? It works perfectly fine for count? I tried making it into a pointer but it did not work?

    //Array of ID's
    int32_t returnedIdsArray[] = {};

    // Array of ID's count
    uint32_t count;

 rc += WI_GetIDsFromList(mod, returnedIdsArray, &count);

Another Example

short dpCount;

//Get number of data points from the device
WI_GetDatapointCount(modIDHDS, &dpCount);

//dpCount now has returned value of method WI_GetDatapointCount
NSLog@"%d", int(dpCount);

Body:
I guess that what you are trying to do is to have the function output a set of int values where the length is not known at compile-time.

In C++ an array has a fixed size that must be known at compile-time.  The concept of "runtime-sized array" is called vector in C++.

Also, it is more natural to use the return value for values being returned. Your code could look like:

std::vector<int> WI_GetIDsFromList(int32_t mod);

and the calling code could be:

auto values = WI_GetIDsFromList(mod);


问:
Recursive unitless element type
I am trying to come up with a function that gives me the recursive unitless element type. So for example, to shorten it let's call it ruet, I would like to have:

```<code>A = zeros(5,5)
reut(A) == Float64
using Unitful
A = zeros(5,5)*1u"kg"
reut(A) == Float64
AA = [zeros(5,5) for i in 1:5]
reut(AA) == Array{Float64,2}
AofA = [copy(A) for i in 1:5]
reut(AofA) == Array{Float64,2}
using StaticArrays
AofSA = [@SVector [2.0,3.0] for i in 1:5]
reut(AofSA) == SVector{2,Float64}
AofuSA = [@SVector [2.0u"kg",3.0u"kg"] for i in 1:5]
reut(AofuSA) == SVector{2,Float64}
</code>```

So basically strip away the units but still return the correct element type, which could be an array. It's the array part that's hard. I can recurse:

```<code>recursive_eltype(a) = recursive_eltype(eltype(a))
recursive_eltype{T<:Number}(a::Type{T}) = eltype(a)
</code>```

and then get the unitless element type:

```<code>uEltype = recursive_eltype(u)
uEltypeNoUnits = typeof(one(uEltype))
</code>```

but then this is always the number type, and I can't seem to find a good way to get back the array types when it's an array of arrays, i.e. this method is returning Float64 in all of the examples above. I am wondering if dispatching on static arrays and using similar_type is required here.

Note that I would like the solution to, if possible, not have a requirement on Unitful.jl. Getting the unitless type for the number can be done via one(u), so I think this should be possible.

(Somewhat related Julia issue: https://github.com/JuliaLang/julia/issues/22216)

答:
Using Julia version 0.6.2-something (code surely not very portable):

```<code>function _reut(T)
    try
        T.name == Quantity.body.body.body.name && return _reut(T.parameters[1])
        getfield(T.name.module, T.name.name){_reut.(collect(T.parameters))...}
    catch
        T
    end
end
reut(T) = _reut(eltype(T))
</code>```

And the tests in the question pass. Still not inferrable, but replaced eval with getfield(Module,Symbol). Where do you get these questions?

Title: Recursive unitless element type

Body:
I am trying to come up with a function that gives me the recursive unitless element type. So for example, to shorten it let's call it ruet, I would like to have:

A = zeros(5,5)
reut(A) == Float64
using Unitful
A = zeros(5,5)*1u"kg"
reut(A) == Float64
AA = [zeros(5,5) for i in 1:5]
reut(AA) == Array{Float64,2}
AofA = [copy(A) for i in 1:5]
reut(AofA) == Array{Float64,2}
using StaticArrays
AofSA = [@SVector [2.0,3.0] for i in 1:5]
reut(AofSA) == SVector{2,Float64}
AofuSA = [@SVector [2.0u"kg",3.0u"kg"] for i in 1:5]
reut(AofuSA) == SVector{2,Float64}

So basically strip away the units but still return the correct element type, which could be an array. It's the array part that's hard. I can recurse:

recursive_eltype(a) = recursive_eltype(eltype(a))
recursive_eltype{T<:Number}(a::Type{T}) = eltype(a)

and then get the unitless element type:

uEltype = recursive_eltype(u)
uEltypeNoUnits = typeof(one(uEltype))

but then this is always the number type, and I can't seem to find a good way to get back the array types when it's an array of arrays, i.e. this method is returning Float64 in all of the examples above. I am wondering if dispatching on static arrays and using similar_type is required here.

Note that I would like the solution to, if possible, not have a requirement on Unitful.jl. Getting the unitless type for the number can be done via one(u), so I think this should be possible.

(Somewhat related Julia issue: https://github.com/JuliaLang/julia/issues/22216)

Body:
Using Julia version 0.6.2-something (code surely not very portable):

function _reut(T)
    try
        T.name == Quantity.body.body.body.name && return _reut(T.parameters[1])
        getfield(T.name.module, T.name.name){_reut.(collect(T.parameters))...}
    catch
        T
    end
end
reut(T) = _reut(eltype(T))

And the tests in the question pass. Still not inferrable, but replaced eval with getfield(Module,Symbol). Where do you get these questions?


问:
C++ version highlighting
Is there a tool or plugin that one could use to tell

What c++ version is needed to compile the source files.

Let you highlight only the parts of the code that belongs to a certain c++ version.

Use case, I have a library that uses C++11, 14 and 17. I need to back port it to C++11. Hence I want to easily find what parts of the library I need to rework.

答:
I am not sure about tool. But you can go with a kind of elimination process.. Use command line flags for specific version of c++.

For example when using GCC

First compile your working source code with option -std=c++14. Then you can find all c++17 errors.

After fixing all c++17 errors next compile with option -std=c++11. You can find all c++14 errors.

Look into below link for overview.

https://gcc.gnu.org/projects/cxx-status.html

Title: C++ version highlighting


问:
Base operand of '->' has non-pointer type vector<object*>
```<code>std::vector<Piece*> player1, player2;

/* Filling player 1 and 2 vith piece
   player1.push_back(new Piece()) */

std::vector<Piece*> *currentPlayer, *opponent;

currentPlayer = &player1;
opponent      = &player2

for(int i = 0; i < currentPlayer.size(); ++i)
{
    // This is where i get the error
    // error: base operand of '->' has non-pointer type 'std::vector<Piece*>'
    currentPlayer[i]->memberFunctionOfPiece()
}
</code>```

As you can see I am trying to use a pointer pointing to a vector of pointers. but getting non-pointer type when trying to access the vector
Why can't i access the member function?

答:
The problem is that you are trying to use square brackets on a pointer type:

```<code>currentPlayer[i]->memberFunctionOfPiece();
</code>```

you can use operator[] or even better use the at function

```<code>currentPlayer->at(i)->memberFunctionOfPiece();
</code>```

or

```<code>currentPlayer->operator[](i)->memberFunctionOfPiece();
</code>```

Body:
std::vector<Piece*> player1, player2;

/* Filling player 1 and 2 vith piece
   player1.push_back(new Piece()) */

std::vector<Piece*> *currentPlayer, *opponent;

currentPlayer = &player1;
opponent      = &player2

for(int i = 0; i < currentPlayer.size(); ++i)
{
    // This is where i get the error
    // error: base operand of '->' has non-pointer type 'std::vector<Piece*>'
    currentPlayer[i]->memberFunctionOfPiece()
}

As you can see I am trying to use a pointer pointing to a vector of pointers. but getting non-pointer type when trying to access the vector
Why can't i access the member function?

Body:
The problem is that you are trying to use square brackets on a pointer type:

currentPlayer[i]->memberFunctionOfPiece();

you can use operator[] or even better use the at function

currentPlayer->at(i)->memberFunctionOfPiece();

or

currentPlayer->operator[](i)->memberFunctionOfPiece();


问:
Sum averages over date ranges in Django
I'm trying to construct a query in Django that sums averages that were taken (i.e. averaged) over a range of times.

Here is the relevant Django model:

```<code>class Data(models.Model):

    class Meta:
        verbose_name_plural = "Data"

    site = models.ForeignKey(Site)
    created_on = models.DateTimeField(auto_created=True)
    reported_on = models.DateTimeField(null=True, blank=True)
    baseline_power_kw = models.FloatField('Baseline Power (kw)', blank=True, null=True)
    measured_power_kw = models.FloatField('Measured Power (kw)', blank=True, null=True)
</code>```

In my query, I'm trying to average sites' data over a range of times, and then sum those averages for each range of time. Here is the query I have so far, which I believe just gets the average of all sites' data over a range of times.

```<code>        t_data = Data.objects.filter(site__in=sites) \
                                  .filter(created_on__range=(start, end)) \
                                  .extra(select={'date_slice': "trunc(extract(epoch from created_on) / '60' )"}) \
                                  .values('date_slice') \
                                  .annotate(avg_baseline_power_kw=Avg('baseline_power_kw'),
                                            avg_measured_power_kw=Avg('measured_power_kw'),
                                            time=Min('created_on')) \
                                  .order_by('-created_on')
</code>```

Do you know how I can proceed? I am using Django with Postgres.

Thanks!

答:
If you add 'site' to your .values() clause, like this:

```<code>.values('date_slice', 'site')
</code>```

and remove the order_by, which will cause the 'created_on' field to get added to the generated SQL GROUP BY, you should get averages for your two measurements for each slice+site.  You can then sum those values to get the totals across all sites.

Title: Sum averages over date ranges in Django

Body:
I'm trying to construct a query in Django that sums averages that were taken (i.e. averaged) over a range of times.

Here is the relevant Django model:

class Data(models.Model):

    class Meta:
        verbose_name_plural = "Data"

    site = models.ForeignKey(Site)
    created_on = models.DateTimeField(auto_created=True)
    reported_on = models.DateTimeField(null=True, blank=True)
    baseline_power_kw = models.FloatField('Baseline Power (kw)', blank=True, null=True)
    measured_power_kw = models.FloatField('Measured Power (kw)', blank=True, null=True)

In my query, I'm trying to average sites' data over a range of times, and then sum those averages for each range of time. Here is the query I have so far, which I believe just gets the average of all sites' data over a range of times.

        t_data = Data.objects.filter(site__in=sites) \
                                  .filter(created_on__range=(start, end)) \
                                  .extra(select={'date_slice': "trunc(extract(epoch from created_on) / '60' )"}) \
                                  .values('date_slice') \
                                  .annotate(avg_baseline_power_kw=Avg('baseline_power_kw'),
                                            avg_measured_power_kw=Avg('measured_power_kw'),
                                            time=Min('created_on')) \
                                  .order_by('-created_on')

Do you know how I can proceed? I am using Django with Postgres.

Thanks!

Body:
If you add 'site' to your .values() clause, like this:

.values('date_slice', 'site')

and remove the order_by, which will cause the 'created_on' field to get added to the generated SQL GROUP BY, you should get averages for your two measurements for each slice+site.  You can then sum those values to get the totals across all sites.


问:
How to restart shiny server in Docker container?
I have a Dockerized R Shiny app that extends the rocker/shiny image. I would like to restart the shiny-server inside of the Docker container at some point. From the documentation of shiny-server, I tried all the commands for different Linux builds and none of them worked.

Does anyone know how to restart the shiny-server in the Docker container?

答:
The command

```<code>docker ps
</code>```

lists all running containers, get the required container id. Then run

```<code>docker exec -it <container_id> bash
</code>```

to get into the required docker container. Then

```<code>sudo -i
sudo systemctl restart shiny-server
</code>```

to restart the shiny server. Hope that helps, systemctl will probably only work on Ubuntu.

Body:
The command

docker ps

lists all running containers, get the required container id. Then run

docker exec -it <container_id> bash

to get into the required docker container. Then

sudo -i
sudo systemctl restart shiny-server

to restart the shiny server. Hope that helps, systemctl will probably only work on Ubuntu.


问:
Spark: Extracting summary for a ML logistic regression model from a pipeline model
I've estimated a logistic regression using pipelines.

My last few lines before fitting the logistic regression:

```<code>from pyspark.ml.feature import VectorAssembler
from pyspark.ml.classification import LogisticRegression
lr = LogisticRegression(featuresCol="lr_features", labelCol = "targetvar")
# create assember to include encoded features
    lr_assembler = VectorAssembler(inputCols= numericColumns +
                               [categoricalCol + "ClassVec" for categoricalCol in categoricalColumns],
                               outputCol = "lr_features")
from pyspark.ml.classification import LogisticRegression
from pyspark.ml import Pipeline
# Model definition:
lr = LogisticRegression(featuresCol = "lr_features", labelCol = "targetvar")
# Pipeline definition:
lr_pipeline = Pipeline(stages = indexStages + encodeStages +[lr_assembler, lr])
# Fit the logistic regression model:
lrModel = lr_pipeline.fit(train_train)
</code>```

And then I tried to run the summary of the model. However, the code line below:

```<code>trainingSummary = lrModel.summary
</code>```

results in: 'PipelineModel' object has no attribute 'summary'

Any advice on how one could extract the summary information that is usually contained in regression's model from a pipeline model?

Thanks a lot!

答:
Just get the model from stages:

```<code>lrModel.stages[-1].summary
</code>```

If model is earlier in the Pipeline replace -1 with its index.

Body:
I've estimated a logistic regression using pipelines.

My last few lines before fitting the logistic regression:

from pyspark.ml.feature import VectorAssembler
from pyspark.ml.classification import LogisticRegression
lr = LogisticRegression(featuresCol="lr_features", labelCol = "targetvar")
# create assember to include encoded features
    lr_assembler = VectorAssembler(inputCols= numericColumns +
                               [categoricalCol + "ClassVec" for categoricalCol in categoricalColumns],
                               outputCol = "lr_features")
from pyspark.ml.classification import LogisticRegression
from pyspark.ml import Pipeline
# Model definition:
lr = LogisticRegression(featuresCol = "lr_features", labelCol = "targetvar")
# Pipeline definition:
lr_pipeline = Pipeline(stages = indexStages + encodeStages +[lr_assembler, lr])
# Fit the logistic regression model:
lrModel = lr_pipeline.fit(train_train)

And then I tried to run the summary of the model. However, the code line below:

trainingSummary = lrModel.summary

results in: 'PipelineModel' object has no attribute 'summary'

Any advice on how one could extract the summary information that is usually contained in regression's model from a pipeline model?

Thanks a lot!

Body:
Just get the model from stages:

lrModel.stages[-1].summary

If model is earlier in the Pipeline replace -1 with its index.


问:
Find the second largest number in array
I have an array of three element like [31,23,12] and I want to find the second largest element and its related position without rearranging the array.

Example :

```<code>array = [21,23,34]
</code>```

Second_largest = 23;

Position is = 1;

答:
This way is the most verbose, but also the most algorithmically efficient. It only requires 1 pass through the original array, does not require copying the array, nor sorting. It is also ES5 compliant, since you were asking about supportability.

var array = [21,23,34];

var res = array.reduce(function (results, curr, index) {
    if (index === 0) {
        results.largest = curr;
        results.secondLargest = curr;
        results.indexOfSecondLargest = 0;
        results.indexOfLargest = 0;
    }
    else if (curr > results.secondLargest && curr <= results.largest) {
        results.secondLargest = curr;
        results.indexOfSecondLargest = index;
    }
    else if (curr > results.largest) {
        results.secondLargest = results.largest;
        results.largest = curr;
        results.indexOfSecondLargest = results.indexOfLargest;
        results.indexOfLargest = index;
    }
    return results;
}, {largest: -Infinity, secondLargest: -Infinity, indexOfLargest: -1, indexOfSecondLargest: -1});

console.log("Second Largest: ", res.secondLargest);
console.log("Index of Second Largest: ", res.indexOfSecondLargest);```

Title: Find the second largest number in array

Body:
I have an array of three element like [31,23,12] and I want to find the second largest element and its related position without rearranging the array.

Example :

array = [21,23,34]

Second_largest = 23;

Position is = 1;


问:
How do I set the background process name?
How do I set the name of my program's process, so in task manager instead of seeing "Program.exe(32 bit)" it just shows the name like "Name (32 bit)".Such as it not having the .exe at the end.</p>

答:
Processes in Windows have no "name" property, which can be set or read.

Different utilities, like Task Manager, can show you the name of the EXE file which created the process, as well as the FileDescription from the EXE's VERSIONINFO resource (if it exists), the process's command line, etc.

However, you have no control over how such utilities decide to display your process. Currently, Task Manager tries to show the FileDescription from the EXE's version resource, and if it does not exist then shows the name of EXE file instead.


问:
On logout redirect to login page
I'm trying to get react router 4 to redirect to my login page that is publicly available when the user clicks the the logout button in their Navbar. The logout function works, the user is logged out, however, the redirect never happens. What am I missing here?

I'm using react-router v4 and meteorjs.

<button type="button" className="btn btn-link logout-button" onClick={() => Meteor.logout(() => (<Redirect to="/login" />))}>Logout</button>

答:
```<code>import { Redirect } from "react-router";
class Header extends Component {
 constructor(props){
  super(props);

  this.state = {
    isLoggedIn: Meteor.userId(),
  }
 }

handleLogout(e){
e.preventDefault();

  Meteor.logout((error) =>{
    if (error) {
      console.log(error.reason);
    }else{
      this.setState({isLoggedIn: !this.state.isLoggedIn,});
      console.log("Logout successful");
     }
 });
}

render() {
 return (
   {
    (this.state.isLoggedIn) &&
      <Redirect to="/Login" />
    }
 );
}
</code>```

Just do exactly like that it should redirect you.

Title: On logout redirect to login page

Body:
import { Redirect } from "react-router";
class Header extends Component {
 constructor(props){
  super(props);

  this.state = {
    isLoggedIn: Meteor.userId(),
  }
 }

handleLogout(e){
e.preventDefault();

  Meteor.logout((error) =>{
    if (error) {
      console.log(error.reason);
    }else{
      this.setState({isLoggedIn: !this.state.isLoggedIn,});
      console.log("Logout successful");
     }
 });
}

render() {
 return (
   {
    (this.state.isLoggedIn) &&
      <Redirect to="/Login" />
    }
 );
}

Just do exactly like that it should redirect you.


问:
Why is there another post request after submitting a form?
I am using Django to create a form where users will have to enter their email to get notified in the future. After successfully submitting the form I get a post call that refreshes the page that the form is in:

```<code>[07/Dec/2017 01:22:41] "POST /notify-email/add/ HTTP/1.1" 200 21
[07/Dec/2017 01:22:42] "POST / HTTP/1.1" 200 23030
</code>```

Below is the relevant code:

views.py

```<code>def add_notify_email(request):
        if request.method == "POST":
            form = NotifyEmailForm(request.POST)
            if form.is_valid():
                form.save(commit=True)
                return JsonResponse({"status": "success"})
            else:
                return JsonResponse({"status": "error"})
        else:
            form = NotifyEmailForm()
        return render(request, "landing/home.html", {"form": form})
</code>```

html

```<code><form class="form" onsubmit="addNotifyEmailInHero()" method="POST" id="notify_email_form_in_hero">
        {% csrf_token %}
        <div class="form-group row">
            <div class="col-sm-10 input-group" id="email_input_in_hero">
                <div class="input-group-addon" id="coming_soon_email_icon_in_hero"><i class="fa fa-envelope fa fa-2x" aria-hidden="true" id="email_icon_in_hero"></i></div>
                <input class="form-control" type="email" name="email" onkeypress="if(event.keyCode === 13){addNotifyEmailInHero()}" placeholder="If you want to get notified when we go live, please enter your email...." maxlength="255" required id="id_email"/>
            </div>
            <div class="col-sm-2" id="notify_email_button_in_hero">
                <button type="submit" class="btn btn-block btn-primary" id="submit_notify_email_in_hero"><i class="fa fa-bell nav-icon" aria-hidden="true"></i>Notify Me</button>
            </div>
        </div>
    </form>

    <script src="coming_soon.js"></script>
</code>```

coming_soon.js

```<code>function addNotifyEmailInHero(e){
        var notifyEmailForm = $("#notify_email_form_in_hero");
        var thanksModal = $("#thanks");

        $.ajax({
        type: 'POST',
        url: '/notify-email/add/',
        data: notifyEmailForm.serialize(),
        success: function(res){
                   alert(res.status);
                   if(res.status === "success") {
                        thanksModal.modal('show');
                            }

                    else {$("#id_email").val("");
                          $("#id_email").attr("placeholder", "Please Enter A Valid Email Address");
                            }
        }
    })}
</code>```

What I think is happening:

When you click the button or press enter the form gets "submitted", that means the onsubmit function runs. Specifically, in the js script, you get the form and the modal, then there is an ajax post request with the data from the form to /notify-email/add/.

Based on the urls.py, /notify-email/add/ is connected to the add_notify_email functional view in views.py. This function checks if it is a post request and if the form is valid it saves the data to the database and returns a json response, if the form is not valid it returns also a json response.

If the request is not a post request it renders the specified template.

If add_notify_email returns a json response that gets handled by the js function in coming_soon.js.

That's my understanding of what really is going on.

答: Because you have an onsubmit handler that ultimately makes an AJAX call to /notify-email/add/, and then the form is submitted to its own handler, which is / because you did not specify a handler.</p>

Body:
I am using Django to create a form where users will have to enter their email to get notified in the future. After successfully submitting the form I get a post call that refreshes the page that the form is in:

[07/Dec/2017 01:22:41] "POST /notify-email/add/ HTTP/1.1" 200 21
[07/Dec/2017 01:22:42] "POST / HTTP/1.1" 200 23030

Below is the relevant code:

views.py

def add_notify_email(request):
        if request.method == "POST":
            form = NotifyEmailForm(request.POST)
            if form.is_valid():
                form.save(commit=True)
                return JsonResponse({"status": "success"})
            else:
                return JsonResponse({"status": "error"})
        else:
            form = NotifyEmailForm()
        return render(request, "landing/home.html", {"form": form})

html

<form class="form" onsubmit="addNotifyEmailInHero()" method="POST" id="notify_email_form_in_hero">
        {% csrf_token %}

                <input class="form-control" type="email" name="email" onkeypress="if(event.keyCode === 13){addNotifyEmailInHero()}" placeholder="If you want to get notified when we go live, please enter your email...." maxlength="255" required id="id_email"/>

                <button type="submit" class="btn btn-block btn-primary" id="submit_notify_email_in_hero">Notify Me</button>

    </form>

coming_soon.js

function addNotifyEmailInHero(e){
        var notifyEmailForm = $("#notify_email_form_in_hero");
        var thanksModal = $("#thanks");

        $.ajax({
        type: 'POST',
        url: '/notify-email/add/',
        data: notifyEmailForm.serialize(),
        success: function(res){
                   alert(res.status);
                   if(res.status === "success") {
                        thanksModal.modal('show');
                            }

                    else {$("#id_email").val("");
                          $("#id_email").attr("placeholder", "Please Enter A Valid Email Address");
                            }
        }
    })}

What I think is happening:

When you click the button or press enter the form gets "submitted", that means the onsubmit function runs. Specifically, in the js script, you get the form and the modal, then there is an ajax post request with the data from the form to /notify-email/add/.

Based on the urls.py, /notify-email/add/ is connected to the add_notify_email functional view in views.py. This function checks if it is a post request and if the form is valid it saves the data to the database and returns a json response, if the form is not valid it returns also a json response.

If the request is not a post request it renders the specified template.

If add_notify_email returns a json response that gets handled by the js function in coming_soon.js.

That's my understanding of what really is going on.


问:
'Un'-externalize strings from Eclipse or Intellij
I have a bunch of strings in a properties file which i want to 'un-externalize', ie inline into my code.

I see that both Eclipse and Intellij have great support to 'externalize' strings from within code, however do any of them support inlining strings from a properties file back into code?

For example if I have code like -

My.java

```<code>System.out.println(myResourceBundle.getString("key"));
</code>```

My.properties

```<code>key=a whole bunch of text
</code>```

I want my java code to be replaced as -

My.java

```<code>System.out.println("a whole bunch of text");
</code>```

答:
I would recommend something else: split externalized strings into localizable and non-localizable properties files. It would be probably easier to move some strings to another file than moving it back to source code (which will hurt maintainability by the way).

Of course you can write simple (to some extent) Perl (or whatever) script which will search for calls to resource bundles and introduce constant in this place...
In other words, I haven't heard about de-externalizing mechanism, you need to do it by hand (or write some automated script yourself).

Body:
I have a bunch of strings in a properties file which i want to 'un-externalize', ie inline into my code.

I see that both Eclipse and Intellij have great support to 'externalize' strings from within code, however do any of them support inlining strings from a properties file back into code?

For example if I have code like -

My.java

System.out.println(myResourceBundle.getString("key"));

My.properties

key=a whole bunch of text

I want my java code to be replaced as -

My.java

System.out.println("a whole bunch of text");


问:
Debian rkhunter warning when using --pkgmgr option
I have a web server using rkhunter for rootkit protection.

When I check, rkhunter returns no warnings in the root kit part (so I guess I'm good). But I get a lot of warning when Performing file properties checks.

I figured out that this can be caused every time I update my system (apt-get dist-upgrade), because some files change during the update. Then rkhunter recognizes these changes.

After further research, I figured out that the option "--pkgmgr DPKG" should check against the latest values in the repository. So in theory (as far as I understood), it should return without warnings.

But it does not work and since I get an email as soon as rkhunter returns a warning I would like to know how to avoid these warnings.

答:
You can avoid these warnings by researching what the warnings are and what others have done.  Check the log file that rkhunter tells you to when it completes, google the lines.

Hopefully you can whitelist the problems.

Understanding rkhunter warnings


问:
Inline alias for Kotlin function that includes generics?
I have shortened the names of some frequently-used foreign functions (that I don't control) with "aliases", based on advice I received in an earlier question.  This has worked nicely for extension functions; however, I have a few top-level functions I'd like to alias as well.  For a simplified example, consider the generateSequence function.  I want to be able to do this:

```<code>// DOES NOT COMPILE
inline val <T:Any> seq:(()->T?)->Sequence<T> get() = ::generateSequence
</code>```

...but I can't because the generic must be used in the receiver type, as explained well in this answer.  Is there any other way to create an alias for a top-level function (requiring generics) which preserves the inline?

EDIT: I tried using Any? and star projection right after posting the question, but I still don't think it's a good answer:

```<code>inline val seq:(()->Any?)->Sequence<*> get() = ::generateSequence
</code>```

This seems boptimalsu because it compromises type-checking on the Sequence's element type, correct?  Other answers/thoughts as to what could work?

答:
An option that you could use is a renaming import, though it is limited to a single source file:

```<code>import kotlin.sequences.generateSequence as seq

fun main(args: Array<String>) {
    seq(1) { it + 1 }.take(10).forEach(::println)
}
</code>```

Apart from that, I think, the best you could do is to fall back to declaring another inline function:

```<code>inline fun <T> seq(nextFunction: () -> T?) =
    generateSequence(nextFunction)
</code>```

In fact, I'd expect the performance of this option to be better than of the one with a function reference, because using an inline property returning a function reference still has some overhead when you make a call to that reference, while this call is inlined and thus should introduce no overhead for another nested call.

Body:
I have shortened the names of some frequently-used foreign functions (that I don't control) with "aliases", based on advice I received in an earlier question.  This has worked nicely for extension functions; however, I have a few top-level functions I'd like to alias as well.  For a simplified example, consider the generateSequence function.  I want to be able to do this:

// DOES NOT COMPILE
inline val <T:Any> seq:(()->T?)->Sequence<T> get() = ::generateSequence

...but I can't because the generic must be used in the receiver type, as explained well in this answer.  Is there any other way to create an alias for a top-level function (requiring generics) which preserves the inline?

EDIT: I tried using Any? and star projection right after posting the question, but I still don't think it's a good answer:

inline val seq:(()->Any?)->Sequence<*> get() = ::generateSequence

This seems boptimalsu because it compromises type-checking on the Sequence's element type, correct?  Other answers/thoughts as to what could work?

Body:
An option that you could use is a renaming import, though it is limited to a single source file:

import kotlin.sequences.generateSequence as seq

fun main(args: Array<String>) {
    seq(1) { it + 1 }.take(10).forEach(::println)
}

Apart from that, I think, the best you could do is to fall back to declaring another inline function:

inline fun <T> seq(nextFunction: () -> T?) =
    generateSequence(nextFunction)

In fact, I'd expect the performance of this option to be better than of the one with a function reference, because using an inline property returning a function reference still has some overhead when you make a call to that reference, while this call is inlined and thus should introduce no overhead for another nested call.


问:
PostSharp [NotifyPropertyChanged] does not work for properties from base class
I am tryig to do a PoC with PostSharp [NotifyPropertyChanged] feature.
Suppose that I have some model assembly containing my model classes (simple POCOs) which does not implement INotifyPropertyChanged and cannot be changed.

```<code>namespace Ryu.Model
{
    public class PersonModel
    {
        public int Id { get; set; }

        public string DisplayName { get; set; }

        public DateTime? ModifiedDate { get; set; }
    }
}
</code>```

And I want to introduce a Wrapper layer, which simply inherits from Model's classes and apply PostSharp's [NotifyPropertyChanged] feature.

```<code>namespace Ryu.Wrapper
{
    [NotifyPropertyChanged]
    public class PersonWrapper : PersonModel
    {
    }
}
</code>```

I was expecting this to work and apply PropertyChanged to all properties of base class (PersonModel). But it does not work. Is there any trick to make this work?

答:
PostSharp weaves additional code into the methods and properties of a class when you apply [NotifyPropertyChanged] aspect to that class.

In your case the properties of PersonModel are not modified, because it does not have the aspect applied to it. And I understand that you would not want to apply any changes to PersonModel class. However, the properties are derived as-is by PersonWrapper and so they cannot behave differently in these two classes.

However, if the case is that you would like to add INotifyPropertyChanged implementation to PersonModel but you don't have the source code of the assembly, then you can process the existing assembly by running PostSharp on the command-line. This will produce a new assembly with the aspects weaved into the selected classes. Please refer to the documentation for more information: http://doc.postsharp.net/command-line

Body:
I am tryig to do a PoC with PostSharp [NotifyPropertyChanged] feature.
Suppose that I have some model assembly containing my model classes (simple POCOs) which does not implement INotifyPropertyChanged and cannot be changed.

namespace Ryu.Model
{
    public class PersonModel
    {
        public int Id { get; set; }

        public string DisplayName { get; set; }

        public DateTime? ModifiedDate { get; set; }
    }
}

And I want to introduce a Wrapper layer, which simply inherits from Model's classes and apply PostSharp's [NotifyPropertyChanged] feature.

namespace Ryu.Wrapper
{
    [NotifyPropertyChanged]
    public class PersonWrapper : PersonModel
    {
    }
}

I was expecting this to work and apply PropertyChanged to all properties of base class (PersonModel). But it does not work. Is there any trick to make this work?


问:
How to assign System.Drawing.Color to Microsoft.Office.Interop.Excel.ColorFormat
Sample code as follow,

```<code>Chart.SerialsCollection(1).Point(1).Format.Fill.ForeColor = System.Drawing.Color.Red;
</code>```

Return an error. Cannot implicitly convert type, one is a Struct, the other is ColorFormat.

ForeColor.RGB is Int type, I can only get 3 ints from Color.Red.R, Color.Red.G and Color.Red.B.  How to assign the color I want to ForeColor property?

答:
As suggested in the comments, use ColorTranslator.ToOle

```<code>Chart.SerialsCollection(1).Point(1).Format.Fill.ForeColor.RGB = ColorTranslator.ToOle(Color.Red);
</code>```

Or, entering the RGB values:

```<code>Chart.SerialsCollection(1).Point(1).Format.Fill.ForeColor.RGB = ColorTranslator.ToOle(Color.FromArgb(255, 0, 0);
</code>```

Some additional information, so I'm not just repeating the comments:

ForeColor.RGB can be represented in Hex as 0xBBGGRR (source). Knowing that, you could create the following function:

```<code>public int Color_to_RGB(Color color) {
    return (color.B << 16) | (color.G << 8) | Color.R;
}
</code>```

Use:

```<code>Chart.SerialCollection(1).Point(1).Format.Fill.ForeColor.RGB = Color_to_RGB(Color.Red);
</code>```

The reason ToArgb(), used in the other answer, does not work because its Hex representation is 0xAARRGGBB

Body:
Sample code as follow,

Chart.SerialsCollection(1).Point(1).Format.Fill.ForeColor = System.Drawing.Color.Red;

Return an error. Cannot implicitly convert type, one is a Struct, the other is ColorFormat.

ForeColor.RGB is Int type, I can only get 3 ints from Color.Red.R, Color.Red.G and Color.Red.B.  How to assign the color I want to ForeColor property?

Body:
As suggested in the comments, use ColorTranslator.ToOle

Chart.SerialsCollection(1).Point(1).Format.Fill.ForeColor.RGB = ColorTranslator.ToOle(Color.Red);

Or, entering the RGB values:

Chart.SerialsCollection(1).Point(1).Format.Fill.ForeColor.RGB = ColorTranslator.ToOle(Color.FromArgb(255, 0, 0);

Some additional information, so I'm not just repeating the comments:

ForeColor.RGB can be represented in Hex as 0xBBGGRR (source). Knowing that, you could create the following function:

public int Color_to_RGB(Color color) {
    return (color.B << 16) | (color.G << 8) | Color.R;
}

Use:

Chart.SerialCollection(1).Point(1).Format.Fill.ForeColor.RGB = Color_to_RGB(Color.Red);

The reason ToArgb(), used in the other answer, does not work because its Hex representation is 0xAARRGGBB


问:
Scrambling/Unscrambling a string in Classic ASP
I'm wanting to send a string that has some meaning through the URL.

I know that I could probably do other things to send a string, but this is the only way in this situation.

I'm wanting send it and an unreadable format and be able to get the original string back later. I'm trying to avoid the words encrypt/decrypt because I've done research and It seems a bit more envolved than what I'm wanting in classic ASP( unless I'm missing something ). So I'm not really wanting to IMPLEMENT a encrypt/decrypt algorithm. I'm hoping there is something built into ASP that will allow me to do this.

I'm looking for both the way to scramble the message and a way to get it back.

Any suggestions?

答:
Doug Chamberlain should mentioned that his example for numerical values only.

And if you want to really encrypt what you are passing between ASP pages use link which was suggested by George.

Tested by me and it does exactly what you need, no matter what type of data you are passing: strings or numerical.

And if you going to re-use any of data then session variable is best bet for you, you do not need to scramble data for that.
Keep in mind that from testing your site should be using port 80 for session variable work as intended.

There is some kind of bug in IIS 7 which clearing up sessions in really short period of time or if your user submit anything else.


问:
Unit testing with Moq method invoked inside of Task.Run
I am trying to mock a service call inside of a method that I want to test.

The method body looks like this:

```<code>public string OnActionException(HttpActionContext httpRequest, Exception ex)
{
    var formattedActionException = ActionLevelExceptionManager.GetActionExceptionMessage(httpRequest);

    var mainErrorMessage = $"[{formattedActionException.ErrorId}]{formattedActionException.ErrorMessage}, {ex.Message}";

    this.LogError(mainErrorMessage, ex);

    if (this._configuration.MailSupportOnException)
        Task.Run(async () => await this._mailService.SendEmailForThrownException(this._configuration.SupportEmail, $"{mainErrorMessage} ---> Stack trace: {ex.StackTrace.ToString()}"));

    return $"(ErrID:{formattedActionException.ErrorId}) {formattedActionException.ErrorMessage} {formattedActionException.KindMessage}";
}
</code>```

What I am trying to mock inside my test is:

Task.Run(async () => await this._mailService.SendEmailForThrownException(this._configuration.SupportEmail, $"{mainErrorMessage} ---> Stack trace: {ex.StackTrace.ToString()}"));

The test method looks like this:

```<code>[TestMethod]
public void We_Send_System_Exception_On_Email_If_Configured_In_Settings()
{
    // arrange
    this._configurationWrapperMock.Setup(cwm => cwm.MailSupportOnException)
        .Returns(true);
    this._mailServiceMock.Setup(msm => msm.SendEmailForThrownException(It.IsAny<string>(), It.IsAny<string>()))
        .Returns(Task.FromResult(0));

    // act
    var logger = new ApiLogger(this._configurationWrapperMock.Object, this._mailServiceMock.Object);
    logger.OnActionException(
        new HttpActionContext(
            new HttpControllerContext()
            {
                Request = new HttpRequestMessage()
                {
                    Method = HttpMethod.Get,
                    RequestUri = new System.Uri("https://www.google.bg/")
                }
            },
            new ReflectedHttpActionDescriptor() { }
        ),
        new System.Exception());

    // assert
    this._mailServiceMock.Verify(
        msm => msm.SendEmailForThrownException(It.IsAny<string>(), It.IsAny<string>()),
        Times.Once);
}
</code>```

The problem is that the method is never invoked, so my assert fails.

EDIT: I could change my question to: How do I need to re-write my method in order to make it testable?

答:
Your code is a classic situation to apply Humble Object Pattern.

In this case all you have to do is to extract Task.Run into a virtual method, then partial mock the SUT and override this virtual method:

```<code>public class ApiLogger
{
    ...

    public string OnActionException(Exception ex)
    {
        ...
        if (this._configuration.MailSupportOnException)
            RunInTask(...);
        ...
    }

    public virtual Task RunInTask(Action action)
    {
        return Task.Run(action);
    }
}
</code>```

Then the test will look like:

```<code>[TestMethod]
public void We_Send_System_Exception_On_Email_If_Configured_In_Settings()
{
    ...

    var logger = new Mock<ApiLogger>(MockBehavior.Default,
                                     new object[]
                                     {
                                       this._configurationWrapperMock.Object,
                                       this._mailServiceMock.Object
                                     }).Object;

    logger.OnActionException(...);

    this._mailServiceMock.Verify(
            msm => msm.SendEmailForThrownException(It.IsAny<string>(), It.IsAny<string>()),
            Times.Once);
}
</code>```

Body:
I am trying to mock a service call inside of a method that I want to test.

The method body looks like this:

public string OnActionException(HttpActionContext httpRequest, Exception ex)
{
    var formattedActionException = ActionLevelExceptionManager.GetActionExceptionMessage(httpRequest);

    var mainErrorMessage = $"[{formattedActionException.ErrorId}]{formattedActionException.ErrorMessage}, {ex.Message}";

    this.LogError(mainErrorMessage, ex);

    if (this._configuration.MailSupportOnException)
        Task.Run(async () => await this._mailService.SendEmailForThrownException(this._configuration.SupportEmail, $"{mainErrorMessage} ---> Stack trace: {ex.StackTrace.ToString()}"));

    return $"(ErrID:{formattedActionException.ErrorId}) {formattedActionException.ErrorMessage} {formattedActionException.KindMessage}";
}

What I am trying to mock inside my test is:

Task.Run(async () => await this._mailService.SendEmailForThrownException(this._configuration.SupportEmail, $"{mainErrorMessage} ---> Stack trace: {ex.StackTrace.ToString()}"));

The test method looks like this:

[TestMethod]
public void We_Send_System_Exception_On_Email_If_Configured_In_Settings()
{
    // arrange
    this._configurationWrapperMock.Setup(cwm => cwm.MailSupportOnException)
        .Returns(true);
    this._mailServiceMock.Setup(msm => msm.SendEmailForThrownException(It.IsAny<string>(), It.IsAny<string>()))
        .Returns(Task.FromResult(0));

    // act
    var logger = new ApiLogger(this._configurationWrapperMock.Object, this._mailServiceMock.Object);
    logger.OnActionException(
        new HttpActionContext(
            new HttpControllerContext()
            {
                Request = new HttpRequestMessage()
                {
                    Method = HttpMethod.Get,
                    RequestUri = new System.Uri("https://www.google.bg/")
                }
            },
            new ReflectedHttpActionDescriptor() { }
        ),
        new System.Exception());

    // assert
    this._mailServiceMock.Verify(
        msm => msm.SendEmailForThrownException(It.IsAny<string>(), It.IsAny<string>()),
        Times.Once);
}

The problem is that the method is never invoked, so my assert fails.

EDIT: I could change my question to: How do I need to re-write my method in order to make it testable?

Body:
Your code is a classic situation to apply Humble Object Pattern.

In this case all you have to do is to extract Task.Run into a virtual method, then partial mock the SUT and override this virtual method:

public class ApiLogger
{
    ...

    public string OnActionException(Exception ex)
    {
        ...
        if (this._configuration.MailSupportOnException)
            RunInTask(...);
        ...
    }

    public virtual Task RunInTask(Action action)
    {
        return Task.Run(action);
    }
}

Then the test will look like:

[TestMethod]
public void We_Send_System_Exception_On_Email_If_Configured_In_Settings()
{
    ...

    var logger = new Mock<ApiLogger>(MockBehavior.Default,
                                     new object[]
                                     {
                                       this._configurationWrapperMock.Object,
                                       this._mailServiceMock.Object
                                     }).Object;

    logger.OnActionException(...);

    this._mailServiceMock.Verify(
            msm => msm.SendEmailForThrownException(It.IsAny<string>(), It.IsAny<string>()),
            Times.Once);
}


问:
How to create Start menu items for all users when running installer with PrivilegesRequired=lowest as Administrator
Inno Setup documentation says the following:

{group}
      The path to the Start Menu folder, as selected by the user on Setup's Select Start Menu Folder wizard page. This folder is created under the All Users profile unless the user installing the application does not have administrative privileges, in which case it is created in the user's profile.*

When I use PrivilegesRequired=admin (i.e. the default), Start menu items are created for all users in C:\ProgramData\Microsoft\Windows\Start Menu\Programs.

When I use PrivilegesRequired=lowest, but run setup with right-click run-as-administrator, Start menu items are created for just the admin user in C:\Users\admin-user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs.  This happens even if the current user is an admin.

How can I make start menu items be for all users when using right-click elevation?  In this situation, Setup installs program files for all users in C:\Program Files\.  So I would like start menu items also to be for all users.

答:
You can use the (deprecated and now undocumented) value PrivilegesRequired=none to make Inno adapt to whether it is being run with or without admin privileges, including redirecting the Start Menu entries accordingly.

However the reason that this setting is deprecated is because the entire concept is a little silly.  Most applications should be designed to require admin privileges to install (since typically people who are non-admins are not supposed to install software).

If you do end up with an application installed both as an admin and as a regular user then you will have cases where certain users will see two copies of the application installed and will not know which one to use.  Furthermore the admin might upgrade the one they installed thinking that all users will see it, but meanwhile some users are still using the older version.

I strongly encourage you to abandon the idea of letting unprivileged users install your application and just stick with PrivilegesRequired=admin, or if you really want to allow that, then PrivilegesRequired=lowest.

If you do use PrivilegesRequired=lowest, then also use {userpf} in your DefaultDirName so that it doesn't install to Program Files if someone erroneously runs it as an admin.


答:
You may create a trigger for it

```<code>CREATE TRIGGER date_updated BEFORE UPDATE ON <your table name>
       FOR EACH ROW SET <old exp date column> = OLD.<expired date column>
</code>```

In PostgreSQL, you can use the RETURNING clause

```<code>UPDATE <table name> SET <column> = <value> RETURNING <column>
</code>```

Body:
I have a MySQL table that updates from an API daily, but now I want to track a specific field that has been updated from the API. I want to update the row with the current field(value) change and keep the old field(value) in another field.
Could somebody please point me in the right direction and what would be the best practice for this?

Table (original)

---------------------------------
|ID | Input Date | Expired Date |
---------------------------------
| 2 | 2017-05-17 | 2017-12-19   |
---------------------------------
| 3 | 2017-07-09 | 2018-05-19   |
---------------------------------

Table when updated (current)

---------------------------------
|ID | Input Date | Expired Date |
---------------------------------
| 2 | 2017-05-17 | 2018-05-28   |  <----- ID 2: Expired Date updated
---------------------------------
| 3 | 2017-07-09 | 2018-05-19   |
---------------------------------

Table updated and keeps old field value

------------------------------------------------
|ID | Input Date | Expired Date | Old Exp Date |
------------------------------------------------
| 2 | 2017-05-17 | 2018-05-28   | 2017-12-19   |
------------------------------------------------
| 3 | 2017-07-09 | 2018-05-19   |              |
------------------------------------------------

I hope this made sense a little, please help..Thank you so much:)

Body:
You may create a trigger for it

CREATE TRIGGER date_updated BEFORE UPDATE ON <your table name>
       FOR EACH ROW SET <old exp date column> = OLD.<expired date column>

In PostgreSQL, you can use the RETURNING clause

UPDATE <table name> SET <column> = <value> RETURNING <column>