问:
CROSS APPLY Creating Additional Records
I am trying to create a report that display potential duplicate records based on three criteria: the last 4 of an SSN, last name and DOB.  I posted a question here on the issue and received an answer that I should be using a Cross Apply to unpivot the data. The query runs fast and the results look better than my original query.

The new query is below and I have added a filter to show two examples that I am seeing occur across the data:

```<code>DECLARE
@StartDate DATE = '1/1/2017',
@EndDate DATE = '3/1/2017';

WITH
CTE
AS
(
SELECT
    DENSE_RANK() OVER (ORDER BY c.socialSecurityNumber) AS [SSNRanking] ,

    c.id AS [CustomerID]  ,
    c.socialSecurityNumber AS [SSN],
    c.firstName AS [FirstName] ,
    c.lastName AS [LastName] ,
    c.birthDate [BirthDate] ,
    c.emailAddress AS [EmailAddress],
    c.createDate AS [CreateDate] ,
    MAX(co.orderDate) AS [LastOrderDate] ,
    ca.street1 AS [Addr1] ,
    ca.city AS [City] ,
    ca.stateAndTerritoriesID AS [State],
    ca.zipCode5 AS [Zip] ,

    c2.id AS [DupCustomerID] ,
    c2.socialSecurityNumber AS [DupSSN] ,
    c2.firstName AS [DupFirstName] ,
    c2.lastName AS [DupLastName] ,
    c2.birthDate AS [DupBirthDate] ,
    c2.emailAddress AS [DupEmailAddress] ,
    c2.createDate AS [DupCreateDate] ,
    MAX(co.orderDate) AS [DupLastOrderDate] ,
    ca.street1 AS [DupAddr1] ,
    ca.city AS [DupCity],
    ca.stateAndTerritoriesID AS [DupState] ,
    ca.zipCode5 AS [DupZip]

FROM
    dbo.Customers AS [c]
    INNER JOIN dbo.Customers AS [c2] ON ( SUBSTRING(c.socialSecurityNumber,6,4) = SUBSTRING(c2.socialSecurityNumber,6,4) AND c.birthDate = c2.birthDate AND c.lastName = c2.lastName AND c.id <> c2.id )
    INNER JOIN dbo.CustomerAddresses AS [ca] ON c.id = ca.customerID
    --INNER JOIN dbo.CustomerAddresses AS [ca2] ON ca2.customerID = c2.id
    LEFT OUTER JOIN dbo.Common_Orders AS [co] ON co.customerID = c.id
WHERE
    c.customerStatusTypeID <> 'M'
    AND c2.customerStatusTypeID <> 'M'
    AND ca.addressType = 'M'
    --AND ca2.addressType = 'M'
    AND c.mergedTo IS NULL
    AND c2.mergedTo IS NULL
    AND CAST(co.orderDate AS DATE) >= @StartDate
    AND CAST(co.orderDate AS DATE) <= @EndDate
    AND ( c.id = 1545229 OR c.id = 2020489 )
GROUP BY
    c.id ,
    c.socialSecurityNumber ,
    c.firstName ,
    c.lastName ,
    c.birthDate ,
    c.emailAddress ,
    c.createDate ,
    ca.street1 ,
    ca.city ,
    ca.stateAndTerritoriesID ,
    ca.zipCode5 ,

    c2.id ,
    c2.socialSecurityNumber ,
    c2.firstName ,
    c2.lastName ,
    c2.birthDate ,
    c2.emailAddress ,
    c2.createDate ,
    ca.street1 ,
    ca.city ,
    ca.stateAndTerritoriesID ,
    ca.zipCode5
)
SELECT CA.CustomerID,
CA.SSNRanking ,
CA.SSN ,
CA.FirstName,
CA.LastName,
CA.BirthDate,
CA.EmailAddress,
CA.CreateDate ,
CA.LastOrderDate ,
CA.Addr1,
CA.City,
CA.[State],
CA.Zip
FROM
CTE
CROSS APPLY
(
    VALUES
    (CTE.SSNRanking, CTE.CustomerID,    CTE.SSN,     CTE.FirstName,    CTE.LastName,    CTE.Birthdate,    CTE.EmailAddress,    CTE.CreateDate,    CTE.LastOrderDate,    CTE.Addr1,    CTE.City,    CTE.[State],  CTE.Zip),
    (CTE.SSNRanking, CTE.DupCustomerID, CTE.DupSSN,  CTE.DupFirstName, CTE.DuplastName, CTE.DupBirthDate, CTE.DupEmailAddress, CTE.DupCreateDate, CTE.DupLastOrderDate, CTE.DupAddr1, CTE.DupCity, CTE.DupState, CTE.DupZip)
) AS CA (SSNRanking, CustomerID, SSN, FirstName, LastName, BirthDate, EmailAddress, CreateDate, LastOrderDate, Addr1, City, [State], Zip)
ORDER BY CAST(CA.SSN AS INT) ASC, CA.CustomerID;
</code>```

And the result set looks like (Original Image):

```<code>+ ---------- + ---------- + --------- + ---------- + -------- + ---------- + ------------ + --------------------- + ----------------------- + --------------------- + ------------ + ----- + ----- +
| CustomerId | SSNRanking | SSN       | FirstName  | LastName | BirthDate  | EmailAddress | CreateDate            | LastOrderDate           | Addr1                 | City         | State | Zip   |
+ ---------- + ---------- + --------- + ---------- + -------- + ---------- + ------------ + --------------------- + ----------------------- + --------------------- + ------------ + ----- + ----- +
| 1545229    | 1          | 000000000 | Aquia Boat | SALES    | 1900-01-01 | null         | 2013-05-28 00:00:00.0 | 2017-01-23 11:08:30.723 | 236 Willow Landing Rd | Stafford     | VA    | 22554 |
| 1545229    | 1          | 000000000 | Aquia Boat | SALES    | 1900-01-01 | null         | 2013-05-28 00:00:00.0 | 2017-01-06 12:31:15.370 | 11963 Jefferson Ave   | Newport News | VA    | 23606 |
| 2020489    | 1          | 000000000 | DIXIE      | SALES    | 1900-01-01 | null         | 2017-01-06 12:27:56.5 | 2017-01-06 12:31:15.370 | 11963 Jefferson Ave   | Newport News | VA    | 23606 |
| 2020489    | 1          | 000000000 | DIXIE      | SALES    | 1900-01-01 | null         | 2017-01-06 12:27:56.5 | 2017-01-23 11:08:30.723 | 236 Willow Landing Rd | Stafford     | VA    | 22554 |
+ ---------- + ---------- + --------- + ---------- + -------- + ---------- + ------------ + --------------------- + ----------------------- + --------------------- + ------------ + ----- + ----- +
</code>```

And I see that the last four of the SSN, last name and DOB all match.  But then I noticed duplicate Customer IDs Aqua Boats has an entry with the Dixie Sales address and Dixie Sales has an entry for Aqua Boats address - which I should not have and I looked in the Customer /Customer Addresses table at the particular accounts:

```<code>SELECT c.id, c.socialSecurityNumber, c.firstName, c.lastName, c.birthDate, ca.street1
    FROM dbo.Customers AS c
    INNER JOIN dbo.CustomerAddresses AS [ca] ON ca.customerID = c.id
    WHERE c.id IN (1545229,2020489) AND ca.addressType = 'M';
</code>```

And the results are here (Original Image):

```<code>+ ---------- + -------------------- + ---------- + -------- + ---------- + --------------------- +
| id         | socialSecurityNumber | firstName  | lastName | birthDate  | street 1              |
+ ---------- + -------------------- + ---------- + -------- + ---------- + --------------------- +
| 1545229    | 000000000            | Aquia Boat | SALES    | 1900-01-01 | 236 Willow Landing Rd |
| 2020489    | 000000000            | DIXIE      | SALES    | 1900-01-01 | 11963 Jefferson Ave   |
+ ---------- + -------------------- + ---------- + -------- + ---------- + --------------------- +
</code>```

When I run the query inside the CTE, I added two additional filters:

```<code>AND c.id <> ca2.customerID
AND c2.id <> ca.customerID
</code>```

And the dataset looks like I want (Original Image):

```<code>+ ---------- + ---------- + --------- + ---------- + -------- + ---------- + --------------------- + ------------ + ----- + ----- + ------------- + --------- + ------------- + ----------- + ------------- + --------------------- + ------------ + -------- + ------ +
| SSNRanking | CustomerID | SSN       | FirstName  | LastName | BirthDate  | Addr1                 | City         | State | Zip   | DupCustomerID | DupSSN    | DupFirstName  | DupLastName | DupBirthDate  | DupAddr1              | DupCity      | DupState | DupZip |
+ ---------- + ---------- + --------- + ---------- + -------- + ---------- + --------------------- + ------------ + ----- + ----- + ------------- + --------- + ------------- + ----------- + ------------- + --------------------- + ------------ + -------- + ------ +
| 1          | 1545229    | 000000000 | Aquia Boat | SALES    | 1900-01-01 | 236 Willow Landing Rd | Stafford     | VA    | 22554 | 2020589       | 000000000 | DIXIE         | SALES       | 1900-01-01    | 236 Willow Landing Rd | Stafford     | VA       | 22554  |
| 1          | 2020489    | 000000000 | DIXIE      | SALES    | 1900-01-01 | 11963 Jefferson Ave   | Newport News | VA    | 23606 | 1545229       | 000000000 | AQUIA BOAT    | SALES       | 1900-01-01    | 11963 Jefferson Ave   | Newport News | VA       | 23606  |
+ ---------- + ---------- + --------- + ---------- + -------- + ---------- + --------------------- + ------------ + ----- + ----- + ------------- + --------- + ------------- + ----------- + ------------- + --------------------- + ------------ + -------- + ------ +
</code>```

Can I prevent the CROSS APPLY from creating additional records for customers with mailing address assigned to another customer?

Thanks,

答:
i think you should throw sample data (at least 1 - 20 rows).

Or first you get your query correct then try to find duplicate records.

what do you mean by "the last 4 of an SSN, last name and DOB. " what kind of data you get ?

It appear to be very simple,

```<code>DECLARE @SampleData AS TABLE ( SSN int,lastName varchar(50),DOB datetime)
INSERT INTO @SampleData VALUES (50,'Smith','1980-02-02'),
(50,'Smith1','1980-02-02'),(50,'Smith','1980-02-02'),(50,'Smith','1980-02-02')

;With CTE as
(
select *,ROW_NUMBER()over(PARTITION by ssn,lastName,dob order by (select null))rn
from @SampleData
)
select * from cte
where rn>=4
</code>```

Title: CROSS APPLY Creating Additional Records

Body:
I am trying to create a report that display potential duplicate records based on three criteria: the last 4 of an SSN, last name and DOB.  I posted a question here on the issue and received an answer that I should be using a Cross Apply to unpivot the data. The query runs fast and the results look better than my original query.

The new query is below and I have added a filter to show two examples that I am seeing occur across the data:

DECLARE
@StartDate DATE = '1/1/2017',
@EndDate DATE = '3/1/2017';

WITH
CTE
AS
(
SELECT
    DENSE_RANK() OVER (ORDER BY c.socialSecurityNumber) AS [SSNRanking] ,

    c.id AS [CustomerID]  ,
    c.socialSecurityNumber AS [SSN],
    c.firstName AS [FirstName] ,
    c.lastName AS [LastName] ,
    c.birthDate [BirthDate] ,
    c.emailAddress AS [EmailAddress],
    c.createDate AS [CreateDate] ,
    MAX(co.orderDate) AS [LastOrderDate] ,
    ca.street1 AS [Addr1] ,
    ca.city AS [City] ,
    ca.stateAndTerritoriesID AS [State],
    ca.zipCode5 AS [Zip] ,

    c2.id AS [DupCustomerID] ,
    c2.socialSecurityNumber AS [DupSSN] ,
    c2.firstName AS [DupFirstName] ,
    c2.lastName AS [DupLastName] ,
    c2.birthDate AS [DupBirthDate] ,
    c2.emailAddress AS [DupEmailAddress] ,
    c2.createDate AS [DupCreateDate] ,
    MAX(co.orderDate) AS [DupLastOrderDate] ,
    ca.street1 AS [DupAddr1] ,
    ca.city AS [DupCity],
    ca.stateAndTerritoriesID AS [DupState] ,
    ca.zipCode5 AS [DupZip]

FROM
    dbo.Customers AS [c]
    INNER JOIN dbo.Customers AS [c2] ON ( SUBSTRING(c.socialSecurityNumber,6,4) = SUBSTRING(c2.socialSecurityNumber,6,4) AND c.birthDate = c2.birthDate AND c.lastName = c2.lastName AND c.id <> c2.id )
    INNER JOIN dbo.CustomerAddresses AS [ca] ON c.id = ca.customerID
    --INNER JOIN dbo.CustomerAddresses AS [ca2] ON ca2.customerID = c2.id
    LEFT OUTER JOIN dbo.Common_Orders AS [co] ON co.customerID = c.id
WHERE
    c.customerStatusTypeID <> 'M'
    AND c2.customerStatusTypeID <> 'M'
    AND ca.addressType = 'M'
    --AND ca2.addressType = 'M'
    AND c.mergedTo IS NULL
    AND c2.mergedTo IS NULL
    AND CAST(co.orderDate AS DATE) >= @StartDate
    AND CAST(co.orderDate AS DATE) <= @EndDate
    AND ( c.id = 1545229 OR c.id = 2020489 )
GROUP BY
    c.id ,
    c.socialSecurityNumber ,
    c.firstName ,
    c.lastName ,
    c.birthDate ,
    c.emailAddress ,
    c.createDate ,
    ca.street1 ,
    ca.city ,
    ca.stateAndTerritoriesID ,
    ca.zipCode5 ,

    c2.id ,
    c2.socialSecurityNumber ,
    c2.firstName ,
    c2.lastName ,
    c2.birthDate ,
    c2.emailAddress ,
    c2.createDate ,
    ca.street1 ,
    ca.city ,
    ca.stateAndTerritoriesID ,
    ca.zipCode5
)
SELECT CA.CustomerID,
CA.SSNRanking ,
CA.SSN ,
CA.FirstName,
CA.LastName,
CA.BirthDate,
CA.EmailAddress,
CA.CreateDate ,
CA.LastOrderDate ,
CA.Addr1,
CA.City,
CA.[State],
CA.Zip
FROM
CTE
CROSS APPLY
(
    VALUES
    (CTE.SSNRanking, CTE.CustomerID,    CTE.SSN,     CTE.FirstName,    CTE.LastName,    CTE.Birthdate,    CTE.EmailAddress,    CTE.CreateDate,    CTE.LastOrderDate,    CTE.Addr1,    CTE.City,    CTE.[State],  CTE.Zip),
    (CTE.SSNRanking, CTE.DupCustomerID, CTE.DupSSN,  CTE.DupFirstName, CTE.DuplastName, CTE.DupBirthDate, CTE.DupEmailAddress, CTE.DupCreateDate, CTE.DupLastOrderDate, CTE.DupAddr1, CTE.DupCity, CTE.DupState, CTE.DupZip)
) AS CA (SSNRanking, CustomerID, SSN, FirstName, LastName, BirthDate, EmailAddress, CreateDate, LastOrderDate, Addr1, City, [State], Zip)
ORDER BY CAST(CA.SSN AS INT) ASC, CA.CustomerID;

And the result set looks like (Original Image):

+ ---------- + ---------- + --------- + ---------- + -------- + ---------- + ------------ + --------------------- + ----------------------- + --------------------- + ------------ + ----- + ----- +
| CustomerId | SSNRanking | SSN       | FirstName  | LastName | BirthDate  | EmailAddress | CreateDate            | LastOrderDate           | Addr1                 | City         | State | Zip   |
+ ---------- + ---------- + --------- + ---------- + -------- + ---------- + ------------ + --------------------- + ----------------------- + --------------------- + ------------ + ----- + ----- +
| 1545229    | 1          | 000000000 | Aquia Boat | SALES    | 1900-01-01 | null         | 2013-05-28 00:00:00.0 | 2017-01-23 11:08:30.723 | 236 Willow Landing Rd | Stafford     | VA    | 22554 |
| 1545229    | 1          | 000000000 | Aquia Boat | SALES    | 1900-01-01 | null         | 2013-05-28 00:00:00.0 | 2017-01-06 12:31:15.370 | 11963 Jefferson Ave   | Newport News | VA    | 23606 |
| 2020489    | 1          | 000000000 | DIXIE      | SALES    | 1900-01-01 | null         | 2017-01-06 12:27:56.5 | 2017-01-06 12:31:15.370 | 11963 Jefferson Ave   | Newport News | VA    | 23606 |
| 2020489    | 1          | 000000000 | DIXIE      | SALES    | 1900-01-01 | null         | 2017-01-06 12:27:56.5 | 2017-01-23 11:08:30.723 | 236 Willow Landing Rd | Stafford     | VA    | 22554 |
+ ---------- + ---------- + --------- + ---------- + -------- + ---------- + ------------ + --------------------- + ----------------------- + --------------------- + ------------ + ----- + ----- +

And I see that the last four of the SSN, last name and DOB all match.  But then I noticed duplicate Customer IDs Aqua Boats has an entry with the Dixie Sales address and Dixie Sales has an entry for Aqua Boats address - which I should not have and I looked in the Customer /Customer Addresses table at the particular accounts:

SELECT c.id, c.socialSecurityNumber, c.firstName, c.lastName, c.birthDate, ca.street1
    FROM dbo.Customers AS c
    INNER JOIN dbo.CustomerAddresses AS [ca] ON ca.customerID = c.id
    WHERE c.id IN (1545229,2020489) AND ca.addressType = 'M';

And the results are here (Original Image):

+ ---------- + -------------------- + ---------- + -------- + ---------- + --------------------- +
| id         | socialSecurityNumber | firstName  | lastName | birthDate  | street 1              |
+ ---------- + -------------------- + ---------- + -------- + ---------- + --------------------- +
| 1545229    | 000000000            | Aquia Boat | SALES    | 1900-01-01 | 236 Willow Landing Rd |
| 2020489    | 000000000            | DIXIE      | SALES    | 1900-01-01 | 11963 Jefferson Ave   |
+ ---------- + -------------------- + ---------- + -------- + ---------- + --------------------- +

When I run the query inside the CTE, I added two additional filters:

AND c.id <> ca2.customerID
AND c2.id <> ca.customerID

And the dataset looks like I want (Original Image):

+ ---------- + ---------- + --------- + ---------- + -------- + ---------- + --------------------- + ------------ + ----- + ----- + ------------- + --------- + ------------- + ----------- + ------------- + --------------------- + ------------ + -------- + ------ +
| SSNRanking | CustomerID | SSN       | FirstName  | LastName | BirthDate  | Addr1                 | City         | State | Zip   | DupCustomerID | DupSSN    | DupFirstName  | DupLastName | DupBirthDate  | DupAddr1              | DupCity      | DupState | DupZip |
+ ---------- + ---------- + --------- + ---------- + -------- + ---------- + --------------------- + ------------ + ----- + ----- + ------------- + --------- + ------------- + ----------- + ------------- + --------------------- + ------------ + -------- + ------ +
| 1          | 1545229    | 000000000 | Aquia Boat | SALES    | 1900-01-01 | 236 Willow Landing Rd | Stafford     | VA    | 22554 | 2020589       | 000000000 | DIXIE         | SALES       | 1900-01-01    | 236 Willow Landing Rd | Stafford     | VA       | 22554  |
| 1          | 2020489    | 000000000 | DIXIE      | SALES    | 1900-01-01 | 11963 Jefferson Ave   | Newport News | VA    | 23606 | 1545229       | 000000000 | AQUIA BOAT    | SALES       | 1900-01-01    | 11963 Jefferson Ave   | Newport News | VA       | 23606  |
+ ---------- + ---------- + --------- + ---------- + -------- + ---------- + --------------------- + ------------ + ----- + ----- + ------------- + --------- + ------------- + ----------- + ------------- + --------------------- + ------------ + -------- + ------ +

Can I prevent the CROSS APPLY from creating additional records for customers with mailing address assigned to another customer?

Thanks,

Body:
i think you should throw sample data (at least 1 - 20 rows).

Or first you get your query correct then try to find duplicate records.

what do you mean by "the last 4 of an SSN, last name and DOB. " what kind of data you get ?

It appear to be very simple,

DECLARE @SampleData AS TABLE ( SSN int,lastName varchar(50),DOB datetime)
INSERT INTO @SampleData VALUES (50,'Smith','1980-02-02'),
(50,'Smith1','1980-02-02'),(50,'Smith','1980-02-02'),(50,'Smith','1980-02-02')

;With CTE as
(
select *,ROW_NUMBER()over(PARTITION by ssn,lastName,dob order by (select null))rn
from @SampleData
)
select * from cte
where rn>=4


来源: stackexchange

问:
how to filter data from from a dictionary to list
```<code>Dictionary<string, int> d4 = (Dictionary<string,int>)Session["Barcodes"];
</code>```

The dictionary contains barcodes. Simultaneously,

```<code>List<AddInventory> Getdetails = Deserialize<List<AddInventory>>(Session[hdnPullId.Value].ToString());
</code>```

This contains a list. In this model AddInventory, there is a property Barcode and in the dictionary, the string contains the Barcode. The List has many redundant entries, so i just want to have those entries in my List, which are present in dictionary.

Any kind of help will be appreciated.

Thanks

答:
i just want to have those entries in my List, which are present in
  dictionary.

```<code>Getdetails = Getdetails.Where(i => d4.ContainsKey(i.BarCode)).ToList();
</code>```

If you want to remove redundant entries you need to tell us which you want to keep.

ContentLicense: CC BY-SA 3.0

Body:
Dictionary<string, int> d4 = (Dictionary<string,int>)Session["Barcodes"];

The dictionary contains barcodes. Simultaneously,

List<AddInventory> Getdetails = Deserialize<List<AddInventory>>(Session[hdnPullId.Value].ToString());

This contains a list. In this model AddInventory, there is a property Barcode and in the dictionary, the string contains the Barcode. The List has many redundant entries, so i just want to have those entries in my List, which are present in dictionary.

Any kind of help will be appreciated.

Thanks

Body:
i just want to have those entries in my List, which are present in
  dictionary.

Getdetails = Getdetails.Where(i => d4.ContainsKey(i.BarCode)).ToList();

If you want to remove redundant entries you need to tell us which you want to keep.


问:
adb cannot connect to daemon at tcp:5037
My adb can't connect devices.
I am runing adb start-server

```<code>    ulucudeMacBook-Pro:~ ulucu$ adb start-server
    * daemon not running. starting it now at tcp:5037 *
    * daemon started successfully *
</code>```

Then run "lsof -i tcp:5037"

```<code>    ulucudeMacBook-Pro:~ ulucu$ lsof -i tcp:5037
    COMMAND  PID  USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
    adb     2308 ulucu    7u  IPv4 0x440443a862048a7b      0t0  TCP localhost:5037 (LISTEN)
</code>```

But when I run adb kill-server

```<code>    ulucudeMacBook-Pro:~ ulucu$ adb kill-server
    * server not running *
</code>```

or run adb devices or adb shell

```<code>    List of devices attached
    * daemon not running. starting it now at tcp:5037 *
    adb E 03-31 09:30:26  2350 95705 usb_osx.cpp:333] Could not open interface: e00002c5
    adb E 03-31 09:30:26  2350 95705 usb_osx.cpp:294] Could not find device interface
    error: could not install *smartsocket* listener: Address already in use
    ADB server didn't ACK
    * failed to start daemon *
    error: cannot connect to daemon
</code>```

The adb has been running.

No other processes using "5037" port.

No other simulator like "genymotion".

My system is Mac 10.12.14.

My adb version is 1.0.39.

What's the problem?

答:
Based from this thread, you cannot connect because the address is already in use. You may try busybox netstat -antp to check who is using the port. Here's another workaroung which might help:

Solve this problem on MacBook by first running the following command
  to list the process which is using port 5037

```<code>lsof -n -i4TCP:5037 | grep LISTEN
</code>```

Then, I kill it:

```<code>kill -9 <PID>
</code>```

Then, adb devices works!

Hope this helps!

ContentLicense: CC BY-SA 4.0

Body:
My adb can't connect devices.
I am runing adb start-server

    ulucudeMacBook-Pro:~ ulucu$ adb start-server
    * daemon not running. starting it now at tcp:5037 *
    * daemon started successfully *

Then run "lsof -i tcp:5037"

    ulucudeMacBook-Pro:~ ulucu$ lsof -i tcp:5037
    COMMAND  PID  USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
    adb     2308 ulucu    7u  IPv4 0x440443a862048a7b      0t0  TCP localhost:5037 (LISTEN)

But when I run adb kill-server

    ulucudeMacBook-Pro:~ ulucu$ adb kill-server
    * server not running *

or run adb devices or adb shell

    List of devices attached
    * daemon not running. starting it now at tcp:5037 *
    adb E 03-31 09:30:26  2350 95705 usb_osx.cpp:333] Could not open interface: e00002c5
    adb E 03-31 09:30:26  2350 95705 usb_osx.cpp:294] Could not find device interface
    error: could not install *smartsocket* listener: Address already in use
    ADB server didn't ACK
    * failed to start daemon *
    error: cannot connect to daemon

The adb has been running.

No other processes using "5037" port.

No other simulator like "genymotion".

My system is Mac 10.12.14.

My adb version is 1.0.39.

What's the problem?

Body:
Based from this thread, you cannot connect because the address is already in use. You may try busybox netstat -antp to check who is using the port. Here's another workaroung which might help:

Solve this problem on MacBook by first running the following command
  to list the process which is using port 5037

lsof -n -i4TCP:5037 | grep LISTEN

Then, I kill it:

kill -9 <PID>

Then, adb devices works!

Hope this helps!


问:
Android. How test duration execution of method?
I write unit test (JUnit, Espresso) for Android app.

And I want to test the duration of execution of any method in Activity. And my test must be fail if duration more than 1 second.

Is it possible in Android?

答:
```<code>long startTime = System.currentTimeMillis();

// here code to be time measured

Log.i ("Execution time ", "milliseconds : " + System.currentTimeMillis() - startTime);
</code>```


问:
How to detect the user input text language in android
I need to know How I can detect the language of a text entered by a user in an editText in android.

I search about all the available tries to solve this issue, especially in this link, How to detect language of user entered text?
but that was not applicable because the app gets crashed before it's started.

I also tried "locale" but this didn't work because it specifies the language of the device, not the text written in an edit text.

Is there any solution? could you help me?

答:
Try this</p>

```<code>InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

    InputMethodSubtype ims = imm.getCurrentInputMethodSubtype();

    String locale = ims.getLocale();
</code>```

Body:
Try this

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

    InputMethodSubtype ims = imm.getCurrentInputMethodSubtype();

    String locale = ims.getLocale();


问:
Make div responsive at certain screen size
I want that at different screen sizes for example at 480px width and lower that the #homepageRightImg goes under #homepageLeftImg. This is the code that I'm using, but it doesn't seem to be working. What am I missing or doing wrong?

HTML

```<code>        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link href="assets/css/style.css" rel="stylesheet" type="text/css" />
</head>
<!--[if IE 8]><body class="ie8"><![endif]-->
<!--[if gt IE 8]><!--><body> <!--<![endif]-->

<div id="homepageContentGlobal" class="homepageContentGlobal" style="display:none"></div>
<div></div>

        <div id="homepageLeftNav" class="homePageNav">
            <div class="content" id="homepageLeftMenuTitle">
                <p class="title">My<br>Test</p>
                <div class="subTitle">
                      <a href="http://www.google.com/" class="button">Learn more</a>
                </div>
            </div>
            <div id="homepageLeftTitle" class="homepageTitle">

            </div>
        </div>

        <div id="homepageRightNav" class="homePageNav">
           <div class="content" id="homepageRightMenuTitle">
                <p class="title">My<br>Title</p>
                <div class="subTitle">
 <a href="http://www.google.com/" class="button">Learn more</a>
                </div>
            </div>
            <div id="homepageRightTitle" class="homepageTitle">

            </div>
        </div>
<div>
        <ul id="homepageLeftImg" class="homepageCol">
<li><img src="test.jpg"></li>
<li><img src="test.jpg"></li>
<li><img src="test.jpg"></li>
<li><img src="test.jpg"></li>
<li><img src="test.jpg"/></li>
       </ul>

<ul id="homepageRightImg" class="homepageCol">
<li><img src="test.jpg"></li>
<li><img src="test.jpg"></li>
<li><img src="test.jpg"></li>
<li><img src="test.jpg"></li>
<li><img src="test.jpg"/></li>       </ul>
    </div>
</body>
</html>
</code>```

CSS

```<code>     .homepageContentGlobal {
        position: fixed;
        z-index: 98;
        left: 0;
        right: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
        overflow: hidden;
     }
    .homepageCol li {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 0;
        display: block;
     }

     #homepageLeftImg {
        position: absolute;
        top:0;
        left: 0;
        bottom: 0;
        right: 50%;
        width: 50%;
        height: 100%;
    z-index: 0;
        overflow: hidden;
     }

     #homepageRightImg {
        position: absolute;
        top:0;
        right: 0;
        left: 50%;
        width: 50%;
        height: 100%;
        overflow: hidden;
    }

     #homepageLeftNav {
        position: absolute;
        left: 0;
        right: 50%;
        width: 50%;
        z-index: 3;
        cursor: pointer;
    height: 100%;
    }

   #homepageRightNav {
        position: absolute;
        right: 0;
        left: 50%;
        width: 50%;
        z-index: 3;
        cursor: pointer;
    height: 100%;
   }

.homepageTitle {
        cursor: default;
        width: 100%;
        margin: 0 auto;
        text-align: center;
    position: absolute;
    height: 100%;
    top: 100%;
     }
   .homepageNavLink{}

    #homepageLeftMessage {
    z-index: 100;
    height: 100px;
    width: 100px;
     }

     #homepageLeftMessage #subLogo {
    z-index: 100;
    }

    @media only screen and (max-width : 480px) {
     #homepageLeftImg {
    display:block;
     }

   #homepageRightImg {
    display:block;
    }
}
</code>```

答:
Added an example how to use css other than position elements.

body,
html {
  margin: 0px;
  padding: 0px;
  height: 100%;
}

ul {
  margin: 0px;
  padding: 0px;
}

li {
  list-style: none;
  margin: 0px;
  padding: 0px;
}

#homepageLeftImg,
#homepageRightImg {
  float: left;
  /* Keeps both the div to align side by side to each other */
  width: 50%;
  /* 50% width to both equates to 100% */
  height: 100%;
}

#homepageLeftImg li,
#homepageRightImg li {
  width: 100%;
  height: 100%;
  float: left;
}

#homepageLeftImg li img,
#homepageRightImg li img {
  width: 100%;
  height: 100%;
}

@media (max-width:480px) {
  #homepageLeftImg,
  #homepageRightImg {
    width: 100%;
    /* Below 480px the width will be 100% and the images will come in stakced view. */
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="homepageLeftImg" class="homepageCol">
  <li><img src="https://dummyimage.com/400x800/red/fff&text=This+is+Dummy+left+Image"></li>

</ul>

<ul id="homepageRightImg" class="homepageCol">
  <li><img src="https://dummyimage.com/400x800/blue/fff&text=This+is+Dummy+right+Image"></li>
</ul></code>```

You are missing the width:100% and also add top:100% to the #homepageRightImg

Add the following css in your media query:

```<code>@media only screen and (max-width : 480px) {
     #homepageLeftImg {
    display:block;
width:100%;
     }

   #homepageRightImg {
    display:block;
width:100%; top:100%:
    }
}
</code>```

Also seeing your css code I see a lot poisition:absolute elements.
I suggest not to use position:absolute on every element as it destroys the structure.

Body:
I want that at different screen sizes for example at 480px width and lower that the #homepageRightImg goes under #homepageLeftImg. This is the code that I'm using, but it doesn't seem to be working. What am I missing or doing wrong?

HTML

        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link href="assets/css/style.css" rel="stylesheet" type="text/css" />

My
Test

                      Learn more

My
Title

 Learn more

CSS

     .homepageContentGlobal {
        position: fixed;
        z-index: 98;
        left: 0;
        right: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
        overflow: hidden;
     }
    .homepageCol li {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 0;
        display: block;
     }

     #homepageLeftImg {
        position: absolute;
        top:0;
        left: 0;
        bottom: 0;
        right: 50%;
        width: 50%;
        height: 100%;
    z-index: 0;
        overflow: hidden;
     }

     #homepageRightImg {
        position: absolute;
        top:0;
        right: 0;
        left: 50%;
        width: 50%;
        height: 100%;
        overflow: hidden;
    }

     #homepageLeftNav {
        position: absolute;
        left: 0;
        right: 50%;
        width: 50%;
        z-index: 3;
        cursor: pointer;
    height: 100%;
    }

   #homepageRightNav {
        position: absolute;
        right: 0;
        left: 50%;
        width: 50%;
        z-index: 3;
        cursor: pointer;
    height: 100%;
   }

.homepageTitle {
        cursor: default;
        width: 100%;
        margin: 0 auto;
        text-align: center;
    position: absolute;
    height: 100%;
    top: 100%;
     }
   .homepageNavLink{}

    #homepageLeftMessage {
    z-index: 100;
    height: 100px;
    width: 100px;
     }

     #homepageLeftMessage #subLogo {
    z-index: 100;
    }

    @media only screen and (max-width : 480px) {
     #homepageLeftImg {
    display:block;
     }

   #homepageRightImg {
    display:block;
    }
}

Body:
Added an example how to use css other than position elements.

body,
html {
  margin: 0px;
  padding: 0px;
  height: 100%;
}

ul {
  margin: 0px;
  padding: 0px;
}

li {
  list-style: none;
  margin: 0px;
  padding: 0px;
}

#homepageLeftImg,
#homepageRightImg {
  float: left;
  /* Keeps both the div to align side by side to each other */
  width: 50%;
  /* 50% width to both equates to 100% */
  height: 100%;
}

#homepageLeftImg li,
#homepageRightImg li {
  width: 100%;
  height: 100%;
  float: left;
}

#homepageLeftImg li img,
#homepageRightImg li img {
  width: 100%;
  height: 100%;
}

@media (max-width:480px) {
  #homepageLeftImg,
  #homepageRightImg {
    width: 100%;
    /* Below 480px the width will be 100% and the images will come in stakced view. */
  }
}

<ul id="homepageLeftImg" class="homepageCol">
  <li><img src="https://dummyimage.com/400x800/red/fff&text=This+is+Dummy+left+Image"></li>

</ul>

<ul id="homepageRightImg" class="homepageCol">
  <li><img src="https://dummyimage.com/400x800/blue/fff&text=This+is+Dummy+right+Image"></li>
</ul>

You are missing the width:100% and also add top:100% to the #homepageRightImg

Add the following css in your media query:

@media only screen and (max-width : 480px) {
     #homepageLeftImg {
    display:block;
width:100%;
     }

   #homepageRightImg {
    display:block;
width:100%; top:100%:
    }
}

Also seeing your css code I see a lot poisition:absolute elements.
I suggest not to use position:absolute on every element as it destroys the structure.


问:
Why do we need to pass LPCTSTR lpParameters with ShellExecute
Shell Execute has the following signature :

```<code>HINSTANCE ShellExecute(
  __in_opt  HWND hwnd,
  __in_opt  LPCTSTR lpOperation,
  __in      LPCTSTR lpFile,
  __in_opt  LPCTSTR lpParameters,
  __in_opt  LPCTSTR lpDirectory,
  __in      INT nShowCmd
);
</code>```

How can we use lpParameters , Can we handle the parameter in my application. I am executing my app as below:

```<code>HINSTANCE hShellExecuteStatus = ShellExecute(NULL, "open", "MyPath/MyApp.EXE", NULL, NULL, SW_SHOWNORMAL);
</code>```

Can I pass something in the 4th parameter i.e: lpParameters , so that I can handle this with MyApp.Exe , let's say if I am passing "Hi: in the 4th param:

```<code>HINSTANCE hShellExecuteStatus = ShellExecute(NULL, "open", "MyPath/MyApp.EXE", "Hi", NULL, SW_SHOWNORMAL);
</code>```

Can I check in my application whether it is hi and display a message high.

I tried with POSTMESSAGE , but is not helpful with shellexecute

答: lpParameters will come through in the command line. Use GetCommandLine() to see it.

ContentLicense: CC BY-SA 2.5

Body:
Shell Execute has the following signature :

HINSTANCE ShellExecute(
  __in_opt  HWND hwnd,
  __in_opt  LPCTSTR lpOperation,
  __in      LPCTSTR lpFile,
  __in_opt  LPCTSTR lpParameters,
  __in_opt  LPCTSTR lpDirectory,
  __in      INT nShowCmd
);

How can we use lpParameters , Can we handle the parameter in my application. I am executing my app as below:

HINSTANCE hShellExecuteStatus = ShellExecute(NULL, "open", "MyPath/MyApp.EXE", NULL, NULL, SW_SHOWNORMAL);

Can I pass something in the 4th parameter i.e: lpParameters , so that I can handle this with MyApp.Exe , let's say if I am passing "Hi: in the 4th param:

HINSTANCE hShellExecuteStatus = ShellExecute(NULL, "open", "MyPath/MyApp.EXE", "Hi", NULL, SW_SHOWNORMAL);

Can I check in my application whether it is hi and display a message high.

I tried with POSTMESSAGE , but is not helpful with shellexecute


问:
PowerBuilder Tabpage
I have a Tabpage (tab_1) in PowerBuilder, What I want to do is Insert a Tab Page in that (tab_1) whenever I click a button. It will insert tab pages thru coding. I want to replicate whatever (Right Click Insert Tab page does...) Any help? thanks.</p>

答:
To create tabpage dynamically, you can use any of the following method.

tabcontrolname.OpenTab ( userobjectvar, userobjecttype, index )

tabcontrolname.OpenTabWithParm ( userobjectvar, parameter, index )

Please Refer :
http://infocenter-archive.sybase.com/help/index.jsp?topic=/com.sybase.dc37781_1150/html/psref/CAIDCDGJ.htm

Title: PowerBuilder Tabpage


问:
Django test fail at postgres hstore migration
I am using postgres with my django app and I had manually created the hstore extension in the database. But, when I run tests it tries to create a new database and fails when the hstore extension is not found.

I am getting the following errors:

```<code>django.db.utils.ProgrammingError: hstore type not found in the database. please install it from your 'contrib/hstore.sql' file
</code>```

I have update my migrations as per this post and it's as follows:

```<code># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings
from django.contrib.postgres.operations import HStoreExtension
import django.contrib.postgres.fields
import django.contrib.postgres.fields.hstore

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        HStoreExtension(),
        migrations.CreateModel(
        name='AppUser',
        fields=[
            ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),
            ('created_date', models.DateTimeField(auto_now_add=True)),
            ('modified_date', models.DateTimeField(auto_now=True)),
            ('lock', models.BooleanField(default=False)),
            ('username', models.CharField(max_length=100)),
            ('email', models.EmailField(max_length=150)),
            ('social_data', django.contrib.postgres.fields.hstore.HStoreField(blank=True, default='')),
            ('phone_number', models.CharField(max_length=15)),
            ('photo', models.URLField(blank=True)),
            ('gender', models.TextField(max_length=6)),
            ('badges', django.contrib.postgres.fields.ArrayField(size=None, base_field=models.CharField(max_length=30))),
        ],
        options={
            'abstract': False,
        },
    ),
    ]
</code>```

答:
The following steps will help you to create  hstore extension.

$ sudo su - postgres

$ psql

$ \c data_base_name

$ CREATE EXTENSION hstore;

It's worked for me.

Body:
I am using postgres with my django app and I had manually created the hstore extension in the database. But, when I run tests it tries to create a new database and fails when the hstore extension is not found.

I am getting the following errors:

django.db.utils.ProgrammingError: hstore type not found in the database. please install it from your 'contrib/hstore.sql' file

I have update my migrations as per this post and it's as follows:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings
from django.contrib.postgres.operations import HStoreExtension
import django.contrib.postgres.fields
import django.contrib.postgres.fields.hstore

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        HStoreExtension(),
        migrations.CreateModel(
        name='AppUser',
        fields=[
            ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),
            ('created_date', models.DateTimeField(auto_now_add=True)),
            ('modified_date', models.DateTimeField(auto_now=True)),
            ('lock', models.BooleanField(default=False)),
            ('username', models.CharField(max_length=100)),
            ('email', models.EmailField(max_length=150)),
            ('social_data', django.contrib.postgres.fields.hstore.HStoreField(blank=True, default='')),
            ('phone_number', models.CharField(max_length=15)),
            ('photo', models.URLField(blank=True)),
            ('gender', models.TextField(max_length=6)),
            ('badges', django.contrib.postgres.fields.ArrayField(size=None, base_field=models.CharField(max_length=30))),
        ],
        options={
            'abstract': False,
        },
    ),
    ]


问:
Swift Wait for Callback to finish before method return
I'm using Siesta REST API client for swift. I'm logging into an external API (successfully) and get the result from the siesta request object. The request has two callbacks - onSuccess and onFailure.

If the login was successful I set a token in the keychain and then return the result to the view controller - which segues to a new view controller if successful.

However, as I'm assuming the callback is used asynchronously, my function is not returning the correct result.

```<code> @IBAction func normalLoginButton(_ sender: UIButton) {

    //do normal login
    let standardLogin = StandardLogin()
    let credentials = ["email" : "john@example.com", "password": "password" ]
    let loginResult = standardLogin.login(params: credentials)
    print(loginResult)
    if loginResult {
        performSegue(withIdentifier: "showSuccessfulLoginView", sender: self)
    }

 }

 func login(params : Dictionary<String,String>) -> Bool{
    var loginSuccess = false
    let loginRequest = wrApi.makePostRequest(route: "login", params:params)

    loginRequest
        .onSuccess { data in
            print("succes")
            self.setJwtToken(jsonData: data.content)
            loginSuccess = true
        }
        .onFailure { error in print("an error occured")
    }

    return loginSuccess

}
</code>```

My question is basically how do I wait for the callback to finish before returning my loginSuccess Boolean?

I'm pretty new to swift, so any help would be appreciated.

答:
As @Nguyen points out, you can't return an immediate value from an async function.  Given that all you're doing with the return value is performing your segue - just move that call into the completion handler</p>

```<code>@IBAction func normalLoginButton(_ sender: UIButton) {
    //do normal login
    let standardLogin = StandardLogin()
    let credentials = ["email" : "john@example.com", "password": "password" ]
    standardLogin.login(params: credentials)
}

func login(params : Dictionary<String,String>){
    let loginRequest = wrApi.makePostRequest(route: "login", params:params)

    loginRequest
        .onSuccess { data in
            print("success")
            self.setJwtToken(jsonData: data.content)
            performSegue(withIdentifier: "showSuccessfulLoginView", sender: self)
    }
        .onFailure { error in print("an error occured")
    }
}
</code>```

Body:
I'm using Siesta REST API client for swift. I'm logging into an external API (successfully) and get the result from the siesta request object. The request has two callbacks - onSuccess and onFailure.

If the login was successful I set a token in the keychain and then return the result to the view controller - which segues to a new view controller if successful.

However, as I'm assuming the callback is used asynchronously, my function is not returning the correct result.

 @IBAction func normalLoginButton(_ sender: UIButton) {

    //do normal login
    let standardLogin = StandardLogin()
    let credentials = ["email" : "john@example.com", "password": "password" ]
    let loginResult = standardLogin.login(params: credentials)
    print(loginResult)
    if loginResult {
        performSegue(withIdentifier: "showSuccessfulLoginView", sender: self)
    }

 }

 func login(params : Dictionary<String,String>) -> Bool{
    var loginSuccess = false
    let loginRequest = wrApi.makePostRequest(route: "login", params:params)

    loginRequest
        .onSuccess { data in
            print("succes")
            self.setJwtToken(jsonData: data.content)
            loginSuccess = true
        }
        .onFailure { error in print("an error occured")
    }

    return loginSuccess

}

My question is basically how do I wait for the callback to finish before returning my loginSuccess Boolean?

I'm pretty new to swift, so any help would be appreciated.

Body:
As @Nguyen points out, you can't return an immediate value from an async function.  Given that all you're doing with the return value is performing your segue - just move that call into the completion handler

@IBAction func normalLoginButton(_ sender: UIButton) {
    //do normal login
    let standardLogin = StandardLogin()
    let credentials = ["email" : "john@example.com", "password": "password" ]
    standardLogin.login(params: credentials)
}

func login(params : Dictionary<String,String>){
    let loginRequest = wrApi.makePostRequest(route: "login", params:params)

    loginRequest
        .onSuccess { data in
            print("success")
            self.setJwtToken(jsonData: data.content)
            performSegue(withIdentifier: "showSuccessfulLoginView", sender: self)
    }
        .onFailure { error in print("an error occured")
    }
}


问:
How to update id set from 1?
I have an id i.e primary key and auto increment. Is there any query to update my existing id and make my id start from 1 and next id 2 and so on..

For example

```<code>id  name
3   ABC
5   XYZ
9   PQR
</code>```

NOTE: id is already primary and auto increment and I don't want truncate my id.

if possible i want to get

```<code>id  name
1   ABC
2   XYZ
3   PQR
</code>```

ALTER TABLE table AUTO_INCREMENT = 1; is not my solution.

Thanks

答:
Of course there is a way:

```<code>set @counter = 0;
update table_name
set id  = (@counter := @counter + 1);
</code>```

EDIT

To avoid problem with duplicate keys you can run something like this before to temporary change current ids to negative equivalents:

```<code>update table_name
set id  = 0 - id;
</code>```

Title: How to update id set from 1?

Body:
I have an id i.e primary key and auto increment. Is there any query to update my existing id and make my id start from 1 and next id 2 and so on..

For example

id  name
3   ABC
5   XYZ
9   PQR

NOTE: id is already primary and auto increment and I don't want truncate my id.

if possible i want to get

id  name
1   ABC
2   XYZ
3   PQR

ALTER TABLE table AUTO_INCREMENT = 1; is not my solution.

Thanks

Body:
Of course there is a way:

set @counter = 0;
update table_name
set id  = (@counter := @counter + 1);

EDIT

To avoid problem with duplicate keys you can run something like this before to temporary change current ids to negative equivalents:

update table_name
set id  = 0 - id;


问:
Help for Mapping JSON Twitter answer to Jaxb with Jettison
I'm a bit new to use JSON format manipulation and not very experimented in JAXB either.
What I try to do is building a small client to launch search on Twitter. My starting framework is JBoss RESTEasy (JAX-RS implementation) that provides an elegant way to consume Rest services JSON services by mapping JSON to JAXB thru Jettison framework (it works also in the other way if you want to provide REST service and produce JSON from JAXB).

So I launch a simple request to Twitter :

```<code>http://search.twitter.com/search.json?q=java
</code>```

And the answer comes in the following JSON format

```<code>{
"results":
[
  {"from_user_id_str":"67875385",
  "profile_image_url":"http://a2.twimg.com/axt_normal.png",
  "created_at":"Sun, 28 Nov 2010 22:38:39 +0000",
  "from_user":"extant",
  "id_str":"9013327095136256",
  "metadata":{"result_type":"recent"},
  "to_user_id":null,
  "text": "New blog post: No fancy swap in java",
  "id":9013327095136256,
  "from_user_id":67875385,
  "geo":null,
  "iso_language_code":"en",
  "to_user_id_str":null,
  "source":"wordpress"
  },
  <more tweets...>
],
"max_id":9013327095136256,
"since_id":0,
"refresh_url":"?since_id=9013327095136256&q=java",
"next_page":"?page=2&max_id=9013327095136256&q=java",
"results_per_page":15,
"page":1,"completed_in":0.020154,
"since_id_str":"0",
"max_id_str":"9013327095136256",
"query":"java"
}
</code>```

So I created two classes to map this answer

```<code>@BadgerFish
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class SearchResults {
 @XmlElement
 public List<Tweet> results;
 @XmlElement(name = "max_id")
 public long maxId;
 @XmlElement(name = "since_id")
 public long sinceId;
}
</code>```

and

```<code>@BadgerFish
@XmlRootElement(name="tweet")
public class Tweet {

 @XmlElement(name = "id")
 public long id;

 @XmlElement(name = "text")
 public String text;

 @XmlElement(name = "created_at")
 public Date createdAt;

 @XmlElement(name = "from_user")
 public String fromUser;

 @XmlElement(name = "profile_image_url")
 public String profileImageUrl;

 @XmlElement(name = "to_user_id")
 public Long toUserId;

 @XmlElement(name = "from_user_id")
 public long fromUserId;

 @XmlElement(name = "language_code")
 public String languageCode;

 @XmlElement(name = "source")
 public String source;

}
</code>```

My Twitter RESTEasy client is a simple interface

```<code>public interface TwitterResource {
 @Path("/search.json")
 @Consumes("application/*+json")
 @GET
 SearchResults search(@QueryParam("q")String query);
}
</code>```

Which is exploited with the following RESTEasy code :

```<code>...
TwitterResource tr = ProxyFactory.create(TwitterResource.class, "http://search.twitter.com");
SearchResults sr = tr.search("java");
...
</code>```

This code give the following Exception :

```<code>Exception in thread "main" org.jboss.resteasy.plugins.providers.jaxb.JAXBUnmarshalException: javax.xml.bind.JAXBException
 - with linked exception:
[org.codehaus.jettison.json.JSONException: JSONObject["results"] is not a JSONObject.]
 at org.jboss.resteasy.plugins.providers.jaxb.AbstractJAXBProvider.readFrom(AbstractJAXBProvider.java:86)
</code>```

I assume it comes from a wrong JAXB mapping on SearchResults class but can't figure how to correct it (and it's complicated with the JSON translation to XML). Any clue to correct it would be great.

Thanks in advance

答:
Ok, no solution found with Jettison (I'm convinced it's a bug) and JAXB mapping for JSON. But as RESTEasy support also the Jackson Framework, I switched to Jackson and everything thing is ok now.

In fact I find more clean to avoid this JSON to JAXB translation my first solution was using.

Thanks myself ;-)

Body:
I'm a bit new to use JSON format manipulation and not very experimented in JAXB either.
What I try to do is building a small client to launch search on Twitter. My starting framework is JBoss RESTEasy (JAX-RS implementation) that provides an elegant way to consume Rest services JSON services by mapping JSON to JAXB thru Jettison framework (it works also in the other way if you want to provide REST service and produce JSON from JAXB).

So I launch a simple request to Twitter :

http://search.twitter.com/search.json?q=java

And the answer comes in the following JSON format

{
"results":
[
  {"from_user_id_str":"67875385",
  "profile_image_url":"http://a2.twimg.com/axt_normal.png",
  "created_at":"Sun, 28 Nov 2010 22:38:39 +0000",
  "from_user":"extant",
  "id_str":"9013327095136256",
  "metadata":{"result_type":"recent"},
  "to_user_id":null,
  "text": "New blog post: No fancy swap in java",
  "id":9013327095136256,
  "from_user_id":67875385,
  "geo":null,
  "iso_language_code":"en",
  "to_user_id_str":null,
  "source":"wordpress"
  },
  <more tweets...>
],
"max_id":9013327095136256,
"since_id":0,
"refresh_url":"?since_id=9013327095136256&q=java",
"next_page":"?page=2&max_id=9013327095136256&q=java",
"results_per_page":15,
"page":1,"completed_in":0.020154,
"since_id_str":"0",
"max_id_str":"9013327095136256",
"query":"java"
}

So I created two classes to map this answer

@BadgerFish
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class SearchResults {
 @XmlElement
 public List<Tweet> results;
 @XmlElement(name = "max_id")
 public long maxId;
 @XmlElement(name = "since_id")
 public long sinceId;
}

and

@BadgerFish
@XmlRootElement(name="tweet")
public class Tweet {

 @XmlElement(name = "id")
 public long id;

 @XmlElement(name = "text")
 public String text;

 @XmlElement(name = "created_at")
 public Date createdAt;

 @XmlElement(name = "from_user")
 public String fromUser;

 @XmlElement(name = "profile_image_url")
 public String profileImageUrl;

 @XmlElement(name = "to_user_id")
 public Long toUserId;

 @XmlElement(name = "from_user_id")
 public long fromUserId;

 @XmlElement(name = "language_code")
 public String languageCode;

 @XmlElement(name = "source")
 public String source;

}

My Twitter RESTEasy client is a simple interface

public interface TwitterResource {
 @Path("/search.json")
 @Consumes("application/*+json")
 @GET
 SearchResults search(@QueryParam("q")String query);
}

Which is exploited with the following RESTEasy code :

...
TwitterResource tr = ProxyFactory.create(TwitterResource.class, "http://search.twitter.com");
SearchResults sr = tr.search("java");
...

This code give the following Exception :

Exception in thread "main" org.jboss.resteasy.plugins.providers.jaxb.JAXBUnmarshalException: javax.xml.bind.JAXBException
 - with linked exception:
[org.codehaus.jettison.json.JSONException: JSONObject["results"] is not a JSONObject.]
 at org.jboss.resteasy.plugins.providers.jaxb.AbstractJAXBProvider.readFrom(AbstractJAXBProvider.java:86)

I assume it comes from a wrong JAXB mapping on SearchResults class but can't figure how to correct it (and it's complicated with the JSON translation to XML). Any clue to correct it would be great.

Thanks in advance


问:
Will this remove, and only remove, selection keys which are ready to read data?
In my program, I want to ensure last messages from my server are sent letting the clients know a shutdown was initiated, so I want to prevent more commands being accepted while allowing the selector loop to continue till all messages are finished sending.

To this end, I want to be able to deregister all keys allowing input from the clients, will this work as intended?

```<code>if (Thread.currentThread().isInterrupted()) {
    for (SelectionKey key : sel.keys()) {
        if (key.interestOps() == SelectionKey.OP_READ) {
            key.cancel();
        }
    }
}
</code>```

Many thanks for any help, much appreciated!

答:
In my program, I want to ensure last messages from my server are sent letting the clients know a shutdown was initiated, so I want to prevent more commands being accepted while allowing the selector loop to continue till all messages are finished sending.

To this end, I want to be able to deregister all keys allowing input from the clients, will this work as intended?

No. It won't send anything on the wire to the clients, and it will prevent you detecting futher read events on the channels, so they will just sit there open indefinitely.

You need to either close those channels, which seems the most obvious solution, unless you have pending output or at least shutdown the associated socket for input.

But this is a very strange requirement. The clients shouldn't be sending new requests while prior responses are still pending. The application protocol should take care of this, not fiddling around with sockets.

Body:
In my program, I want to ensure last messages from my server are sent letting the clients know a shutdown was initiated, so I want to prevent more commands being accepted while allowing the selector loop to continue till all messages are finished sending.

To this end, I want to be able to deregister all keys allowing input from the clients, will this work as intended?

if (Thread.currentThread().isInterrupted()) {
    for (SelectionKey key : sel.keys()) {
        if (key.interestOps() == SelectionKey.OP_READ) {
            key.cancel();
        }
    }
}

Many thanks for any help, much appreciated!


问:
Check parameter in Lambda Expression
I have this code:

```<code> Function<Integer, String> converter = (num) -> Integer.toString(num);
</code>```

As I see here the "num" is the parameter of the function, however, if my user accidentally input a float, there will be error.
I only create the "num" parameter in the Function code?
How can I add an exception like if(!(num instanceOf Integer)) {//throw exception}.

答:
The declaration

```<code>Function<Integer, String> converter = num -> Integer.toString(num);
</code>```

is just a short-hand for

```<code>Function<Integer, String> converter = (Integer num) -> Integer.toString(num);
</code>```

letting the compiler infer the type of num, using the target type Function<Integer, String>. While Function is a generic interface whose type arguments could be ignored using an unchecked operation, the formal parameter of the lambda expression has the specified type which can’t be tainted. I.e.

```<code>((Function)converter).apply(1f); // should raise "unchecked" warning
</code>```

will throw java.lang.ClassCastException: java.lang.Float cannot be cast to java.lang.Integer, before even entering the code of your lambda expression.

It’s like you had written

```<code>Function<Integer, String> converter = MyClass::myLambdaCode;
…
private static String myLambdaCode(Integer num) {
    return Integer.toString(num);
}
</code>```

just more concise. But technically, it’s the same. It is impossible to enter the code with an object that is not an instance of Integer. Checking whether num is something other than an Integer has no point. It always is (unless null). If it is null, a NullPointerException would be thrown by Integer.toString(num) anyway, so checking that beforehand, just to do the same, i.e. throw an exception, is obsolete.

Title: Check parameter in Lambda Expression

Body:
I have this code:

 Function<Integer, String> converter = (num) -> Integer.toString(num);

As I see here the "num" is the parameter of the function, however, if my user accidentally input a float, there will be error.
I only create the "num" parameter in the Function code?
How can I add an exception like if(!(num instanceOf Integer)) {//throw exception}.

Body:
The declaration

Function<Integer, String> converter = num -> Integer.toString(num);

is just a short-hand for

Function<Integer, String> converter = (Integer num) -> Integer.toString(num);

letting the compiler infer the type of num, using the target type Function<Integer, String>. While Function is a generic interface whose type arguments could be ignored using an unchecked operation, the formal parameter of the lambda expression has the specified type which can’t be tainted. I.e.

((Function)converter).apply(1f); // should raise "unchecked" warning

will throw java.lang.ClassCastException: java.lang.Float cannot be cast to java.lang.Integer, before even entering the code of your lambda expression.

It’s like you had written

Function<Integer, String> converter = MyClass::myLambdaCode;
…
private static String myLambdaCode(Integer num) {
    return Integer.toString(num);
}

just more concise. But technically, it’s the same. It is impossible to enter the code with an object that is not an instance of Integer. Checking whether num is something other than an Integer has no point. It always is (unless null). If it is null, a NullPointerException would be thrown by Integer.toString(num) anyway, so checking that beforehand, just to do the same, i.e. throw an exception, is obsolete.


问:
I want to create a label which keeps track of how many times a view controller has been visited
I have a table view cell that performs a segue. Now my question is:

I want to put a label that counts how many times a particular view controller has been visited/viewed. Is there anything that we can do to when we click a table cell which performs a segue to another view controller and label in another view controller increments like:
Visited 1 times,
Visited 2 times,
Visited 3 times.

I did not implement this basic thing, I have something like

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let val2 = mySongsArray[indexPath.row] performSegue(withIdentifier: "JustinTableViewCell" , sender: val2)
}
</code>```

I am using Swift 3.

答:
In your table view controller, you can create counter variables or properties to count the number of time of user tapped the same cell if I correctly understood what you want to achieve.

Notice that I didn't use the phrase the same view controller is because let's say, you click on cell A and went to view controller A, and you come back to table view controller, you click on cell A again, the new view controller is not the view controller you just visited any more. The old vc has gone already.

So if you really want to count the number of time that user visited that particular view controller, put a counter in that view controller's viewDidLoad method and update it in viewDidAppear

if you just want to count the number of time the user entered by tapping that particular cell. count it in your table view controller. update the corresponding counter in didSelectRowAtIndexPath part

Body:
I have a table view cell that performs a segue. Now my question is:

I want to put a label that counts how many times a particular view controller has been visited/viewed. Is there anything that we can do to when we click a table cell which performs a segue to another view controller and label in another view controller increments like:
Visited 1 times,
Visited 2 times,
Visited 3 times.

I did not implement this basic thing, I have something like

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let val2 = mySongsArray[indexPath.row] performSegue(withIdentifier: "JustinTableViewCell" , sender: val2)
}

I am using Swift 3.


问:
Automatic Step over
I have been getting this error message when I step into some methods

```Do you want to continue being notified when an Automatic step over occurs?```

I usually answer Yes and I get taken to the line I want to step to.

However, I just pressed No (cause I was tired of the dialog box always popping up).  When I did that it skipped a lot of code I wanted to step through.  Now when I step into my method it is skipping my method (and jumping to the finally block because the method I am trying to step into is throwing an exception).

How can I change my answer back to Yes?

I would prefer it never ask me (default showing the code), but if faced with the choice of it skipping the code I need to see, or having a NagBox, I will take the NagBox.

答: Uncheck Tools + Options, Debugger, "Step over properties and operators" and that will fix this issue.</p>

Title: Automatic Step over

Body:
I have been getting this error message when I step into some methods

Do you want to continue being notified when an Automatic step over occurs?

I usually answer Yes and I get taken to the line I want to step to.

However, I just pressed No (cause I was tired of the dialog box always popping up).  When I did that it skipped a lot of code I wanted to step through.  Now when I step into my method it is skipping my method (and jumping to the finally block because the method I am trying to step into is throwing an exception).

How can I change my answer back to Yes?

I would prefer it never ask me (default showing the code), but if faced with the choice of it skipping the code I need to see, or having a NagBox, I will take the NagBox.


问:
How to avoid to enter repeated number in input text form?
I'm trying past few days to solve input number form validation in javascript. The logic user doesn't allow to enter repeated same number like "00000000000", "11111111111". If they enter numbers on text field i have to show error message,

sample code,

```<code>var mobNumber = $('#phNo').val();

if(mobNumber.match("00000000") || mobNumber.match("1111111")) {
  alert('Please enter valid phone number');
}
</code>```

答:
try this :

```<code>var checkPhone = function() {
  phone_number = $('#phone').val();
  res = (/^(.)\1+$/.test(phone_number) ? '1' : '0');
  if(res == '1'){
    return 'bad phone number';
  } else {
    return 'good phone number';
  }
}
</code>```

Test it here : JSFIDDLE

Body:
I'm trying past few days to solve input number form validation in javascript. The logic user doesn't allow to enter repeated same number like "00000000000", "11111111111". If they enter numbers on text field i have to show error message,

sample code,

var mobNumber = $('#phNo').val();

if(mobNumber.match("00000000") || mobNumber.match("1111111")) {
  alert('Please enter valid phone number');
}

Body:
try this :

var checkPhone = function() {
  phone_number = $('#phone').val();
  res = (/^(.)\1+$/.test(phone_number) ? '1' : '0');
  if(res == '1'){
    return 'bad phone number';
  } else {
    return 'good phone number';
  }
}

Test it here : JSFIDDLE


问:
Spark: how to parse empty string values as null in json
I have data that looks like this:

```<code>{"domain_userid":"a","g_id":"1"}
{"domain_userid":"b"}
{"domain_userid":"c","g_id":""}
</code>```

I'm loading this into a DataFrame with

```<code>spark.read.schema(myschema).json("/my/json")
</code>```

This results in a DataFrame like this:

```<code>+--------------------+--------+
|       domain_userid|g_id    |
+--------------------+--------+
|a                   | 1      |
|b                   | null   |
|c                   |        |
</code>```

What I'm looking for is

```<code>+--------------------+--------+
|       domain_userid|g_id    |
+--------------------+--------+
|a                   | 1      |
|b                   |    null|
|c                   |    null|
</code>```

I know I could write a udf to map empty strings to null, but my data has many columns (100+) so this seems like there could be a performance penalty because many tranformations are involved. Is there any flag/option on the json parser to just write null from the start?

答:
json file:

```<code>{"domain_userid":"","g_id":"1"}
{"domain_userid":"b"}
{"domain_userid":"c","g_id":""}
</code>```

try this:

```<code>df = spark.read.load('file:///home/zht/PycharmProjects/test/json_file.json', format='json')

myfunc = f.UserDefinedFunction(lambda *args: map(lambda x: None if x == '' else x, args),
                               returnType=ArrayType(StringType()))
cols = df.columns
df = df.select(myfunc(*cols)).rdd.flatMap(lambda x: x)
df = spark.createDataFrame(df, schema=cols)
df.show()
</code>```

and output:

```<code>+-------------+----+
|domain_userid|g_id|
+-------------+----+
|         null|   1|
|            b|null|
|            c|null|
+-------------+----+
</code>```

Body:
I have data that looks like this:

{"domain_userid":"a","g_id":"1"}
{"domain_userid":"b"}
{"domain_userid":"c","g_id":""}

I'm loading this into a DataFrame with

spark.read.schema(myschema).json("/my/json")

This results in a DataFrame like this:

+--------------------+--------+
|       domain_userid|g_id    |
+--------------------+--------+
|a                   | 1      |
|b                   | null   |
|c                   |        |

What I'm looking for is

+--------------------+--------+
|       domain_userid|g_id    |
+--------------------+--------+
|a                   | 1      |
|b                   |    null|
|c                   |    null|

I know I could write a udf to map empty strings to null, but my data has many columns (100+) so this seems like there could be a performance penalty because many tranformations are involved. Is there any flag/option on the json parser to just write null from the start?

Body:
json file:

{"domain_userid":"","g_id":"1"}
{"domain_userid":"b"}
{"domain_userid":"c","g_id":""}

try this:

df = spark.read.load('file:///home/zht/PycharmProjects/test/json_file.json', format='json')

myfunc = f.UserDefinedFunction(lambda *args: map(lambda x: None if x == '' else x, args),
                               returnType=ArrayType(StringType()))
cols = df.columns
df = df.select(myfunc(*cols)).rdd.flatMap(lambda x: x)
df = spark.createDataFrame(df, schema=cols)
df.show()

and output:

+-------------+----+
|domain_userid|g_id|
+-------------+----+
|         null|   1|
|            b|null|
|            c|null|
+-------------+----+


问:
Ng-repeat does'nt works with array in array
i'm new at ionic and i need to loop trough object with ng-repeat and i always get this error

Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: info in allInfos, Duplicate key: string:", Duplicate value:

"this is my arrays

Please help...

答:
The duplicate error occurs due to the duplicate in the value for the tack by expression. Its better to track by the $index in ng-repeat. Try this one.

```<code><div ng-repeat="item in Array track by $index">
    {{item}}
</div>
</code>```

Body:
The duplicate error occurs due to the duplicate in the value for the tack by expression. Its better to track by the $index in ng-repeat. Try this one.

<div ng-repeat="item in Array track by $index">
    {{item}}
</div>


问:
How to use existing C# code from C program
Is there a way I can develop a sample C# program, and make it a DLL, and use it in my C program?

Say, C# DLL has a function add(int a, int b) which returns or prints the result. I want to use this in my C program. Any example link should be a good help.

答:
The easiest way to do this is to expose the C# DLL as a COM object, and then create an instance of it from your C/C++ application. See MSDN for a step-by-step guide.

Alternatively, if it's actually a C++ application that you want to be able to call the C# DLL from, you could create a mixed-mode C++/CLI application, which contains both managed and unmanaged code. The C++ application can then call functions directly from the managed C# DLL.

Also see "An Overview of Managed/Unmanaged Code Interoperability" on MSDN.

EDIT: Without any more information than "it doesn't work in C," I don't even know which of the above suggestions that you tried. As I suggested, I'm not certain if the second will work with straight C (never tried it), but I see no reason why the first wouldn't.

Regardless, the quick and dirty fix might be to wrap the C# functions in a C++ DLL, which you then call from your C application. Make sure that you declare any of the functions that you want to export from the C++ DLL as extern, otherwise their names will be mangled C++ names, which are impossible to work with in C. See here for more information: http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html


问:
Convert array values to object keys
I do a get which returns me a json object like so:

"data": [
  [
    "2016 Pass/Fail Rates by Test Centre",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    ""
  ],
  [
    "",
    "Passes",
    "",
    "No ID",
    "",
    "Fails",
    "",
    "Fail Dangerous",
    "",
    "Total"
  ],
  [
    "Sometown",
    "8,725",
    "53.40%",
    "140",
    "0.90%",
    "7,417",
    "45.40%",
    "48",
    "0.30%",
    "16,330"
  ],
  [
    "Some Other Town",
    "12,778",
    "44.80%",
    "193",
    "0.70%",
    "15,422",
    "54.10%",
    "103",
    "0.40%",
    "28,496"
  ],
  [...many more identically formatted arrays...]
```
<p>and I would like to end up with:</p>
<pre class="lang-js prettyprint-override"><code>[{
    "Location": "Sometown",
    "Passes": 8,
    725,
    "Pass%": 53.40 % ,
    "No ID": 140,
    "NoID%": 0.90 % ,
    "Fails": 7,
    417,
    "Fail%": 45.40 % ,
    "Fail Dangerous": 48,
    "FailDangerous%": 0.30 % ,
    "Total": 16,
    330
  }, {
    "Location": "Some Other Town",
    "Passes": 8,
    725,
    etc etc...
</code>```

So I want to ignore the first array inside the "data" array, use the values of the second array as keys (and replace the empty strings with something more useful) and the values in all remaining arrays as values in the resulting object.

So it is quite the multipart problem, though I suspect a fairly simple one.  What is the simplest way to do that - and if different, what is the leanest way to do it in terms of processing/page load?

Thanks in advance,

答:
You could take the second array as keys for the wanted objects and iterate only the part after the keys. Then iterate the keys and build a new object for the values of the array. Return the object for mapping for a new array.

var data = { data: [["2016 Pass/Fail Rates by Test Centre", "", "", "", "", "", "", "", "", ""], ["Location", "Passes", "Passes%", "No ID", "No ID%", "Fails", "Fails%", "Fail Dangerous", "Fail Dangerous%", "Total"], ["Sometown", "8,725", "53.40%", "140", "0.90%", "7,417", "45.40%", "48", "0.30%", "16,330"], ["Some Other Town", "12,778", "44.80%", "193", "0.70%", "15,422", "54.10%", "103", "0.40%", "28,496"]] },
    keys = data.data[1],
    result = data.data.slice(2).map(function (a) {
        var temp = {};
        keys.forEach(function (k, i) {
            temp[k] = a[i];
        })
        return temp;
    });

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Convert array values to object keys

Body:
I do a get which returns me a json object like so:

"data": [
  [
    "2016 Pass/Fail Rates by Test Centre",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    ""
  ],
  [
    "",
    "Passes",
    "",
    "No ID",
    "",
    "Fails",
    "",
    "Fail Dangerous",
    "",
    "Total"
  ],
  [
    "Sometown",
    "8,725",
    "53.40%",
    "140",
    "0.90%",
    "7,417",
    "45.40%",
    "48",
    "0.30%",
    "16,330"
  ],
  [
    "Some Other Town",
    "12,778",
    "44.80%",
    "193",
    "0.70%",
    "15,422",
    "54.10%",
    "103",
    "0.40%",
    "28,496"
  ],
  [...many more identically formatted arrays...]

and I would like to end up with:

[{
    "Location": "Sometown",
    "Passes": 8,
    725,
    "Pass%": 53.40 % ,
    "No ID": 140,
    "NoID%": 0.90 % ,
    "Fails": 7,
    417,
    "Fail%": 45.40 % ,
    "Fail Dangerous": 48,
    "FailDangerous%": 0.30 % ,
    "Total": 16,
    330
  }, {
    "Location": "Some Other Town",
    "Passes": 8,
    725,
    etc etc...

So I want to ignore the first array inside the "data" array, use the values of the second array as keys (and replace the empty strings with something more useful) and the values in all remaining arrays as values in the resulting object.

So it is quite the multipart problem, though I suspect a fairly simple one.  What is the simplest way to do that - and if different, what is the leanest way to do it in terms of processing/page load?

Thanks in advance,

Body:
You could take the second array as keys for the wanted objects and iterate only the part after the keys. Then iterate the keys and build a new object for the values of the array. Return the object for mapping for a new array.

var data = { data: [["2016 Pass/Fail Rates by Test Centre", "", "", "", "", "", "", "", "", ""], ["Location", "Passes", "Passes%", "No ID", "No ID%", "Fails", "Fails%", "Fail Dangerous", "Fail Dangerous%", "Total"], ["Sometown", "8,725", "53.40%", "140", "0.90%", "7,417", "45.40%", "48", "0.30%", "16,330"], ["Some Other Town", "12,778", "44.80%", "193", "0.70%", "15,422", "54.10%", "103", "0.40%", "28,496"]] },
    keys = data.data[1],
    result = data.data.slice(2).map(function (a) {
        var temp = {};
        keys.forEach(function (k, i) {
            temp[k] = a[i];
        })
        return temp;
    });

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How control buttons on listview in android
I m in little problem
I add the buttons on listview but i can't add the listener on that buttons.i used the custom listview in which we give xml view to custom adapter and set that adapter on listview and this listview placed in another xml file.

if anyone add the buttons on listview and handle that buttons with listeners then please help me because my project is stop for this reason

答:
if you are using custom adapter, in that getview you can add listener for you button.<br>
Refer this question </p>

Body:
if you are using custom adapter, in that getview you can add listener for you button.

Refer this question


问:
Android paste large text file into edittext
I have an app and I need users to be able to paste any amount of text into an edittext box. I would like users to be able to paste up to at least 100,000 words if possible. How can I accomplish this with android? Attaching a file isn't possible.

Here is the xml for my edittext if that helps.

```<code>    <EditText
    android:id="@+id/editText"
    android:ems="10"
    android:inputType="textMultiLine"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:text=""
    android:minLines="2"
    android:textIsSelectable="true"
    android:isScrollContainer="true"
    android:focusable="true"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView2"

    />
</code>```

And if it helps this is all I am doing with the edit text

```<code>final EditText input = (EditText) findViewById(R.id.editText);
    button2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            document = input.getText().toString();
</code>```

答:
There is no defined limit for EditText.

You can only limit it manually (android:maxLength="10")

Body:
I have an app and I need users to be able to paste any amount of text into an edittext box. I would like users to be able to paste up to at least 100,000 words if possible. How can I accomplish this with android? Attaching a file isn't possible.

Here is the xml for my edittext if that helps.

    <EditText
    android:id="@+id/editText"
    android:ems="10"
    android:inputType="textMultiLine"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:text=""
    android:minLines="2"
    android:textIsSelectable="true"
    android:isScrollContainer="true"
    android:focusable="true"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView2"

    />

And if it helps this is all I am doing with the edit text

final EditText input = (EditText) findViewById(R.id.editText);
    button2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            document = input.getText().toString();


问:
List Comprehension that has more elements than array
I am trying to create an array with list comprehensions like:

```<code>array = [(x,y)|(x,y,z)<-oldArray, z == 10]
</code>```

Let's say that oldArray is a previously made array that has 3 Int values, but the new array I want to make only needs the first two, but whether or not they get added depends on a condition of the third.

I can't tell if this is working correctly or not though.

答:
I think what you really want to ask is how to debug a haskell program. For this case, just fire up ghci, and make your algorithm a little function, and play with it.

```<code>Prelude> let foo oldArray = [(x,y)|(x,y,z)<-oldArray, z == 10]
Prelude> foo [(1,2,3)]
[]
Prelude> foo [(1,2,10)]
[(1,2)]
Prelude> foo [(1,2,10),(3,4,5),(5,6,10)]
[(1,2),(5,6)]
</code>```

"Working properly" basically means what you really got is what you expected. As we can see, foo works fine.

Or we could just use some print in the source file, and see if the output  is expected.

For more, you can use ghci debugger, or Debug.Trace.

https://hackage.haskell.org/package/base-4.9.1.0/docs/Debug-Trace.html

https://wiki.haskell.org/Debugging

https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/ghci.html#the-ghci-debugger

Body:
I am trying to create an array with list comprehensions like:

array = [(x,y)|(x,y,z)<-oldArray, z == 10]

Let's say that oldArray is a previously made array that has 3 Int values, but the new array I want to make only needs the first two, but whether or not they get added depends on a condition of the third.

I can't tell if this is working correctly or not though.

Body:
I think what you really want to ask is how to debug a haskell program. For this case, just fire up ghci, and make your algorithm a little function, and play with it.

Prelude> let foo oldArray = [(x,y)|(x,y,z)<-oldArray, z == 10]
Prelude> foo [(1,2,3)]
[]
Prelude> foo [(1,2,10)]
[(1,2)]
Prelude> foo [(1,2,10),(3,4,5),(5,6,10)]
[(1,2),(5,6)]

"Working properly" basically means what you really got is what you expected. As we can see, foo works fine.

Or we could just use some print in the source file, and see if the output  is expected.

For more, you can use ghci debugger, or Debug.Trace.

https://hackage.haskell.org/package/base-4.9.1.0/docs/Debug-Trace.html

https://wiki.haskell.org/Debugging

https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/ghci.html#the-ghci-debugger


问:
Fill multidimesional array with values of another array in php
I've this array as query result:

```<code>[0]=>
array(2) {
["id_iscr"]=>
int(2)
["id_pettorina"]=>
NULL
}
[1]=>
array(2) {
["id_iscr"]=>
int(3)
["id_pettorina"]=>
NULL
}
[2]=>
array(2) {
["id_iscr"]=>
int(5)
["id_pettorina"]=>
NULL
}
[3]=>
array(2) {
["id_iscr"]=>
int(7)
["id_pettorina"]=>
NULL
}
...
</code>```

and this as array of distinct value

```<code>[0]=>
int(125)
[1]=>
int(162)
[2]=>
int(65)
[3]=>
int(98)
...
</code>```

Both array have same number of element;
my question is: in which way can I fill each NULL value of the first array with each value of the socond one and insert into mysql db?
Thanks in advance.

答:
@sihciv simply use if condition inside foreach() like below:</p>

```<code><?php
    $arr1 = array(
                array(
                    "id_iscr"=> 2,
                    "id_pettorina"=> NULL
                ),
                array(
                    "id_iscr"=> 3,
                    "id_pettorina"=> NULL
                ),
                array(
                    "id_iscr"=> 5,
                    "id_pettorina"=> NULL
                ),
                array(
                    "id_iscr"=> 7,
                    "id_pettorina"=> NULL
                )
            );
    echo "```";
    print_r($arr1); //array before
    $arr2 = array(125,162,65,98);
    $i = 0;
    foreach($arr1 as $key => $value){
        foreach ($value as $key1 => $value1) {
            if($value1 == null){
                if(isset($arr2[$i])){
                    $arr1[$key][$key1] = $arr2[$i];
                    $i++;
                }
            }
        }
    }
    echo "```";
    print_r($arr1); //array after
</code>```

Body:
I've this array as query result:

[0]=>
array(2) {
["id_iscr"]=>
int(2)
["id_pettorina"]=>
NULL
}
[1]=>
array(2) {
["id_iscr"]=>
int(3)
["id_pettorina"]=>
NULL
}
[2]=>
array(2) {
["id_iscr"]=>
int(5)
["id_pettorina"]=>
NULL
}
[3]=>
array(2) {
["id_iscr"]=>
int(7)
["id_pettorina"]=>
NULL
}
...

and this as array of distinct value

[0]=>
int(125)
[1]=>
int(162)
[2]=>
int(65)
[3]=>
int(98)
...

Both array have same number of element;
my question is: in which way can I fill each NULL value of the first array with each value of the socond one and insert into mysql db?
Thanks in advance.

Body:
@sihciv simply use if condition inside foreach() like below:

<?php
    $arr1 = array(
                array(
                    "id_iscr"=> 2,
                    "id_pettorina"=> NULL
                ),
                array(
                    "id_iscr"=> 3,
                    "id_pettorina"=> NULL
                ),
                array(
                    "id_iscr"=> 5,
                    "id_pettorina"=> NULL
                ),
                array(
                    "id_iscr"=> 7,
                    "id_pettorina"=> NULL
                )
            );
    echo "<pre>";
    print_r($arr1); //array before
    $arr2 = array(125,162,65,98);
    $i = 0;
    foreach($arr1 as $key => $value){
        foreach ($value as $key1 => $value1) {
            if($value1 == null){
                if(isset($arr2[$i])){
                    $arr1[$key][$key1] = $arr2[$i];
                    $i++;
                }
            }
        }
    }
    echo "<pre>";
    print_r($arr1); //array after


问:
How to display all available variants in python?
If I have this simple code, how can I display all available variants ?

```<code>#Display all possible variants until reach input sum with coins of 2 and 5
#Not fixed: Output only first result !

#Input
summ = int(input("Enter sum: "))
two = 2
five = 5

#Calculations/Checks/Output
for i in range(0, two+1):
    for j in range(0, five+1):
        if (i*2 + j*5 == summ):
            print(i, "*2 + ", j, "*5 = ", summ)

#End
</code>```

For example:

```<code>Input: 17

Output:
1*2 + 3*5 = 17
6*2 + 1*5 = 17
</code>```

But the code displays only the first result?

How can I fix this ?

答:
Change the inputs of range:

```<code>summ = int(input("Enter sum: "))
two = 2
five = 5

for i in range(summ//two+1):
    for j in range(summ//five+1):
        if (i*2 + j*5 == summ):
            print(i, "* 2 +", j, "* 5 =", summ)
</code>```

Body:
If I have this simple code, how can I display all available variants ?

#Display all possible variants until reach input sum with coins of 2 and 5
#Not fixed: Output only first result !

#Input
summ = int(input("Enter sum: "))
two = 2
five = 5

#Calculations/Checks/Output
for i in range(0, two+1):
    for j in range(0, five+1):
        if (i*2 + j*5 == summ):
            print(i, "*2 + ", j, "*5 = ", summ)

#End

For example:

Input: 17

Output:
1*2 + 3*5 = 17
6*2 + 1*5 = 17

But the code displays only the first result?

How can I fix this ?

Body:
Change the inputs of range:

summ = int(input("Enter sum: "))
two = 2
five = 5

for i in range(summ//two+1):
    for j in range(summ//five+1):
        if (i*2 + j*5 == summ):
            print(i, "* 2 +", j, "* 5 =", summ)


问:
Running a simple period task with celery
I can't seem to figure out how to get this working. I want to run a function every ten seconds

```<code>from __future__ import absolute_import, unicode_literals, print_function
from celery import Celery
import app as x # the library which hold the func i want to task

app = Celery(
    'myapp',
    broker='amqp://guest@localhost//',
)

app.conf.timezone = 'UTC'

@app.task
def shed_task():
    x.run()

@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    # Calls say('hello') every 10 seconds.
    sender.add_periodic_task(10.0, shed_task.s(), name='add every 10')

if __name__ == '__main__':
    app.start()
</code>```

Then when I run the script it just shows me a bunch of commands I can use with celery. How can I get this running ? Do I have to run it in command line or something ?

Additionally when I get it running will I be able to see a list of complete tasks along with any errors ?

答:
You can do it simply with python threading module like below</p>

```<code>import time, threading
def foo():
    print(time.ctime())
    threading.Timer(10, foo).start()

foo()
</code>```

Body:
I can't seem to figure out how to get this working. I want to run a function every ten seconds

from __future__ import absolute_import, unicode_literals, print_function
from celery import Celery
import app as x # the library which hold the func i want to task

app = Celery(
    'myapp',
    broker='amqp://guest@localhost//',
)

app.conf.timezone = 'UTC'

@app.task
def shed_task():
    x.run()

@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    # Calls say('hello') every 10 seconds.
    sender.add_periodic_task(10.0, shed_task.s(), name='add every 10')

if __name__ == '__main__':
    app.start()

Then when I run the script it just shows me a bunch of commands I can use with celery. How can I get this running ? Do I have to run it in command line or something ?

Additionally when I get it running will I be able to see a list of complete tasks along with any errors ?

Body:
You can do it simply with python threading module like below

import time, threading
def foo():
    print(time.ctime())
    threading.Timer(10, foo).start()

foo()


问:
Sending email alert from excel to Outlook
I am trying to send a test mail from excel to Outlook, However I am getting error message : Run Time Error 287 in the following line :

```<code>OutMail.Send
</code>```

Please find below my code:

```<code>Sub sendds()

    Dim OutMail As MailItem
    Dim outlookapp As Outlook.Application
     Dim myInspector As Outlook.Inspector

Set outlookapp = CreateObject("Outlook.application")
Set OutMail = outlookapp.CreateItem(olMailItem)

With OutMail

    .To = "email address"
    .Subject = "test mail"
    .Body = "Hi this is test email"

    OutMail.Send 'Getting error on this line

    End With

 Set outlookapp = Nothing
Set OutMail = Nothing

End Sub
</code>```

答:
That is because you have incorrect email or email address  format should be email@email.com or for testing purpose use .Display

Also change it to just .Send

```<code>   With OutMail
        .To = "email@address.com"
        .Subject = "test"
        .Body = "Hi this is test email"
        .Send
    End With
</code>```

**For workaround **

```<code>    With olMail
        .To = "email"
        .CC = ""
        .BCC = ""
        .Subject = ""
        .Display
        .Send
    End With
</code>```

Body:
I am trying to send a test mail from excel to Outlook, However I am getting error message : Run Time Error 287 in the following line :

OutMail.Send

Please find below my code:

Sub sendds()

    Dim OutMail As MailItem
    Dim outlookapp As Outlook.Application
     Dim myInspector As Outlook.Inspector

Set outlookapp = CreateObject("Outlook.application")
Set OutMail = outlookapp.CreateItem(olMailItem)

With OutMail

    .To = "email address"
    .Subject = "test mail"
    .Body = "Hi this is test email"

    OutMail.Send 'Getting error on this line

    End With

 Set outlookapp = Nothing
Set OutMail = Nothing

End Sub

Body:
That is because you have incorrect email or email address  format should be email@email.com or for testing purpose use .Display

Also change it to just .Send

   With OutMail
        .To = "email@address.com"
        .Subject = "test"
        .Body = "Hi this is test email"
        .Send
    End With

**For workaround **

    With olMail
        .To = "email"
        .CC = ""
        .BCC = ""
        .Subject = ""
        .Display
        .Send
    End With


问:
Zend Framework 1 - remote database connection via ssh tunnel
I want to connect to my customer remote database.

I'm able to establish ssh tunnel with command:

```<code>ssh -vvv -i path_to_private_key -L 3308:127.0.0.1:3307 ssh_user@ssh_host
</code>```

and connect to his database with:

```<code>mysql -u database_user -p -h 127.0.0.1 -P 3308
</code>```

But when I want to configure my zend framework project to read data from this database, nothing happen (even there is no logs in apache2 error logs)

Below my configurations from application.ini file:

```<code>resources.db.adapter = "mysqli"
resources.db.params.host = 127.0.0.1
resources.db.params.port = 3308

resources.db.params.dbname = database_name
resources.db.params.username = database_user
resources.db.params.password = database_password
resources.db.params.profiler = false
</code>```

I have no idea what could be wrong. Any ideas?

答: Unfortunately this is not solution for my problem. Last days turned out that it was problem on my customer side, with my command everything was fine.</p>

Body:
I want to connect to my customer remote database.

I'm able to establish ssh tunnel with command:

ssh -vvv -i path_to_private_key -L 3308:127.0.0.1:3307 ssh_user@ssh_host

and connect to his database with:

mysql -u database_user -p -h 127.0.0.1 -P 3308

But when I want to configure my zend framework project to read data from this database, nothing happen (even there is no logs in apache2 error logs)

Below my configurations from application.ini file:

resources.db.adapter = "mysqli"
resources.db.params.host = 127.0.0.1
resources.db.params.port = 3308

resources.db.params.dbname = database_name
resources.db.params.username = database_user
resources.db.params.password = database_password
resources.db.params.profiler = false

I have no idea what could be wrong. Any ideas?


问:
How do I pass a pointer to a structure in a function?
I wonder how to replace *Type  by ? What address has the structure inside?

```<code>//mycode.go

package main

import "fmt"

func out(k *Type) {
    fmt.Println(k)
}

func main() {

    type DataIP struct{ Title, Desc string }

    Data := DataIP{
        "Hello!",
        "Hello GO!",
    }
    out(&Data)
}
</code>```

答:
I am not sure to understand your question.

If you want out to work only with structs of type DataIP:

simply define DataIP outside of main and use the signature func out(k *DataIP).

if what you want is to be able to pass any type of structure to out:

In golang, this sort of generic methods can be implemented using the interface type. As this answer explains, an interface is a container with two words of data:

one word is used to point to a method table for the value’s underlying type,

and the other word is used to point to the actual data being held by that value.

An interface can hold anything and is often used as a function parameter to be able to process many sort of inputs.

In your case, you can do:

```<code>func out(k interface{}) {
    fmt.Println(k)
}
</code>```

This will print &{Hello! Hello GO!}. In case you want the & to disappear (i.e. you always pass it pointers), you can use the reflect package to "dereference" k:

```<code>func out(k interface{}) {
    fmt.Println(reflect.ValueOf(k).Elem())
}
</code>```

which yields {Hello! Hello GO!}

Here is a playground example.

if what you want is to print the address of Data:

you can use the %p pattern with fmt.Printf:

```<code>fmt.Printf("%p", &Data) // 0x1040a130
</code>```

Using the out function, you get:

```<code>func out(k interface{}) {
    fmt.Printf("%p\n", k)
}
</code>```

See this playground example

Body:
I wonder how to replace *Type  by ? What address has the structure inside?

//mycode.go

package main

import "fmt"

func out(k *Type) {
    fmt.Println(k)
}

func main() {

    type DataIP struct{ Title, Desc string }

    Data := DataIP{
        "Hello!",
        "Hello GO!",
    }
    out(&Data)
}

Body:
I am not sure to understand your question.

If you want out to work only with structs of type DataIP:

simply define DataIP outside of main and use the signature func out(k *DataIP).

if what you want is to be able to pass any type of structure to out:

In golang, this sort of generic methods can be implemented using the interface type. As this answer explains, an interface is a container with two words of data:

one word is used to point to a method table for the value’s underlying type,

and the other word is used to point to the actual data being held by that value.

An interface can hold anything and is often used as a function parameter to be able to process many sort of inputs.

In your case, you can do:

func out(k interface{}) {
    fmt.Println(k)
}

This will print &{Hello! Hello GO!}. In case you want the & to disappear (i.e. you always pass it pointers), you can use the reflect package to "dereference" k:

func out(k interface{}) {
    fmt.Println(reflect.ValueOf(k).Elem())
}

which yields {Hello! Hello GO!}

Here is a playground example.

if what you want is to print the address of Data:

you can use the %p pattern with fmt.Printf:

fmt.Printf("%p", &Data) // 0x1040a130

Using the out function, you get:

func out(k interface{}) {
    fmt.Printf("%p\n", k)
}

See this playground example


问:
Generate Password protected pdf rails
I am using wicked PDF for my PDF generation. Now I am looking something to Prevent someone to copy the data from my pdf .When anyone tries to copy some data it should ask for password or the person should not be able to copy the data from PDF .I have look so much on Internet but didn't got any solution so far .Can any one help me with this problem</p>

答:
You can use prawn for this: https://github.com/cortiz/prawn-rails

```<code>pdf = Prawn::Document.new

pdf.encrypt_document(
  user_password: 'foo',
  owner_password: 'bar',
  permissions: {
    print_document: false,
    modify_contents: false,
    copy_contents: false,
    modify_annotations: false
  }
)
</code>```

Check out http://prawnpdf.org/manual.pdf for more description and permissions.

And look through this example: http://code.runnable.com/Uo6huSS6Ut8nAAFm/how-to-password-protect-pdfs-with-prawn-for-ruby-on-rails

Title: Generate Password protected pdf rails

Body:
You can use prawn for this: https://github.com/cortiz/prawn-rails

pdf = Prawn::Document.new

pdf.encrypt_document(
  user_password: 'foo',
  owner_password: 'bar',
  permissions: {
    print_document: false,
    modify_contents: false,
    copy_contents: false,
    modify_annotations: false
  }
)

Check out http://prawnpdf.org/manual.pdf for more description and permissions.

And look through this example: http://code.runnable.com/Uo6huSS6Ut8nAAFm/how-to-password-protect-pdfs-with-prawn-for-ruby-on-rails