问:
default values to hidden fields
I created a content type that uses a CheckBox that has a default value.  When I save documents of that content type the default value behaves as expected.  If I make that checkBox hidden and create a new document with the content type it is not assigning the default value.  When I look at the XML results from a search that returns all documents in that content type the document created with the hidden field on it doesn't even have a node for the hidden field.

Is there something special that I need to do to get the hidden field to take it's default value?

答: It's not exactly the answer of your question. But you can make it a normal (not hidden) column, and hide it from the forms with a simple JavaScript code. You can add a content editor Web part to embed the necessary JS code to the form.</p>

Title: default values to hidden fields


来源: stackexchange

问:
Weekly customer count in DAX
I have a customer dimension:

```<code>Dimcust

| Custnum | StartDate | EndDate |
</code>```

I want to make a new table, using DAX, that for every week in the last year counts the number of customers (distinct custnum) for each week (meaning that the startdate < week and enddate is null or enddate > week).

However I cant get this to work whatsoever.

What I've tried is the following:

```<code>Active Users = Calculate(COUNTROWS(filter(DimCustomer; DimCustomer[StartDate].[Date] > WeeklyKPI[Date];DimCustomer[StartDate].[Date] < WeeklyKPI[Date])))
</code>```

This gave the error:

```<code>A single value for column 'Date' in table 'WeeklyKPI' cannot be determined. This can happen when a measure formula refers to a column that contains many values without specifying an aggregation such as min, max, count, or sum to get a single result.
</code>```

Where WeeklyKPI[Date] is a date table with each date in the range I want. If this had worked I've would done the same, just with weeknumbers.

What I want:

```<code>Weeknumber | Number of customers
     1                13,430
     2                32,530
</code>```

答:
You are seeing the error because you tried to compare individual values (DimCustomer[StartDate].[Date]) with multiple (WeeklyKPI[Date]).

If WeeklyKPI[Date] has all days of the selected week, you could change your measure to the following:

```<code>Active Users = Calculate(COUNTROWS(filter(DimCustomer;
  DimCustomer[StartDate].[Date] > MIN(WeeklyKPI[Date]);
  DimCustomer[StartDate].[Date] < MAX(WeeklyKPI[Date]))))
</code>```

Another option is to create a table with week numbers, WeekNum(Num), and allow the user to select a single value. Your measure would then change to

```<code>Active Users = Calculate(COUNTROWS(filter(DimCustomer;
  WEEKNUM(DimCustomer[StartDate].[Date], 2) = FIRSTNONBLANK(WeekNum[Num]))))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Weekly customer count in DAX

Body:
I have a customer dimension:

Dimcust

| Custnum | StartDate | EndDate |

I want to make a new table, using DAX, that for every week in the last year counts the number of customers (distinct custnum) for each week (meaning that the startdate < week and enddate is null or enddate > week).

However I cant get this to work whatsoever.

What I've tried is the following:

Active Users = Calculate(COUNTROWS(filter(DimCustomer; DimCustomer[StartDate].[Date] > WeeklyKPI[Date];DimCustomer[StartDate].[Date] < WeeklyKPI[Date])))

This gave the error:

A single value for column 'Date' in table 'WeeklyKPI' cannot be determined. This can happen when a measure formula refers to a column that contains many values without specifying an aggregation such as min, max, count, or sum to get a single result.

Where WeeklyKPI[Date] is a date table with each date in the range I want. If this had worked I've would done the same, just with weeknumbers.

What I want:

Weeknumber | Number of customers
     1                13,430
     2                32,530

Body:
You are seeing the error because you tried to compare individual values (DimCustomer[StartDate].[Date]) with multiple (WeeklyKPI[Date]).

If WeeklyKPI[Date] has all days of the selected week, you could change your measure to the following:

Active Users = Calculate(COUNTROWS(filter(DimCustomer;
  DimCustomer[StartDate].[Date] > MIN(WeeklyKPI[Date]);
  DimCustomer[StartDate].[Date] < MAX(WeeklyKPI[Date]))))

Another option is to create a table with week numbers, WeekNum(Num), and allow the user to select a single value. Your measure would then change to

Active Users = Calculate(COUNTROWS(filter(DimCustomer;
  WEEKNUM(DimCustomer[StartDate].[Date], 2) = FIRSTNONBLANK(WeekNum[Num]))))


问:
Various errors while scanning for folders
Please do not mark as duplicate as I have looked at the other questions with this error and I still can't figure it out.

I am making a basic scanner that scans a directory given to it and it deletes all sub directories that are older than 90 days. Here is the code:

```<code>import os, sys
import time
import shutil
from  Tkinter import *
import Tkinter, Tkconstants, tkFileDialog

now = time.time()
home1 = os.path.join(os.environ["HOMEPATH"], "Desktop")
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

root = Tk()
root.withdraw()
path = tkFileDialog.askdirectory(initialdir=desktop, title="Select folder to scan from: ")
path = path.encode('utf-8')

for x in os.walk(path):
    for folders in x:
        while os.stat(folders).st_mtime < now - 90 * 86400:
            q = raw_input('Folder(s) found. NOTE: This will delete all directories or subdirectories in the folder. Do you want to remove?(y/n) ')
            if str(q) == "y" or str(q) == "Y":
                shutil.rmtree(path, ignore_errors=True)
                print 'Successfully deleted folder(s)'
            elif str(q) == "n" or str(q) == "N":
                print 'Folders not deleted.'
                sys.exit()
        else:
            print 'No folder(s) over 90 days'
</code>```

Here is the full traceback:

```<code>Traceback (most recent call last):
File "C:/Users/Bill/Desktop/limitScanner/scanner.py", line 20, in <module>
while os.stat(folders).st_mtime < now - 90 * 86400:
TypeError: coercing to Unicode: need string or buffer, list found
</code>```

Edit: When I use my program on a folder with multiple sub folders such as the desktop folder, it gives me the following error: WindowsError: [Error 2] The system cannot find the file specified and the name of the first folder.

I am using python 2.7.13. Can anyone please help? Any help is widely appreciated.

答:
os.walk returns a 3-tuple (dirpath, dirnames, filenames). Your current approach iterates on the 3-tuple which in the second iteration gives a list of directory names dirnames.

However, you are only interested in the dirnames:

```<code>for _, dirs, _ in os.walk(path):
    for folder in dirs:
        ...
</code>```

Body:
Please do not mark as duplicate as I have looked at the other questions with this error and I still can't figure it out.

I am making a basic scanner that scans a directory given to it and it deletes all sub directories that are older than 90 days. Here is the code:

import os, sys
import time
import shutil
from  Tkinter import *
import Tkinter, Tkconstants, tkFileDialog

now = time.time()
home1 = os.path.join(os.environ["HOMEPATH"], "Desktop")
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

root = Tk()
root.withdraw()
path = tkFileDialog.askdirectory(initialdir=desktop, title="Select folder to scan from: ")
path = path.encode('utf-8')

for x in os.walk(path):
    for folders in x:
        while os.stat(folders).st_mtime < now - 90 * 86400:
            q = raw_input('Folder(s) found. NOTE: This will delete all directories or subdirectories in the folder. Do you want to remove?(y/n) ')
            if str(q) == "y" or str(q) == "Y":
                shutil.rmtree(path, ignore_errors=True)
                print 'Successfully deleted folder(s)'
            elif str(q) == "n" or str(q) == "N":
                print 'Folders not deleted.'
                sys.exit()
        else:
            print 'No folder(s) over 90 days'

Here is the full traceback:

Traceback (most recent call last):
File "C:/Users/Bill/Desktop/limitScanner/scanner.py", line 20, in <module>
while os.stat(folders).st_mtime < now - 90 * 86400:
TypeError: coercing to Unicode: need string or buffer, list found

Edit: When I use my program on a folder with multiple sub folders such as the desktop folder, it gives me the following error: WindowsError: [Error 2] The system cannot find the file specified and the name of the first folder.

I am using python 2.7.13. Can anyone please help? Any help is widely appreciated.

Body:
os.walk returns a 3-tuple (dirpath, dirnames, filenames). Your current approach iterates on the 3-tuple which in the second iteration gives a list of directory names dirnames.

However, you are only interested in the dirnames:

for _, dirs, _ in os.walk(path):
    for folder in dirs:
        ...


问:
How to use angular2-data-table
Can't find any tutorial of how to use angular2-data-table library is here: https://github.com/swimlane/angular2-data-table

The documentation seems to be lacking simple examples.

Can any one give me a simple example of using datatable in angular2

答:
These is a solution :
Implementing data table on easier way

https://www.npmjs.com/package/angular2-datatable

Just change your data, replace
[mfData]="Your responsepacket"

Here i am sharing an example as well.

Data:

```<code>{
    "responsecode": "200",
    "status": "Success",
    "ResponseMessage": "Success",
    "responsepacket": [{
            "member_id": 4,
            "member_name": "mehulkachhwaya",
            "member_contactno": "9977828800",
            "member_dob": "/Date(804623400000)/",
            "member_gender": "Male",
            "workouttype_id": "GYM",
            "member_imagename": "user.jpg",
            "member_imagepath": "user.jpg",
            "joiningdate": "/Date(-62135596800000)/",
            "address": "jail  road",
            "name_complaint": "6/6/2017 6:30:26 PM",
            "contact_complaint": null,
            "msg_complaint": "unlocked",
            "status": null
        },

        {
            "member_id": 7011,
            "member_name": "rakeshchatur",
            "member_contactno": "0000000000",
            "member_dob": "/Date(1498069800000)/",
            "member_gender": "Female",
            "workouttype_id": "GYM+CARDIO",
            "member_imagename": "Today work.png",
            "member_imagepath": "work.png",
            "joiningdate": "/Date(-62135596800000)/",
            "address": "kachhawayamehul@gmail.com",
            "name_complaint": "6/21/2017 7:40:49 PM",
            "contact_complaint": null,
            "msg_complaint": "unlocked",
            "status": null
        },
        {
            "member_id": 7012,
            "member_name": "sadassa",
            "member_contactno": "0000000000",
            "member_dob": "/Date(1498156200000)/",
            "member_gender": "Male",
            "workouttype_id": "GYM",
            "member_imagename": "logo.png",
            "member_imagepath": "hi.png",
            "joiningdate": "/Date(-62135596800000)/",
            "address": "Jail Road",
            "name_complaint": "6/21/2017 7:45:11 PM",
            "contact_complaint": null,
            "msg_complaint": "unlocked",
            "status": null
        },
        {
            "member_id": 7013,
            "member_name": "sadassa",
            "member_contactno": "0000000000",
            "member_dob": "/Date(1498156200000)/",
            "member_gender": "Male",
            "workouttype_id": "GYM",
            "member_imagename": "logo.png",
            "member_imagepath": "hi.png",
            "joiningdate": "/Date(-62135596800000)/",
            "address": "Jail Road",
            "name_complaint": "6/21/2017 7:45:13 PM",
            "contact_complaint": null,
            "msg_complaint": "unlocked",
            "status": null
        },
        {
            "member_id": 7014,
            "member_name": "oyyds",
            "member_contactno": "9090909090",
            "member_dob": "/Date(1497897000000)/",
            "member_gender": "Male",
            "workouttype_id": "GYM",
            "member_imagename": "register1.png",
            "member_imagepath": "hi.png",
            "joiningdate": "/Date(-62135596800000)/",
            "address": "Jail Road",
            "name_complaint": "6/21/2017 7:54:04 PM",
            "contact_complaint": null,
            "msg_complaint": "unlocked",
            "status": null
        }
    ]
}
</code>```

And consume it with in your template:

```<code>   <div>

                                    <table class="pagination" cellspacing="0" [mfData]="responseformate.responsepacket" #mf="mfDataTable" [mfRowsOnPage]="5"
                                    >

                                        <thead>
                                            <tr class="tittle">

                                                <th><span> <mfDefaultSorter by="member_name">User Name</mfDefaultSorter></span> </th>
                                                <th><span>Contact No</span> </th>
                                                 <th><span>WorkOut Type</span> </th>
                                                  <th><span>Image</span> </th>
                                                    <th><span>Joining Date</span> </th>
                                                <th><span>Action</span> </th>

                                            </tr>
                                        </thead>
                                        <tbody id="UserList"  >
                                           <tr *ngFor=" let todo of mf.data let i=index " >

                                                <td>{{todo.member_name}}</td>
                                                <td>{{todo.member_contactno}}</td>
                                                 <td>{{todo.workouttype_id}}</td>

                                                  <td style="width:125 px"><img class="img-circle" src={{todo.member_imagepath}} alt="Smiley face"></td>
                                                  <td>{{todo.name_complaint}}</td>

                  <td style="width:70px;"><a href="javascript:;"  title="Edit User Information">
                 <i class="fa fa-pencil fa-fw" aria-hidden="true" style="color: #1a9ef5;padding-right: 0px"></i></a>
                 <a href="javascript:;" title="UnBlock this user">
                 <i class="fa fa-expeditedssl" aria-hidden="true" style="color: black;"></i></a>
                <a href="javascript:;" title="Delete User" (click)=delete(todo.member_id)>
                                <i class="fa fa-trash-o" aria-hidden="true" style="color: red;"></i></a></td>

                                           </tr>

                                        </tbody>
                                            <tfoot>
                                                <tr>
                                                   <td colspan="4">
                                    <mfBootstrapPaginator [rowsOnPageSet]="[5,10,25]"></mfBootstrapPaginator>

                                                    </td>
                                                </tr>
                                             </tfoot>
                                    </table>
                                    <!--JavaScript se ayega data-->

                                    <div class="referenceRequestError" style="text-align: center; font-size: 18px; font-weight: bold;">
                                        <!--No Request Recived-->
                                    </div>

                                </div>
</code>```

Title: How to use angular2-data-table

Body:
These is a solution :
Implementing data table on easier way

https://www.npmjs.com/package/angular2-datatable

Just change your data, replace
[mfData]="Your responsepacket"

Here i am sharing an example as well.

Data:

{
    "responsecode": "200",
    "status": "Success",
    "ResponseMessage": "Success",
    "responsepacket": [{
            "member_id": 4,
            "member_name": "mehulkachhwaya",
            "member_contactno": "9977828800",
            "member_dob": "/Date(804623400000)/",
            "member_gender": "Male",
            "workouttype_id": "GYM",
            "member_imagename": "user.jpg",
            "member_imagepath": "user.jpg",
            "joiningdate": "/Date(-62135596800000)/",
            "address": "jail  road",
            "name_complaint": "6/6/2017 6:30:26 PM",
            "contact_complaint": null,
            "msg_complaint": "unlocked",
            "status": null
        },

        {
            "member_id": 7011,
            "member_name": "rakeshchatur",
            "member_contactno": "0000000000",
            "member_dob": "/Date(1498069800000)/",
            "member_gender": "Female",
            "workouttype_id": "GYM+CARDIO",
            "member_imagename": "Today work.png",
            "member_imagepath": "work.png",
            "joiningdate": "/Date(-62135596800000)/",
            "address": "kachhawayamehul@gmail.com",
            "name_complaint": "6/21/2017 7:40:49 PM",
            "contact_complaint": null,
            "msg_complaint": "unlocked",
            "status": null
        },
        {
            "member_id": 7012,
            "member_name": "sadassa",
            "member_contactno": "0000000000",
            "member_dob": "/Date(1498156200000)/",
            "member_gender": "Male",
            "workouttype_id": "GYM",
            "member_imagename": "logo.png",
            "member_imagepath": "hi.png",
            "joiningdate": "/Date(-62135596800000)/",
            "address": "Jail Road",
            "name_complaint": "6/21/2017 7:45:11 PM",
            "contact_complaint": null,
            "msg_complaint": "unlocked",
            "status": null
        },
        {
            "member_id": 7013,
            "member_name": "sadassa",
            "member_contactno": "0000000000",
            "member_dob": "/Date(1498156200000)/",
            "member_gender": "Male",
            "workouttype_id": "GYM",
            "member_imagename": "logo.png",
            "member_imagepath": "hi.png",
            "joiningdate": "/Date(-62135596800000)/",
            "address": "Jail Road",
            "name_complaint": "6/21/2017 7:45:13 PM",
            "contact_complaint": null,
            "msg_complaint": "unlocked",
            "status": null
        },
        {
            "member_id": 7014,
            "member_name": "oyyds",
            "member_contactno": "9090909090",
            "member_dob": "/Date(1497897000000)/",
            "member_gender": "Male",
            "workouttype_id": "GYM",
            "member_imagename": "register1.png",
            "member_imagepath": "hi.png",
            "joiningdate": "/Date(-62135596800000)/",
            "address": "Jail Road",
            "name_complaint": "6/21/2017 7:54:04 PM",
            "contact_complaint": null,
            "msg_complaint": "unlocked",
            "status": null
        }
    ]
}

And consume it with in your template:

   <div>

                                    <table class="pagination" cellspacing="0" [mfData]="responseformate.responsepacket" #mf="mfDataTable" [mfRowsOnPage]="5"
                                    >

                                        <thead>
                                            <tr class="tittle">

                                                <th><span> <mfDefaultSorter by="member_name">User Name</mfDefaultSorter></span> </th>
                                                <th><span>Contact No</span> </th>
                                                 <th><span>WorkOut Type</span> </th>
                                                  <th><span>Image</span> </th>
                                                    <th><span>Joining Date</span> </th>
                                                <th><span>Action</span> </th>

                                            </tr>
                                        </thead>
                                        <tbody id="UserList"  >
                                           <tr *ngFor=" let todo of mf.data let i=index " >

                                                <td>{{todo.member_name}}</td>
                                                <td>{{todo.member_contactno}}</td>
                                                 <td>{{todo.workouttype_id}}</td>

                                                  <td style="width:125 px"><img class="img-circle" src={{todo.member_imagepath}} alt="Smiley face"></td>
                                                  <td>{{todo.name_complaint}}</td>

                  <td style="width:70px;"><a href="javascript:;"  title="Edit User Information">
                 <i class="fa fa-pencil fa-fw" aria-hidden="true" style="color: #1a9ef5;padding-right: 0px"></i></a>&nbsp;
                 <a href="javascript:;" title="UnBlock this user">
                 <i class="fa fa-expeditedssl" aria-hidden="true" style="color: black;"></i></a>&nbsp;
                <a href="javascript:;" title="Delete User" (click)=delete(todo.member_id)>
                                <i class="fa fa-trash-o" aria-hidden="true" style="color: red;"></i></a></td>

                                           </tr>

                                        </tbody>
                                            <tfoot>
                                                <tr>
                                                   <td colspan="4">
                                    <mfBootstrapPaginator [rowsOnPageSet]="[5,10,25]"></mfBootstrapPaginator>

                                                    </td>
                                                </tr>
                                             </tfoot>
                                    </table>
                                    <!--JavaScript se ayega data-->

                                    <div class="referenceRequestError" style="text-align: center; font-size: 18px; font-weight: bold;">
                                        <!--No Request Recived-->
                                    </div>

                                </div>

ContentLicense: CC BY-SA 4.0


问:
Group by Help in R and Keeping all columns
I have a large dataset with 4161512 rows and 10 columns. I am trying to group my dataset based on two columns which are character data type.I could make the grouping but I get only three rows as output, I looking for other 7 columns also which are related to grouped by columns.

Below code which gives me only the three columns (Manufacture, Name, Pay) but I also want other 7 column so that I can have 10 columns in my data table including the grouped columns.

```<code>Newname = Dt %>%
  group_by(Manufacturer,Name) %>%
  summarise(Payments=sum(Payments))
</code>```

Please help Thank you in advance!

答:
Use mutate instead of summarise after grouping the data

```<code>Newname = Dt %>%
  group_by(Manufacturer,Name) %>%
  mutate(PaymentsSum = sum(Payments))
</code>```

Body:
I have a large dataset with 4161512 rows and 10 columns. I am trying to group my dataset based on two columns which are character data type.I could make the grouping but I get only three rows as output, I looking for other 7 columns also which are related to grouped by columns.

Below code which gives me only the three columns (Manufacture, Name, Pay) but I also want other 7 column so that I can have 10 columns in my data table including the grouped columns.

Newname = Dt %>%
  group_by(Manufacturer,Name) %>%
  summarise(Payments=sum(Payments))

Please help Thank you in advance!

Body:
Use mutate instead of summarise after grouping the data

Newname = Dt %>%
  group_by(Manufacturer,Name) %>%
  mutate(PaymentsSum = sum(Payments))


问:
How to debug a "String index out of range" error in a Java program?
```<code>["Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 2
    at java.lang.String.charAt(Unknown Source)
    at Haupt.main(Haupt.java:21)"]
</code>```

And here is my code. Why did I get this error?

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

public class Haupt {

    public static void main(String[] args) {
        String Wort="";
        String WortCpy="";
        String WortRev="";
        int i=0;
        Scanner scan = new Scanner(System.in);

        System.out.print("Geben Sie ein Wort ein : "); //Ausgabe
        Wort = scan.nextLine(); //Eingabe
        scan.close();
        for(i=0;i < Wort.length();i++) {
            WortCpy= WortCpy +  Wort.charAt(i); //Speichert jeden Buchstaben einzeln in Wortcpy ab
        }
        for(i=Wort.length();i>=0;i--) {
            WortRev = WortRev +  Wort.charAt(i);
        }

        System.out.println("Wort : " + Wort);
        System.out.println("Wort Kopiert : " + WortCpy);
        System.out.println("Wort umgedreht : " + WortRev);

    }

}
</code>```

答:
Where you are looping from wort.length() through to 0 (and vice versa) you need to use wort.length() - 1.

This is because the strings char array is 0 indexed (meaning that the first char is at index 0 and the last char is at length - 1). So by this logic, in your code, when the loop hits the point where i = wort.length() then you'll get array out of bounds error.

Body:
["Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 2
    at java.lang.String.charAt(Unknown Source)
    at Haupt.main(Haupt.java:21)"]

And here is my code. Why did I get this error?

import java.util.Scanner;

public class Haupt {

    public static void main(String[] args) {
        String Wort="";
        String WortCpy="";
        String WortRev="";
        int i=0;
        Scanner scan = new Scanner(System.in);

        System.out.print("Geben Sie ein Wort ein : "); //Ausgabe
        Wort = scan.nextLine(); //Eingabe
        scan.close();
        for(i=0;i < Wort.length();i++) {
            WortCpy= WortCpy +  Wort.charAt(i); //Speichert jeden Buchstaben einzeln in Wortcpy ab
        }
        for(i=Wort.length();i>=0;i--) {
            WortRev = WortRev +  Wort.charAt(i);
        }

        System.out.println("Wort : " + Wort);
        System.out.println("Wort Kopiert : " + WortCpy);
        System.out.println("Wort umgedreht : " + WortRev);

    }

}


问:
Single vs. Dual Sockets In Network Programming
The question is about network programming, more precisely servers. Let's suppose there is a server which handles a lot of connections, and thus has a listening socket. There obviously exists a single instance of such a socket, that's clear. Now I've seen designs which use (a)one socket for every connection, both for incoming and outgoing data, and (b)two sockets, one for the incoming data, one for the outgoing data. What makes one or the other design more preferrable? What are the possible reasons / usecases for these two designs?
The programs I was referring to were actually instant messengers (two of them), but this theoretically applies to any multiple-connection server (any server, then.)

Hope this question is not too generic, I don't know a lot about network programming at the moment, so asking this. Rapid Googling didn't help either.

答: TCP and UDP Sockets are full duplex. There is no reason whatsoever to use separate sockets for input from and output to the same client. It is just wastefully using up kernel resources at double the rate.</p>

ContentLicense: CC BY-SA 2.5


问:
Returns simplify as null
So, First of all, I'm a beginner, and 6 months of experience in C# at school. I can do it the other way, but I want to know more ways to do stuffs so..
And I need help about this. What happens is, when i run the program everything goes okay until private void Add(), some error comes up and says that Simplify is null? Thanks in advance.

```<code>using System;

namespace test1
{
 class Details
 {
    int NumberSimplify;
    double Solution;

    private void Ask()
    {
        Console.Write("Would you like to Add or Substract (1 - Add, 2 - Substract) -► ");
        int Opt = int.Parse(Console.ReadLine());

        switch(Opt)
        {
            case 1:
                Console.Write("\nHow many numbers would you like to add? -► ");
                NumberSimplify = int.Parse(Console.ReadLine());
                break;

            case 2:
                break;
        }
    }

    public void DisplayResult(double[] Simplify)
    {
        Console.Write("Result from Addition -► ", Add(Simplify));
    }

    private void AddDetails()
    {
        Ask();
        double[] Simplify = new double[NumberSimplify];
        Console.WriteLine();
        for (int i = 0; i < Simplify.Length; i++)
        {
            Console.Write("Number {0} -► ", i + 1);
            Simplify[i] = double.Parse(Console.ReadLine());
        }
    }

    private double Add(double[] Simplify)
    {
        AddDetails();
        for (int i = 0; i < Simplify.Length; i++)
        {
            Solution = Simplify[i] + Simplify[i + 1];
        }
        return Solution;
    }

}

class Execute
{
    public static double[] Simplify { get; private set; }

    static void Main(string[] args)
    {

        Details AddOrSub = new Details();
        AddOrSub.DisplayResult(Simplify);
        Console.ReadLine();

    }
}
</code>```

}

答:
Simplify is indeed null....

```<code>public static double[] Simplify { get; private set; }
</code>```

You need to initialize arrays... so this should be more like;

```<code>public static double[] Simplify { get; private set; } = new double[someNumberOfElements]
</code>```

But as pointed out in the comments, you dont even use this initial version of the variable (It is overwritten anyway in your next methods) so consider removing it altogether and re-visiting your control flow...

Title: Returns simplify as null

Body:
So, First of all, I'm a beginner, and 6 months of experience in C# at school. I can do it the other way, but I want to know more ways to do stuffs so..
And I need help about this. What happens is, when i run the program everything goes okay until private void Add(), some error comes up and says that Simplify is null? Thanks in advance.

using System;

namespace test1
{
 class Details
 {
    int NumberSimplify;
    double Solution;

    private void Ask()
    {
        Console.Write("Would you like to Add or Substract (1 - Add, 2 - Substract) -► ");
        int Opt = int.Parse(Console.ReadLine());

        switch(Opt)
        {
            case 1:
                Console.Write("\nHow many numbers would you like to add? -► ");
                NumberSimplify = int.Parse(Console.ReadLine());
                break;

            case 2:
                break;
        }
    }

    public void DisplayResult(double[] Simplify)
    {
        Console.Write("Result from Addition -► ", Add(Simplify));
    }

    private void AddDetails()
    {
        Ask();
        double[] Simplify = new double[NumberSimplify];
        Console.WriteLine();
        for (int i = 0; i < Simplify.Length; i++)
        {
            Console.Write("Number {0} -► ", i + 1);
            Simplify[i] = double.Parse(Console.ReadLine());
        }
    }

    private double Add(double[] Simplify)
    {
        AddDetails();
        for (int i = 0; i < Simplify.Length; i++)
        {
            Solution = Simplify[i] + Simplify[i + 1];
        }
        return Solution;
    }

}

class Execute
{
    public static double[] Simplify { get; private set; }

    static void Main(string[] args)
    {

        Details AddOrSub = new Details();
        AddOrSub.DisplayResult(Simplify);
        Console.ReadLine();

    }
}

}

Body:
Simplify is indeed null....

public static double[] Simplify { get; private set; }

You need to initialize arrays... so this should be more like;

public static double[] Simplify { get; private set; } = new double[someNumberOfElements]

But as pointed out in the comments, you dont even use this initial version of the variable (It is overwritten anyway in your next methods) so consider removing it altogether and re-visiting your control flow...


问:
maven repository sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
I have the fragment of pom.xml which tries to resolve the fitbit dependency:

```<code><repositories>
        <repository>
            <name>FitBit GitHub Repo</name>
            <id>fitbit4j</id>
            <url>https://nexus.vanntett.net/content/repositories/fitbit/</url>
        </repository>
    </repositories>
</code>```

I am getting the below error:

```<code>Failed to collect dependencies at com.fitbit:fitbit4j:jar:1.0.26: Failed to read artifact descriptor for com.fitbit:fitbit4j:jar:1.0.26: Could not transfer artifact com.fitbit:fitbit4j:pom:1.0.26 from/to fitbit4j (https://nexus.vanntett.net/content/repositories/fitbit/): sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target -> [Help 1]
</code>```

I used these parameters in eclipse:
    -Dmaven.wagon.http.ssl.insecure=true -   Dmaven.wagon.http.ssl.allowall=true

which didn't work.

Please help.

Thanks

答:
Check that run keytool -import.. command from jre which exists uder jdk.
like this.

1.Open cmd as admin...

go to path: C:\Program Files\Java\jdk1.8.0_65\bin>

run bellow command.

keytool -import -noprompt -trustcacerts -alias certPen -file  D:\certificates\ca-cert.pem -keystore "C:\Program Files\Java\jdk1.8.0_60\jre\lib\security\cacerts"

and if u facing problem of file not found then set your all permission from
Right click on cacerts → choose properties → select Securit tab → Allow all permissions to all the Group and user names.

Body:
I have the fragment of pom.xml which tries to resolve the fitbit dependency:

<repositories>
        <repository>
            <name>FitBit GitHub Repo</name>
            <id>fitbit4j</id>
            <url>https://nexus.vanntett.net/content/repositories/fitbit/</url>
        </repository>
    </repositories>

I am getting the below error:

Failed to collect dependencies at com.fitbit:fitbit4j:jar:1.0.26: Failed to read artifact descriptor for com.fitbit:fitbit4j:jar:1.0.26: Could not transfer artifact com.fitbit:fitbit4j:pom:1.0.26 from/to fitbit4j (https://nexus.vanntett.net/content/repositories/fitbit/): sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target -> [Help 1]

I used these parameters in eclipse:
    -Dmaven.wagon.http.ssl.insecure=true -   Dmaven.wagon.http.ssl.allowall=true

which didn't work.

Please help.

Thanks


问:
TypeScript Sort Object by Object in Array
Does anyone know how sort Array with Person by value TaskTime in tasks?

```<code>export class Person {
    Id: string;
    Email: string;
    FirstName: string;
    LastName: string;
    Presence: boolean;
    RegisterTime: Date;
    tasks: Array<Task>
}

export class Task {
    TaskName: string;
    DoneTask: boolean;
    TaskTime: number;
}
</code>```

Thanks for help

答:
Try to follow such way to sort your array. The sample code below will sort the array in descending order by blockId field. </p>

```<code>this.itemList.sort((left, right): number => {
  if (left.blockId < right.blockId) return 1;
  if (left.blockId > right.blockId) return -1;
  return 0;
});
</code>```

Body:
Does anyone know how sort Array with Person by value TaskTime in tasks?

export class Person {
    Id: string;
    Email: string;
    FirstName: string;
    LastName: string;
    Presence: boolean;
    RegisterTime: Date;
    tasks: Array<Task>
}

export class Task {
    TaskName: string;
    DoneTask: boolean;
    TaskTime: number;
}

Thanks for help

Body:
Try to follow such way to sort your array. The sample code below will sort the array in descending order by blockId field.

this.itemList.sort((left, right): number => {
  if (left.blockId < right.blockId) return 1;
  if (left.blockId > right.blockId) return -1;
  return 0;
});


问:
UIView - Center alignment all the contents of UIView?
How to center alignment all the contents of view. When i am rotating iPad contents are not align center it self how to resolve this problem??

Thanks!!!

答:
You should change programmatic-ally the contents' frame  for both Landscape and portrait modes.
You can try this as:</p>

```<code>- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight){
        // set contents' frame for landscape
    }

    else {
        // set contents' frame for portrait

    }

    return YES;
}
</code>```

Body:
You should change programmatic-ally the contents' frame  for both Landscape and portrait modes.
You can try this as:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight){
        // set contents' frame for landscape
    }

    else {
        // set contents' frame for portrait

    }

    return YES;
}


问:
IOS/Objective-C:Add another variable to a mutableArray
I have a simple array of strings such as the following:

```<code>myArray *NSArray = [NSArray arrayWithObjects: @"chevy", @"ford", @"toyota", nil];
</code>```

I want to add another dimension to the array such as @"1",@"2",@"3" in order to keep track of the order.

Is there a simple way to do this?

Edit

I found answer here.  Create 2nd array and employ loop:

```<code>//For your 2D array
NSMutableArray *secondArray = [[NSMutableArray alloc] initWithCapacity:[homePlayersArray count]];

//populate as required
for(int i=0;i<[homePlayersArray count];i++){
    NSArray *tempArray = [[NSArray alloc] initWithObjects:[homePlayersArray objectAtIndex:i],[NSNumber numberWithInt:0], nil];
    [secondArray addObject:tempArray];
}
</code>```

答:
Are those supposed to key-value pairs? If so, better use NSDictionary:  </p>

```<code>NSDictionary *dictionary = @{ @"1" : @"chevy", @"2" : @"ford", @"3" : @"toyota"};
</code>```

Body:
I have a simple array of strings such as the following:

myArray *NSArray = [NSArray arrayWithObjects: @"chevy", @"ford", @"toyota", nil];

I want to add another dimension to the array such as @"1",@"2",@"3" in order to keep track of the order.

Is there a simple way to do this?

Edit

I found answer here.  Create 2nd array and employ loop:

//For your 2D array
NSMutableArray *secondArray = [[NSMutableArray alloc] initWithCapacity:[homePlayersArray count]];

//populate as required
for(int i=0;i<[homePlayersArray count];i++){
    NSArray *tempArray = [[NSArray alloc] initWithObjects:[homePlayersArray objectAtIndex:i],[NSNumber numberWithInt:0], nil];
    [secondArray addObject:tempArray];
}

Body:
Are those supposed to key-value pairs? If so, better use NSDictionary:

NSDictionary *dictionary = @{ @"1" : @"chevy", @"2" : @"ford", @"3" : @"toyota"};


问:
Querying MSSQL server 2012 from a Raspberry Pi 3 using Python, FreeTDS and pyodbc
I am trying to query MSSQL server 2012 using Python as my scripting language on a raspberry Pi3.

I have the need to create an application that will query MSSQL server and return some values that need to be displayed on a H.M.I. I chose the Raspberry Pi platform to develop this solution using Python as the programming language. I created the script using PyCharm on a Windows 7 PC and all worked well. When I moved it to the Raspberry Platform it didn't work.

I am using pyODBC to do the connecting and querying and FreeTDS as the driver. I used the following procedure to set this up:

```<code> sudo apt-get install freetds-dev freetds-bin unixodbc-dev tdsodbc
 pip3 install pyODBC
</code>```

Configured the /etc/freetds.conf file as follows

```<code> [NAME]
 host = ipAddress
 port = 1433
 tds version = 7.4
 instance = dbInstanceName
</code>```

I then went to the command line and tested the connection with: tsql -S NAME -U username. The command line then prompts with Password: so I typed the password in and I got the following:

```<code> locale is "enGB.UTF-8"
 locale charset is "UTF-8"
 using default charset "UTF-8"
 1>
</code>```

As there are no errors present I can only assume that this has worked?

I then set up the /etc/odbcinst.ini file as follows:

```<code> [FreeTDS]
 Driver = /usr/lib/arm-linux-gnueabihf/odbc/libtdsodbc.so
</code>```

I then setup the  /etc/odbc.ini file as follows:

```<code> [NAME1]
 Driver = /usr/lib/arm-linux-gnueabihf/odbc/libtdsodbc.so
 Description = MSSQL Server
 Trace = No
 Server = ipAddress
 Database = dbName
 Port = 1433
 TDS_Version = 7.4
</code>```

I then tested this with the isql function in the command line: isql NAME1 user password and I got the following prompt:

```<code>+-------------------------------------------------+
| Connected!
|
| sql-statement
| help [tablename]
| quit
|
+-------------------------------------------------+

SQL>
</code>```

so I typed in select getDate() and the date and time returned.

However within Python I still can't get a connection, I typed the following into the interpreter:

```<code>import pyodbc

conn = pyodbc.connect('DRIVER=FreeTDS;SERVER=NAME;DATABASE=dbName;UID=user;PWD=password')
</code>```

Then when I type this cu = conn.cursor() I get an error:

```<code>AttributeError: 'NoneType' object has no attribute cursor
</code>```

答:
The problem is with your connection string. Here's a full connection string example for FreeTDS:

```<code>conn = pyodbc.connect(
    'DRIVER={FreeTDS};SERVER=yourfqdn.com;PORT=1433;DATABASE=your_db;UID=your_username;PWD=your_pw;TDS_Version=7.4;'
)
</code>```

Try putting {FreeTDS} in braces and adding the TDS_Version explicitly. I also choose to use the FQDN in my Python connection strings and set username / password as environment variables to keep configuration in one less place.

Body:
I am trying to query MSSQL server 2012 using Python as my scripting language on a raspberry Pi3.

I have the need to create an application that will query MSSQL server and return some values that need to be displayed on a H.M.I. I chose the Raspberry Pi platform to develop this solution using Python as the programming language. I created the script using PyCharm on a Windows 7 PC and all worked well. When I moved it to the Raspberry Platform it didn't work.

I am using pyODBC to do the connecting and querying and FreeTDS as the driver. I used the following procedure to set this up:

 sudo apt-get install freetds-dev freetds-bin unixodbc-dev tdsodbc
 pip3 install pyODBC

Configured the /etc/freetds.conf file as follows

 [NAME]
 host = ipAddress
 port = 1433
 tds version = 7.4
 instance = dbInstanceName

I then went to the command line and tested the connection with: tsql -S NAME -U username. The command line then prompts with Password: so I typed the password in and I got the following:

 locale is "enGB.UTF-8"
 locale charset is "UTF-8"
 using default charset "UTF-8"
 1>

As there are no errors present I can only assume that this has worked?

I then set up the /etc/odbcinst.ini file as follows:

 [FreeTDS]
 Driver = /usr/lib/arm-linux-gnueabihf/odbc/libtdsodbc.so

I then setup the  /etc/odbc.ini file as follows:

 [NAME1]
 Driver = /usr/lib/arm-linux-gnueabihf/odbc/libtdsodbc.so
 Description = MSSQL Server
 Trace = No
 Server = ipAddress
 Database = dbName
 Port = 1433
 TDS_Version = 7.4

I then tested this with the isql function in the command line: isql NAME1 user password and I got the following prompt:

+-------------------------------------------------+
| Connected!
|
| sql-statement
| help [tablename]
| quit
|
+-------------------------------------------------+

SQL>

so I typed in select getDate() and the date and time returned.

However within Python I still can't get a connection, I typed the following into the interpreter:

import pyodbc

conn = pyodbc.connect('DRIVER=FreeTDS;SERVER=NAME;DATABASE=dbName;UID=user;PWD=password')

Then when I type this cu = conn.cursor() I get an error:

AttributeError: 'NoneType' object has no attribute cursor

Body:
The problem is with your connection string. Here's a full connection string example for FreeTDS:

conn = pyodbc.connect(
    'DRIVER={FreeTDS};SERVER=yourfqdn.com;PORT=1433;DATABASE=your_db;UID=your_username;PWD=your_pw;TDS_Version=7.4;'
)

Try putting {FreeTDS} in braces and adding the TDS_Version explicitly. I also choose to use the FQDN in my Python connection strings and set username / password as environment variables to keep configuration in one less place.


问:
Android Firebase Push notification not working when application is killed
I have created android application to receive push notification from server but it is not working.

When app is in foreground, it works perfectly. But when we force close app from system tray it does not work.

Below is my json code which I send to FCM.

```<code>{"to":"\/topics\/global","data":{"title":"Title","body":"Body"}}
</code>```

Below is my android function

```<code>public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.d("Msg", "Message received ["+remoteMessage+"]");

        Map<String, String> data = remoteMessage.getData();

        DatabaseHandler db = new DatabaseHandler(getApplicationContext());
        db.addData(data.get("body"));

        Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
        resultIntent.putExtra("message", data.get("body"));

        showNotificationMessage(getApplicationContext(), data.get("title"), data.get("body"), "", resultIntent);
    }
</code>```

Below is code to show notification.

```<code>private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
    }
</code>```

I can not find any problem, can any one please help me.

Thank you very much in advance.

Edit :

I have solved my problem by changing phone, in samsung device code is working fine but its problem with MI device itself.

I have also got solution for MI devices, use below steps to enable auto start that application.

Go to settings --> permissions --> autostart. From there, pick the apps you want to receive notifications, and toggle the switch to turn it on.

答:
As per the doc there are two possibilities when notification arrived.

Application is in foreground.

You will get notify in onMessageReceived, and you can get data in this method. You need to generate local notification in system tray.

Handle Notification

You have done this code as mentioned in question.

Application is in background.

You get notification in system tray. You don't need to generate notification here. You will get data in Intent of launcher Activity.

Handle Notification

Here is code of launcher activity

```<code>@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        if (intent == null || intent.getExtras() == null) {
            // your code to handle if there is no notification
        } else {
            // handle notification
            String body = intent.getStringExtra("body");
            String title = intent.getStringExtra("title");
            //TODO your code to open activity as per notification
        }
    }
</code>```

I have done this, and its works for me.

Body:
I have created android application to receive push notification from server but it is not working.

When app is in foreground, it works perfectly. But when we force close app from system tray it does not work.

Below is my json code which I send to FCM.

{"to":"\/topics\/global","data":{"title":"Title","body":"Body"}}

Below is my android function

public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.d("Msg", "Message received ["+remoteMessage+"]");

        Map<String, String> data = remoteMessage.getData();

        DatabaseHandler db = new DatabaseHandler(getApplicationContext());
        db.addData(data.get("body"));

        Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
        resultIntent.putExtra("message", data.get("body"));

        showNotificationMessage(getApplicationContext(), data.get("title"), data.get("body"), "", resultIntent);
    }

Below is code to show notification.

private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
    }

I can not find any problem, can any one please help me.

Thank you very much in advance.

Edit :

I have solved my problem by changing phone, in samsung device code is working fine but its problem with MI device itself.

I have also got solution for MI devices, use below steps to enable auto start that application.

Go to settings --> permissions --> autostart. From there, pick the apps you want to receive notifications, and toggle the switch to turn it on.

Body:
As per the doc there are two possibilities when notification arrived.

Application is in foreground.

You will get notify in onMessageReceived, and you can get data in this method. You need to generate local notification in system tray.

Handle Notification

You have done this code as mentioned in question.

Application is in background.

You get notification in system tray. You don't need to generate notification here. You will get data in Intent of launcher Activity.

Handle Notification

Here is code of launcher activity

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        if (intent == null || intent.getExtras() == null) {
            // your code to handle if there is no notification
        } else {
            // handle notification
            String body = intent.getStringExtra("body");
            String title = intent.getStringExtra("title");
            //TODO your code to open activity as per notification
        }
    }

I have done this, and its works for me.


问:
using javascript to get value of a cookie that was set in php
I have a cookie that I set the value in PHP, and I would like to the its value in javascript. I cant find any tutorials on this, I find tutorials that set and get values from either php or javascript, but i cant find a tutorial of setting a cookie in php and getting its value in JavaScript. The php cookie is workign i have echoed it.

PHP

```<code>setcookie($name, $pID, time() + (86400 * 30), "/");
</code>```

Javascript

I tried this from W3 school but it doesnt work.

```<code>function displayA() {
        var name = "id=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for(var i = 0; i <ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        alert(c);
    }
</code>```

答:
This is what I have been used in many projects, never had an issue.
Check the jsfiddle for usage.

Also, use your browser (like Chrome) to check all saved cookies make sure you have the cookie before you read it.

EXP: https://jsfiddle.net/1t4q9ejx/

```<code>/*-----------------------------------------------------
            global function for Set/Get Cookie
------------------------------------------------------*/
function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  var expires = "expires=" + d.toGMTString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}
//set cookie
setCookie("selectedUnit", "10", 365);
//get cookie
let cookieUnits = getCookie("selectedUnit");
console.log('cookieUnits-->' + cookieUnits);

//list all cookies
function listCookies() {
  var theCookies = document.cookie.split(';');
  var aString = '';
  for (var i = 1; i <= theCookies.length; i++) {
    aString += i + ' ' + theCookies[i - 1] + "\n";
  }
  return aString;
}
console.log(listCookies());
</code>```

Body:
I have a cookie that I set the value in PHP, and I would like to the its value in javascript. I cant find any tutorials on this, I find tutorials that set and get values from either php or javascript, but i cant find a tutorial of setting a cookie in php and getting its value in JavaScript. The php cookie is workign i have echoed it.

PHP

setcookie($name, $pID, time() + (86400 * 30), "/");

Javascript

I tried this from W3 school but it doesnt work.

function displayA() {
        var name = "id=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for(var i = 0; i <ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        alert(c);
    }

Body:
This is what I have been used in many projects, never had an issue.
Check the jsfiddle for usage.

Also, use your browser (like Chrome) to check all saved cookies make sure you have the cookie before you read it.

EXP: https://jsfiddle.net/1t4q9ejx/

/*-----------------------------------------------------
            global function for Set/Get Cookie
------------------------------------------------------*/
function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  var expires = "expires=" + d.toGMTString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}
//set cookie
setCookie("selectedUnit", "10", 365);
//get cookie
let cookieUnits = getCookie("selectedUnit");
console.log('cookieUnits-->' + cookieUnits);

//list all cookies
function listCookies() {
  var theCookies = document.cookie.split(';');
  var aString = '';
  for (var i = 1; i <= theCookies.length; i++) {
    aString += i + ' ' + theCookies[i - 1] + "\n";
  }
  return aString;
}
console.log(listCookies());


问:
Imposible to use PCA filter from Weka in java code
I have to implement a classifier in java on a dataset with a large number of attributes (1000).

My problem is when I want to use a pca filter on my dataset. I did it with the "Explorer" Preprocess interface of Weka and it works (I get 20 attributes).

It is impossible for me to create the filter, the console return me an error that I don't understand.

Here a simple class using the filter:

```<code>import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.classifiers.bayes.NaiveBayes;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.PrincipalComponents;

public class ClassifierWithFilter{
        public static void main(String args[]) throws Exception{
        //load dataset
        DataSource source = new DataSource("path/trainingfile.arff");
        Instances trainingSet = source.getDataSet();
        //set class index to the last attribute
        trainingSet.setClassIndex(trainingSet.numAttributes()-1);

        //filter
        PrincipalComponents pca = new PrincipalComponents();
        Instances newTrainingSet= Filter.useFilter(dataSet, pca);
        System.out.println(newTrainingSet);

        //the base classifier
        NaiveBayes nb = new NaiveBayes();
        nb.buildClassifier(trainingSet);
        System.out.println(nb);
    }
}
</code>```

The error:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: no/uib/cipr/matrix/Matrix
   at weka.api.ClassifierWithFilter.main(ClassifierWithFilter.java:38)
Caused by: java.lang.ClassNotFoundException: no.uib.cipr.matrix.Matrix
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more
</code>```

If I put the 3 lines below //filter, the error disappears.

I am using the jar package of weka-3-8-1.

答: I finally found the error, I just use a previous version of the Weka package: Weka 3.6.0 and the error disappear.</p>

Body:
I have to implement a classifier in java on a dataset with a large number of attributes (1000).

My problem is when I want to use a pca filter on my dataset. I did it with the "Explorer" Preprocess interface of Weka and it works (I get 20 attributes).

It is impossible for me to create the filter, the console return me an error that I don't understand.

Here a simple class using the filter:

import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.classifiers.bayes.NaiveBayes;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.PrincipalComponents;

public class ClassifierWithFilter{
        public static void main(String args[]) throws Exception{
        //load dataset
        DataSource source = new DataSource("path/trainingfile.arff");
        Instances trainingSet = source.getDataSet();
        //set class index to the last attribute
        trainingSet.setClassIndex(trainingSet.numAttributes()-1);

        //filter
        PrincipalComponents pca = new PrincipalComponents();
        Instances newTrainingSet= Filter.useFilter(dataSet, pca);
        System.out.println(newTrainingSet);

        //the base classifier
        NaiveBayes nb = new NaiveBayes();
        nb.buildClassifier(trainingSet);
        System.out.println(nb);
    }
}

The error:

Exception in thread "main" java.lang.NoClassDefFoundError: no/uib/cipr/matrix/Matrix
   at weka.api.ClassifierWithFilter.main(ClassifierWithFilter.java:38)
Caused by: java.lang.ClassNotFoundException: no.uib.cipr.matrix.Matrix
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more

If I put the 3 lines below //filter, the error disappears.

I am using the jar package of weka-3-8-1.


问:
Ordering for key value pairs
I have the following two classes:

```<code>class KeyClass {
    private prop1;
    private prop2;

    hashcode() {
    //implemented properly
    }

    equals() {
    //implemented properly
    }
}

class ValueClass {
    private prop1;
    private prop2;

    hashcode() {
    //implemented properly
    }

    equals() {
    //implemented properly
    }
}
</code>```

I am trying to find out the max pair from a map where objects of these classes are key and value pairs respectively. I also have an com.google.common.collect.Ordering<ValueClass> which uses multiple comparators. I can easily find out the max of values using this ordering, but what I am interested into is the key of the max value.

I can write a certain implementation wherein I can keep track of my key w.r.t the value in a loop and use the ordering to compare values (similar to the conventional way of finding a max value) but I want to know if we already have such case handled by Guava or any other library?

答:
You say guava or any other library and that's straightforward with Java 8 streams. If your Ordering<ValueClass> instance is called ordering:

```<code>Entry<KeyClass, ValueClass> maxEntry = map.entrySet().stream()
        .max(Comparator.comparing(Entry::getValue, ordering))
        .orElse(null);
</code>```

Add .map(Entry::getKey) before orElse to get just the key.

The above is possible since guava's Ordering implements java.util.Comparator so you can pass it as argument to comparing.

Title: Ordering for key value pairs

Body:
I have the following two classes:

class KeyClass {
    private prop1;
    private prop2;

    hashcode() {
    //implemented properly
    }

    equals() {
    //implemented properly
    }
}

class ValueClass {
    private prop1;
    private prop2;

    hashcode() {
    //implemented properly
    }

    equals() {
    //implemented properly
    }
}

I am trying to find out the max pair from a map where objects of these classes are key and value pairs respectively. I also have an com.google.common.collect.Ordering<ValueClass> which uses multiple comparators. I can easily find out the max of values using this ordering, but what I am interested into is the key of the max value.

I can write a certain implementation wherein I can keep track of my key w.r.t the value in a loop and use the ordering to compare values (similar to the conventional way of finding a max value) but I want to know if we already have such case handled by Guava or any other library?

Body:
You say guava or any other library and that's straightforward with Java 8 streams. If your Ordering<ValueClass> instance is called ordering:

Entry<KeyClass, ValueClass> maxEntry = map.entrySet().stream()
        .max(Comparator.comparing(Entry::getValue, ordering))
        .orElse(null);

Add .map(Entry::getKey) before orElse to get just the key.

The above is possible since guava's Ordering implements java.util.Comparator so you can pass it as argument to comparing.


问:
GORM criteria group by in subquery
Let's assume the following Grails domains:

```<code>Owner {
 String name
 static hasMany [cars: Cars]
}

Car {
 Date inspectionDate
}
</code>```

I want to be able to search for Owners through Criteria, with the following rule: Most recent Car by inspectionDate in Owner's cars list being lower than *given date*.

As an example, I want to apply the following code to a select query in GORM:

```<code>queryResultsList = allOwnersList.filter { owner ->
    owner.cars.min{ car -> car.inspectionDate }.inspectionDate < myDate
}
</code>```

I need to achieve it using Criteria because I am already filtering Owners on other fields.
The whole given code is used as an example, some parts of the original code has been ommited, and source code is not about cars and owners.

As on first thought I assumed I needed a subquery in SQL to retrieve my data as I expected, I tried the following:

```<code>Owner.createCriteria().list {
    // [...] some filters on other fields
    cars {
        lt('inspectionDate', params.inspectionDate)

        'in'('inspectionDate', new grails.gorm.DetachedCriteria(Owner).list {
            projections {
                cars {
                    min('inspectionDate')
                }
            }
        })
    }
}
</code>```

I also tried to add groupProperty in different places in the projection, ending with MissingPropertyException.

I am using Grails 2.2.4

答:
After a few days testing solutions, I've come to the following one:

```<code>Owner.createCriteria().list {
    // [...] some filters on other fields
    cars {
        lt('inspectionDate', params.inspectionDate)

        'in'('inspectionDate', Owner.createCriteria().list {

            projections {
                cars {
                    min('inspectionDate')
                }
                groupProperty 'id'
            }
        // this allows to only get first property, which is inspectionDate
        }.collect { it[0] })
    }
}
</code>```

However, I still feel like doing things wrong. In particular, the collect part looks like a code smell.

I am posting this because it does what I need, but any help with finding a good solution will be appreciated.

Title: GORM criteria group by in subquery

Body:
Let's assume the following Grails domains:

Owner {
 String name
 static hasMany [cars: Cars]
}

Car {
 Date inspectionDate
}

I want to be able to search for Owners through Criteria, with the following rule: Most recent Car by inspectionDate in Owner's cars list being lower than *given date*.

As an example, I want to apply the following code to a select query in GORM:

queryResultsList = allOwnersList.filter { owner ->
    owner.cars.min{ car -> car.inspectionDate }.inspectionDate < myDate
}

I need to achieve it using Criteria because I am already filtering Owners on other fields.
The whole given code is used as an example, some parts of the original code has been ommited, and source code is not about cars and owners.

As on first thought I assumed I needed a subquery in SQL to retrieve my data as I expected, I tried the following:

Owner.createCriteria().list {
    // [...] some filters on other fields
    cars {
        lt('inspectionDate', params.inspectionDate)

        'in'('inspectionDate', new grails.gorm.DetachedCriteria(Owner).list {
            projections {
                cars {
                    min('inspectionDate')
                }
            }
        })
    }
}

I also tried to add groupProperty in different places in the projection, ending with MissingPropertyException.

I am using Grails 2.2.4

Body:
After a few days testing solutions, I've come to the following one:

Owner.createCriteria().list {
    // [...] some filters on other fields
    cars {
        lt('inspectionDate', params.inspectionDate)

        'in'('inspectionDate', Owner.createCriteria().list {

            projections {
                cars {
                    min('inspectionDate')
                }
                groupProperty 'id'
            }
        // this allows to only get first property, which is inspectionDate
        }.collect { it[0] })
    }
}

However, I still feel like doing things wrong. In particular, the collect part looks like a code smell.

I am posting this because it does what I need, but any help with finding a good solution will be appreciated.


问:
Using DateTimeKind on DateTime triggers V3058
```<code>var dict1 = new Dictionary<DateTime, int>()
{
    [new DateTime(0, DateTimeKind.Utc)] = 0,
    [new DateTime(1, DateTimeKind.Utc)] = 1
}
</code>```

dict1 triggers V3058 "V3058 An item with the same key '1' has already been added.".

https://www.viva64.com/en/w/V3058/ states that it warns about issues, that will cause an ArgumentException.
This is clearly not the case here as the keys are different.

Leaving out DateTimeKind.UTC from the ctors stops triggering V3058.

```<code>var dict2 = new Dictionary<DateTime, int>()
{
    [new DateTime(0)] = 0,
    [new DateTime(1)] = 1
}
</code>```

答: Thanks for your feedback! We will fix the issue and let you know about the results. PVS-Studio Team.</p>

Body:
var dict1 = new Dictionary<DateTime, int>()
{
    [new DateTime(0, DateTimeKind.Utc)] = 0,
    [new DateTime(1, DateTimeKind.Utc)] = 1
}

dict1 triggers V3058 "V3058 An item with the same key '1' has already been added.".

https://www.viva64.com/en/w/V3058/ states that it warns about issues, that will cause an ArgumentException.
This is clearly not the case here as the keys are different.

Leaving out DateTimeKind.UTC from the ctors stops triggering V3058.

var dict2 = new Dictionary<DateTime, int>()
{
    [new DateTime(0)] = 0,
    [new DateTime(1)] = 1
}


问:
How to query for status of "Scheduled Jobs" in ClearCase?
I have setup several custom scheduled jobs in my ClearCase Task Scheduler, these jobs are supposed to do automated sync and we usually have no problem with them.

Occasionally the jobs might fail, and I am looking for a CLI way of querying the status of these scheduled jobs and generate a basic report.

Is there such a CLI utility?

答:
The cleartool schedule presented in Viewing job properties seems complete enough:

To view messages and information such as time and status from the last execution of the job, use this command:

```<code>cleartool schedule –status job-id-or-name
</code>```

These commands display properties of jobs by using the job-definition syntax documented on the schedule reference page.

Body:
The cleartool schedule presented in Viewing job properties seems complete enough:

To view messages and information such as time and status from the last execution of the job, use this command:

cleartool schedule –status job-id-or-name

These commands display properties of jobs by using the job-definition syntax documented on the schedule reference page.


问:
How do I manually configure a JdbcTemplate in Spring Boot?
Here's my basic DAO implementation class:

```<code>@Repository
public class MeetingDaoImpl implements MeetingDao {

  @Autowired
  JdbcTemplate jdbcTemplate;

  public boolean insertNewMeeting(String initials, String meetingId, int numYears) {

    int numRowsAffected = jdbcTemplate.update(SQLConstants.INSERT_NEW_MEETING,
        new Object[] {initials.toLowerCase(), meetingId, numYears});

    return numRowsAffected > 0;

  }
}
</code>```

The jdbcTemplate automatically reads the spring.datasource properties from my application.properties file, which is great, but it includes my DB password which is something I don't want to commit. Instead, I'd like to read it from a local server.properties file instead which I can easily read from a Java class.

Is there a way to configure the jdbcTemplate with Java? I've seen multiple examples using a bean and XML, but none with Java.

答:
You can give properties like below :

datasource.local.url=
datasource.local.driver-class-name=
datasource.local.username=
datasource.local.password=

Create a configuration class:

```<code>@Configuration
   @ConfigurationProperties("datasource.local")
   @EnableJpaRepositories(
        basePackages = "com...",
        transactionManagerRef = "localTransactionManager",
        entityManagerFactoryRef = "localEntityManagerFactory"
    )
    public class OracleConfiguration {
    @NotNull
    private String username;
    @NotNull
    private String password;

    @NotNull
    private String url;

    private String driverClassName;

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @Bean
    DataSource localDataSource() throws SQLException {

         return DataSourceBuilder
                 .create()
                 .url(this.url)
                 .username(this.username)
                 .password(this.password)
                 .driverClassName(this.driverClassName)
                 .build();
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    @Bean
    @Autowired
    public PlatformTransactionManager localTransactionManager(@Qualifier("localEntityManagerFactory")
                                                                          EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }

    @Bean
    @Autowired
    public LocalContainerEntityManagerFactoryBean localEntityManagerFactory(@Qualifier("localDataSource")DataSource dataSource) {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(dataSource);
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan("com...");

        return factoryBean;
    }
    @Bean
    @Autowired
    public JdbcTemplate localJdbcTemplate(@Qualifier("localDataSource")DataSource dataSource) {
            return new JdbcTemplate(dataSource);
        }}
</code>```

In your main application class, include this Configuration file:

```<code>@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
        DataSourceTransactionManagerAutoConfiguration.class })
@EnableTransactionManagement
@Import({ OracleConfiguration.class})
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }}
</code>```

Then in your class where you need to inject the template:

```<code>@Autowired
    private JdbcTemplate localJdbcTemplate;
</code>```

Body:
Here's my basic DAO implementation class:

@Repository
public class MeetingDaoImpl implements MeetingDao {

  @Autowired
  JdbcTemplate jdbcTemplate;

  public boolean insertNewMeeting(String initials, String meetingId, int numYears) {

    int numRowsAffected = jdbcTemplate.update(SQLConstants.INSERT_NEW_MEETING,
        new Object[] {initials.toLowerCase(), meetingId, numYears});

    return numRowsAffected > 0;

  }
}

The jdbcTemplate automatically reads the spring.datasource properties from my application.properties file, which is great, but it includes my DB password which is something I don't want to commit. Instead, I'd like to read it from a local server.properties file instead which I can easily read from a Java class.

Is there a way to configure the jdbcTemplate with Java? I've seen multiple examples using a bean and XML, but none with Java.

Body:
You can give properties like below :

datasource.local.url=
datasource.local.driver-class-name=
datasource.local.username=
datasource.local.password=

Create a configuration class:

@Configuration
   @ConfigurationProperties("datasource.local")
   @EnableJpaRepositories(
        basePackages = "com...",
        transactionManagerRef = "localTransactionManager",
        entityManagerFactoryRef = "localEntityManagerFactory"
    )
    public class OracleConfiguration {
    @NotNull
    private String username;
    @NotNull
    private String password;

    @NotNull
    private String url;

    private String driverClassName;

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @Bean
    DataSource localDataSource() throws SQLException {

         return DataSourceBuilder
                 .create()
                 .url(this.url)
                 .username(this.username)
                 .password(this.password)
                 .driverClassName(this.driverClassName)
                 .build();
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    @Bean
    @Autowired
    public PlatformTransactionManager localTransactionManager(@Qualifier("localEntityManagerFactory")
                                                                          EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }

    @Bean
    @Autowired
    public LocalContainerEntityManagerFactoryBean localEntityManagerFactory(@Qualifier("localDataSource")DataSource dataSource) {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(dataSource);
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan("com...");

        return factoryBean;
    }
    @Bean
    @Autowired
    public JdbcTemplate localJdbcTemplate(@Qualifier("localDataSource")DataSource dataSource) {
            return new JdbcTemplate(dataSource);
        }}

In your main application class, include this Configuration file:

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
        DataSourceTransactionManagerAutoConfiguration.class })
@EnableTransactionManagement
@Import({ OracleConfiguration.class})
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }}

Then in your class where you need to inject the template:

@Autowired
    private JdbcTemplate localJdbcTemplate;


问:
Issue while starting Python,Spark and Gunicorn
I am trying to restart Python, gunicorn and spark as soon as the Capistrano completes the deployment but I am getting the below error. However, When I tried to execute these commands on the server by ssh then it is working fine.

Function in deploy.rb:

```<code>desc 'Restart django'
    task :restart_django do
      on roles(:django), in: :sequence, wait: 5 do
        within "#{fetch(:deploy_to)}/current/" do
          execute "cd #{fetch(:deploy_to)}/current/ &&  source bin/activate "
          execute "sudo /etc/init.d/supervisor stop && sudo fuser -k 8000/tcp && pkill -f python && pkill -f gunicorn && pkill -f spark"
#execute " cd /home/ubuntu/code/spark-2.1.0-bin-hadoop2.7/sbin/ && ./start-master.sh && ./start-slave.sh spark://127.0.0.1:7077;"
          #execute "sleep 20"
          #execute "cd /home/ubuntu/code/ && nohup gunicorn example.wsgi:application --name example --workers 4 &"
        end
      end
  end
</code>```

Deploy Output:

```<code>cap dev deploy:restart_django
Using airbrussh format.
Verbose output is being written to log/capistrano.log.
00:00 deploy:restart_django
      01 cd /home/ubuntu/code/ &&  source bin/activate
    ✔ 01 ubuntu@xx-xx-xx-xx-xx.us-west-1.compute.amazonaws.com 2.109s
      02 sudo /etc/init.d/supervisor stop && sudo fuser -k 8000/tcp && pkill -f python gunicorn spark
(Backtrace restricted to imported tasks)
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing as ubuntu@ec2-54-244-99-254.us-west-2.compute.amazonaws.com: sudo /etc/init.d/supervisor stop && sudo fuser -k 8000/tcp && pkill -f python gunicorn spark exit status: 1
sudo /etc/init.d/supervisor stop && sudo fuser -k 8000/tcp && pkill -f python gunicorn spark stdout: Stopping supervisor: supervisord.
sudo /etc/init.d/supervisor stop && sudo fuser -k 8000/tcp && pkill -f python gunicorn spark stderr: Nothing written

SSHKit::Command::Failed: sudo /etc/init.d/supervisor stop && sudo fuser -k 8000/tcp && pkill -f python gunicorn spark exit status: 1
sudo /etc/init.d/supervisor stop && sudo fuser -k 8000/tcp && pkill -f python gunicorn spark stdout: Stopping supervisor: supervisord.
sudo /etc/init.d/supervisor stop && sudo fuser -k 8000/tcp && pkill -f python gunicorn spark stderr: Nothing written

Tasks: TOP => deploy:restart_django
(See full trace by running task with --trace)
</code>```

答:
Capistrano by default invokes no-login, non-interactive shell. However, It's not the good option to use login shell with it but I am able to solve the issue by invoking the login shell under Capistrano execute with below command.</p>

```<code>execute "bash --login -c 'pkill -f spark'", raise_on_non_zero_exit: false
</code>```

Body:
I am trying to restart Python, gunicorn and spark as soon as the Capistrano completes the deployment but I am getting the below error. However, When I tried to execute these commands on the server by ssh then it is working fine.

Function in deploy.rb:

desc 'Restart django'
    task :restart_django do
      on roles(:django), in: :sequence, wait: 5 do
        within "#{fetch(:deploy_to)}/current/" do
          execute "cd #{fetch(:deploy_to)}/current/ &&  source bin/activate "
          execute "sudo /etc/init.d/supervisor stop && sudo fuser -k 8000/tcp && pkill -f python && pkill -f gunicorn && pkill -f spark"
#execute " cd /home/ubuntu/code/spark-2.1.0-bin-hadoop2.7/sbin/ && ./start-master.sh && ./start-slave.sh spark://127.0.0.1:7077;"
          #execute "sleep 20"
          #execute "cd /home/ubuntu/code/ && nohup gunicorn example.wsgi:application --name example --workers 4 &"
        end
      end
  end

Deploy Output:

cap dev deploy:restart_django
Using airbrussh format.
Verbose output is being written to log/capistrano.log.
00:00 deploy:restart_django
      01 cd /home/ubuntu/code/ &&  source bin/activate
    ✔ 01 ubuntu@xx-xx-xx-xx-xx.us-west-1.compute.amazonaws.com 2.109s
      02 sudo /etc/init.d/supervisor stop && sudo fuser -k 8000/tcp && pkill -f python gunicorn spark
(Backtrace restricted to imported tasks)
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing as ubuntu@ec2-54-244-99-254.us-west-2.compute.amazonaws.com: sudo /etc/init.d/supervisor stop && sudo fuser -k 8000/tcp && pkill -f python gunicorn spark exit status: 1
sudo /etc/init.d/supervisor stop && sudo fuser -k 8000/tcp && pkill -f python gunicorn spark stdout: Stopping supervisor: supervisord.
sudo /etc/init.d/supervisor stop && sudo fuser -k 8000/tcp && pkill -f python gunicorn spark stderr: Nothing written

SSHKit::Command::Failed: sudo /etc/init.d/supervisor stop && sudo fuser -k 8000/tcp && pkill -f python gunicorn spark exit status: 1
sudo /etc/init.d/supervisor stop && sudo fuser -k 8000/tcp && pkill -f python gunicorn spark stdout: Stopping supervisor: supervisord.
sudo /etc/init.d/supervisor stop && sudo fuser -k 8000/tcp && pkill -f python gunicorn spark stderr: Nothing written

Tasks: TOP => deploy:restart_django
(See full trace by running task with --trace)

Body:
Capistrano by default invokes no-login, non-interactive shell. However, It's not the good option to use login shell with it but I am able to solve the issue by invoking the login shell under Capistrano execute with below command.

execute "bash --login -c 'pkill -f spark'", raise_on_non_zero_exit: false


问:
Wait Until another function finish
I have a problem. Two function are called from one event almost on the same time. Function1 is doing some asynchronous staff  :

```<code>function1 (callback_Data){
   //some other callbacks here
}

function2 (){

}
</code>```

I want function2 to wait until all callbacks which are in function1 to finish and then to start.

答:
It is a simple method you can call the second function after the 1st function complete execution.

 like this

```<code>function1 (callback_Data){
//some other callbacks here
function2 ();//here is the function call
}
function2 (){
//your code
}
</code>```

Title: Wait Until another function finish

Body:
I have a problem. Two function are called from one event almost on the same time. Function1 is doing some asynchronous staff  :

function1 (callback_Data){
   //some other callbacks here
}

function2 (){

}

I want function2 to wait until all callbacks which are in function1 to finish and then to start.

Body:
It is a simple method you can call the second function after the 1st function complete execution.

 like this

function1 (callback_Data){
//some other callbacks here
function2 ();//here is the function call
}
function2 (){
//your code
}


问:
Building an Angular 2 project with a single TypeScript file compiled separately
I'm currently creating a Chrome Extension in Angular 2. The application has a background.js file that contains the functionality relating to the long-running process that will run in the background while the extension is running. This file (background.js) is currently completely separate from the Angular 2 project and upon build is handled (and copied) as an asset. This setup works, however I really want to use TypeScript in my background file as well.

In this TypeScript file I actually want to access some of the files from my Angular 2 project as such:

```<code>///<reference path="app/app.settings.ts"/>
</code>```

I only need settings (constants) and business objects (classes), nothing more complex.

To actually use this project as an extension I need to build the Angular 2 project and compile the background TypeScript file to a separate JavaScript file on the same location.

What I tried:

Configuring angular build to separately compile the background file

I played around with my angular-cli.json file to achieve the desired results with a single "ng build" commands. I tried the include and files options, with no luck.

Using a script that builds the angular app and compiles the .ts file to the same directory

This one was actually promising. I have the following script that takes a single argument (output path):

```<code>#!/bin/bash
ng build --output-path=$1
tsc --outDir $1 src/background.ts
</code>```

The script works, the Angular projects is built, the background.ts file is compiled along with the referenced dependencies and these are all available in the desired location. However the generated JavaScript does not work, I'm getting the following errors for example:

```<code>Uncaught ReferenceError: exports is not defined
Uncaught SyntaxError: Unexpected token import
</code>```

As I understand now, I'll have to use Webpack to actually make this work, but I did not find a way to do that from the command line, separately from my Angular project.

答:
So, I managed to solve this, I'll leave the answer here, maybe it will help someone.

The solution for me was using browserify to produce a .js that works in browsers. First it needs to be installed globally:

```<code>npm install -g browserify
</code>```

The script posted in the question had to be modified to something like this:

```<code>#!/bin/bash
ng build --output-path=$1
tsc --outDir $1 src/background.ts
browserify $1\\background.js -o $1\\background-browserified.js
</code>```

This way running a single command builds my Angular 2 project and compiles and copies the separate Typescript file to the same location.

I'm sure that other module bundlers like Webpack could've been used as well, but for a simple case like this browserify was the best fit I could find.

Body:
I'm currently creating a Chrome Extension in Angular 2. The application has a background.js file that contains the functionality relating to the long-running process that will run in the background while the extension is running. This file (background.js) is currently completely separate from the Angular 2 project and upon build is handled (and copied) as an asset. This setup works, however I really want to use TypeScript in my background file as well.

In this TypeScript file I actually want to access some of the files from my Angular 2 project as such:

///<reference path="app/app.settings.ts"/>

I only need settings (constants) and business objects (classes), nothing more complex.

To actually use this project as an extension I need to build the Angular 2 project and compile the background TypeScript file to a separate JavaScript file on the same location.

What I tried:

Configuring angular build to separately compile the background file

I played around with my angular-cli.json file to achieve the desired results with a single "ng build" commands. I tried the include and files options, with no luck.

Using a script that builds the angular app and compiles the .ts file to the same directory

This one was actually promising. I have the following script that takes a single argument (output path):

#!/bin/bash
ng build --output-path=$1
tsc --outDir $1 src/background.ts

The script works, the Angular projects is built, the background.ts file is compiled along with the referenced dependencies and these are all available in the desired location. However the generated JavaScript does not work, I'm getting the following errors for example:

Uncaught ReferenceError: exports is not defined
Uncaught SyntaxError: Unexpected token import

As I understand now, I'll have to use Webpack to actually make this work, but I did not find a way to do that from the command line, separately from my Angular project.

Body:
So, I managed to solve this, I'll leave the answer here, maybe it will help someone.

The solution for me was using browserify to produce a .js that works in browsers. First it needs to be installed globally:

npm install -g browserify

The script posted in the question had to be modified to something like this:

#!/bin/bash
ng build --output-path=$1
tsc --outDir $1 src/background.ts
browserify $1\\background.js -o $1\\background-browserified.js

This way running a single command builds my Angular 2 project and compiles and copies the separate Typescript file to the same location.

I'm sure that other module bundlers like Webpack could've been used as well, but for a simple case like this browserify was the best fit I could find.


问:
What is the merit of the "function" type (not "pointer to function")
Reading the C++ Standard, i see that there are "function" types and "pointer to function" types:

```<code>typedef int func(int);     // function
typedef int (*pfunc)(int); // pointer to function
typedef func* pfunc;       // same as above
</code>```

I have never seen the function types used outside of examples (or maybe i didn't recognize their usage?). Some examples:

```<code>func increase, decrease;            // declares two functions
int increase(int), decrease(int);   // same as above

int increase(int x) {return x + 1;} // cannot use the typedef when defining functions
int decrease(int x) {return x - 1;} // cannot use the typedef when defining functions

struct mystruct
{
    func add, subtract, multiply;   // declares three member functions
    int member;
};

int mystruct::add(int x) {return x + member;} // cannot use the typedef
int mystruct::subtract(int x) {return x - member;}

int main()
{
    func k; // the syntax is correct but the variable k is useless!
    mystruct myobject;
    myobject.member = 4;

    cout << increase(5) << ' ' << decrease(5) << '\n'; // outputs 6 and 4
    cout << myobject.add(5) << ' ' << myobject.subtract(5) << '\n'; // 9 and 1
}
</code>```

Seeing that the function types support syntax that doesn't appear in C (declaring member functions), i guess they are not just a part of C baggage that C++ has to support for backward compatibility.

So is there any use for function types, other than demonstrating some funky syntax?

答:
On the one hand, you seem to be talking about function types in general. On the other hand, it appears that your question is really about the usability of typedef names for function types.

The function types themselves is a fundamental concept built into both C and C++ languages. They are used all the time. You just can't live without them. Every time you declare a function you declare an entity of function type. Every time you use a pointer to a function, you use a pointer to function type. Etc.

As for the possibility of making typedef names for function types... I don't see much use for it. It is, I think, a part of C baggage, that was extended a bit for C++ just because it was easy to do.

As you correctly noted typedef names for function types can be used to declare member functions (and in C++ you can also include const specifier into typedef, as in typedef int MemberType() const;), but, for example, you can't use this feature with function types passed as template parameters.

Body:
Reading the C++ Standard, i see that there are "function" types and "pointer to function" types:

typedef int func(int);     // function
typedef int (*pfunc)(int); // pointer to function
typedef func* pfunc;       // same as above

I have never seen the function types used outside of examples (or maybe i didn't recognize their usage?). Some examples:

func increase, decrease;            // declares two functions
int increase(int), decrease(int);   // same as above

int increase(int x) {return x + 1;} // cannot use the typedef when defining functions
int decrease(int x) {return x - 1;} // cannot use the typedef when defining functions

struct mystruct
{
    func add, subtract, multiply;   // declares three member functions
    int member;
};

int mystruct::add(int x) {return x + member;} // cannot use the typedef
int mystruct::subtract(int x) {return x - member;}

int main()
{
    func k; // the syntax is correct but the variable k is useless!
    mystruct myobject;
    myobject.member = 4;

    cout << increase(5) << ' ' << decrease(5) << '\n'; // outputs 6 and 4
    cout << myobject.add(5) << ' ' << myobject.subtract(5) << '\n'; // 9 and 1
}

Seeing that the function types support syntax that doesn't appear in C (declaring member functions), i guess they are not just a part of C baggage that C++ has to support for backward compatibility.

So is there any use for function types, other than demonstrating some funky syntax?


问:
Laravel PHP Unit Testing
I am just testing my laravel app with phpunit
When i run vendor/bin/phpunit i am getting error like below Error: Call to undefined method ExampleTest::assertStatus()

Below is the code i was trying to execute

```<code>$response = $this->json('POST', '/users', ['customer_name' => 'Ratke-Harris']);

        $response
            ->assertStatus(200)
            ->assertExactJson([
                'created' => true,
            ]);
</code>```

As per the laravel docs , even there they have mentioned the same example. I don't understand why it is throwing  error.

Any ideas ? Please.

答: Change ->assertStatus(200) to ->assertResponseStatus(200)

Title: Laravel PHP Unit Testing

Body:
I am just testing my laravel app with phpunit
When i run vendor/bin/phpunit i am getting error like below Error: Call to undefined method ExampleTest::assertStatus()

Below is the code i was trying to execute

$response = $this->json('POST', '/users', ['customer_name' => 'Ratke-Harris']);

        $response
            ->assertStatus(200)
            ->assertExactJson([
                'created' => true,
            ]);

As per the laravel docs , even there they have mentioned the same example. I don't understand why it is throwing  error.

Any ideas ? Please.