问:
REGEX for special character (Decode Unicode)
I have try this code to decode, unicode all works fine if the comment start with any special character, symbol, space and etc shows error. </p>

```<code>      CREATE TEMP FUNCTION DecodeUnicode(s STRING) AS (
      IF(s NOT LIKE '%\\u%', s,
      (SELECT CODE_POINTS_TO_STRING(ARRAY_AGG(CAST(CONCAT('0x', x) AS INT64)))
      FROM UNNEST(SPLIT(s, '\\u')) AS x
      WHERE x != ''))
      );

      SELECT
      original,
      DecodeUnicode(original) AS decoded
      FROM (
      SELECT trim(r'$-\u6599\u91d1\u304c\u9ad8\u3059\u304e\uff01\uff01\uff01') AS original UNION ALL
      SELECT trim(r'abcd')
      );
</code>```

答:
Below is for BigQuery Standard SQL   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
CREATE TEMP FUNCTION DecodeUnicode(s STRING) AS (
  (SELECT CODE_POINTS_TO_STRING(ARRAY_AGG(CAST(CONCAT('0x', x) AS INT64)))
  FROM UNNEST(SPLIT(s, '\\u')) AS x
  WHERE x != ''
  )
);
WITH `yourTable` AS (
  SELECT r'$-\u6599\u91d1\u304c\u9ad8\u3059\u304e\uff01\uff01\uff01' AS original UNION ALL
  SELECT r'abcd'
), uchars AS (
  SELECT DISTINCT
    c,
    DecodeUnicode(c) uchar
  FROM `yourTable`,
  UNNEST(REGEXP_EXTRACT_ALL(original, r'(\\u[abcdef0-9]{4})')) c
)
SELECT
  original,
  STRING_AGG(IFNULL(uchar, x), '' ORDER BY pos) decoded
FROM (
  SELECT
    original,
    pos,
    SUBSTR(original,
      SUM(CASE char WHEN '' THEN 1 ELSE 6 END)
        OVER(PARTITION BY original ORDER BY pos) - CASE char WHEN '' THEN 0 ELSE 5 END,
      CASE char WHEN '' THEN 1 ELSE 6 END) x,
    uchar
  FROM `yourTable`,
  UNNEST(REGEXP_EXTRACT_ALL(original, r'(\\u[abcdef0-9]{4})|.')) char WITH OFFSET AS pos
  LEFT JOIN uchars u ON u.c = char
)
GROUP BY original
-- ORDER BY original
</code>```

<p>What it does - it extracts all unicode characters and decode them and replace them in original string leaving non-unicodes stay as they are, so the output will be as below   </p>

<pre class="lang-sql prettyprint-override"><code>original                                                    decoded
$-\u6599\u91d1\u304c\u9ad8\u3059\u304e\uff01\uff01\uff01     $-料金が高すぎ！！！
abcd                                                        abcd
</code>```

Body:
I have try this code to decode, unicode all works fine if the comment start with any special character, symbol, space and etc shows error.

      CREATE TEMP FUNCTION DecodeUnicode(s STRING) AS (
      IF(s NOT LIKE '%\\u%', s,
      (SELECT CODE_POINTS_TO_STRING(ARRAY_AGG(CAST(CONCAT('0x', x) AS INT64)))
      FROM UNNEST(SPLIT(s, '\\u')) AS x
      WHERE x != ''))
      );

      SELECT
      original,
      DecodeUnicode(original) AS decoded
      FROM (
      SELECT trim(r'$-\u6599\u91d1\u304c\u9ad8\u3059\u304e\uff01\uff01\uff01') AS original UNION ALL
      SELECT trim(r'abcd')
      );

Body:
Below is for BigQuery Standard SQL

#standardSQL
CREATE TEMP FUNCTION DecodeUnicode(s STRING) AS (
  (SELECT CODE_POINTS_TO_STRING(ARRAY_AGG(CAST(CONCAT('0x', x) AS INT64)))
  FROM UNNEST(SPLIT(s, '\\u')) AS x
  WHERE x != ''
  )
);
WITH `yourTable` AS (
  SELECT r'$-\u6599\u91d1\u304c\u9ad8\u3059\u304e\uff01\uff01\uff01' AS original UNION ALL
  SELECT r'abcd'
), uchars AS (
  SELECT DISTINCT
    c,
    DecodeUnicode(c) uchar
  FROM `yourTable`,
  UNNEST(REGEXP_EXTRACT_ALL(original, r'(\\u[abcdef0-9]{4})')) c
)
SELECT
  original,
  STRING_AGG(IFNULL(uchar, x), '' ORDER BY pos) decoded
FROM (
  SELECT
    original,
    pos,
    SUBSTR(original,
      SUM(CASE char WHEN '' THEN 1 ELSE 6 END)
        OVER(PARTITION BY original ORDER BY pos) - CASE char WHEN '' THEN 0 ELSE 5 END,
      CASE char WHEN '' THEN 1 ELSE 6 END) x,
    uchar
  FROM `yourTable`,
  UNNEST(REGEXP_EXTRACT_ALL(original, r'(\\u[abcdef0-9]{4})|.')) char WITH OFFSET AS pos
  LEFT JOIN uchars u ON u.c = char
)
GROUP BY original
-- ORDER BY original

What it does - it extracts all unicode characters and decode them and replace them in original string leaving non-unicodes stay as they are, so the output will be as below

original                                                    decoded
$-\u6599\u91d1\u304c\u9ad8\u3059\u304e\uff01\uff01\uff01     $-料金が高すぎ！！！
abcd                                                        abcd


来源: stackexchange

问:
Xamarin.Forms Page.Width half of what it should be during SizeChanged
In my ContentPage (which takes up the whole screen), I'm setting the SizeChanged event as follows:

```<code>private void init()
{
    EventHandler orientation_update_handler = (object sender, System.EventArgs e) =>
    {
        var binding_context = BindingContext as MyViewModel;
        binding_context?.OnOrientationChanged(Width, Height, Scale);
    };
    SizeChanged += orientation_update_handler;
    orientation_update_handler.Invoke(null, null);
    // other event handler setup...
</code>```

Trying to set a breakpoint within orientation_update_handler but that's not getting hit...
Anyways; set a breakpoint in OnOrientationChanged. The width and height it's receiving are both half of what they actually are, and the scale always seems to be 1.

However, in my App delegate's FinishedLaunching function, while UIScreen.MainScreen.Bounds.Width always seems to be the same as ContentPage.Width, UIScreen.MainScreen.Scale on the other hand is different to ContentPage.Scale and multiplying UIScreen.MainScreen.Bounds.Width by UIScreen.MainScreen.Scale gives me the correct screen resolution of the device.

Why is ContentPage.Scale always 1? If it were the correct value, I could multiply by the width and get the correct screen resolution.

答:
Why is ContentPage.Scale always 1? If it were the correct value, I could multiply by the width and get the correct screen resolution.

This is a misconception. Width and height are not given in physical pixels, see here

Apple iPhone and iPad devices continue to work in units of points

and

Android is similar. Programmers work in units of density-independent pixels (dps)

in both systems 160 units equate to one inch (or 64 units translate to 1 cm).

ContentLicense: CC BY-SA 3.0

Body:
In my ContentPage (which takes up the whole screen), I'm setting the SizeChanged event as follows:

private void init()
{
    EventHandler orientation_update_handler = (object sender, System.EventArgs e) =>
    {
        var binding_context = BindingContext as MyViewModel;
        binding_context?.OnOrientationChanged(Width, Height, Scale);
    };
    SizeChanged += orientation_update_handler;
    orientation_update_handler.Invoke(null, null);
    // other event handler setup...

Trying to set a breakpoint within orientation_update_handler but that's not getting hit...
Anyways; set a breakpoint in OnOrientationChanged. The width and height it's receiving are both half of what they actually are, and the scale always seems to be 1.

However, in my App delegate's FinishedLaunching function, while UIScreen.MainScreen.Bounds.Width always seems to be the same as ContentPage.Width, UIScreen.MainScreen.Scale on the other hand is different to ContentPage.Scale and multiplying UIScreen.MainScreen.Bounds.Width by UIScreen.MainScreen.Scale gives me the correct screen resolution of the device.

Why is ContentPage.Scale always 1? If it were the correct value, I could multiply by the width and get the correct screen resolution.


问:
crop an image in react-native
User can move the crop functionalities according to their needs means downward,upward,left side or rightside may be.Anyone have any idea how to crop the image in react native,I want that image for scanning purpose.  </p>

答: You could use react-native-image-crop-picker</p>

Title: crop an image in react-native


问:
Storing Large Models Common Data between Different PHP Pages
Please tell me how to store common data like an arraylist of Sports Class
which will have different variables in it. I want to access that Arraylist from Vaious pages, so please tell me or send some link so that i will be able to do that.

I am new in PHP Progamming, but done sufficient amount of Web Programming in .Net.

Thanks in Advance.

答:
PHP isn't really stateful so you will load the class on each page you visit.  To store information in an instantiated class filled with data, you can either just store the data in the $_SESSION superglobal or serialize the data and then store it in a file.

see http://us2.php.net/manual/en/function.session-start.php and http://us2.php.net/manual/en/function.serialize.php

ContentLicense: CC BY-SA 2.5


问:
Not able to connect to Hipchat with errbot ? getting permission denied for socket .
While connect error bot with self hosted . Getting this error while doing it -

```<code>10:40:34 DEBUG    sleekxmpp.xmlstream.xmlst RECV: <proceed xmlns="urn:ietf:params:xml:ns:xmpp-tls" />
10:40:34 DEBUG    sleekxmpp.features.featur Starting TLS
10:40:34 INFO     sleekxmpp.xmlstream.xmlst Negotiating TLS
10:40:34 INFO     sleekxmpp.xmlstream.xmlst Using SSL version: TLSv1
10:40:34 DEBUG    sleekxmpp.xmlstream.xmlst Event triggered: socket_error
10:40:34 ERROR    sleekxmpp.xmlstream.xmlst **Socket Error #13: Permission denied**
10:40:34 DEBUG    sleekxmpp.xmlstream.xmlst reconnecting...
</code>```

This is config which i am using for same .

```<code>BACKEND = 'Hipchat'  # Errbot will start in text mode (console only mode) and will answer commands from there.

BOT_DATA_DIR = r'/Users/XXX/errbot/errbot/data'
BOT_EXTRA_PLUGIN_DIR = '/Users/XXXX/errbot/errbot/plugins'

BOT_LOG_FILE = r'/Users/XXXX/errbot/errbot/errbot.log'
BOT_LOG_LEVEL = logging.DEBUG

BOT_ADMINS = ('@XXXXX', )  # !! Don't leave that to "CHANGE ME" if you connect your errbot to a chat system !!

# The identity, or credentials, used to connect to a server
BOT_IDENTITY = {
    'username': 'XXXX',  # The JID of the user you have created for the bot
    'password': 'XXXXX',       # The corresponding password for this user
    'token': 'XXXXXX',
    'endpoint' : 'https://xxxx.xxxx.com',
}
</code>```

Can someone please let me know what i am doing wrong in above config ?

Or please also suggest any other bot (in python) that works with self hosted Hipchat .

答:
Hipchat Server removed external access to the XMPP ports on the 2.0.7  release, in favor of supporting only communication over port 443 (using XMPP's BOSH protocol).

Depending on your server version, you might be able to enable them back by running hipchat network --enable-xmpp-ports.

https://confluence.atlassian.com/hipchatkb/external-xmpp-ports-5222-5223-disabled-by-default-in-hipchat-server-2-0-7-859442760.html has more information on this topic.

Body:
While connect error bot with self hosted . Getting this error while doing it -

10:40:34 DEBUG    sleekxmpp.xmlstream.xmlst RECV: <proceed xmlns="urn:ietf:params:xml:ns:xmpp-tls" />
10:40:34 DEBUG    sleekxmpp.features.featur Starting TLS
10:40:34 INFO     sleekxmpp.xmlstream.xmlst Negotiating TLS
10:40:34 INFO     sleekxmpp.xmlstream.xmlst Using SSL version: TLSv1
10:40:34 DEBUG    sleekxmpp.xmlstream.xmlst Event triggered: socket_error
10:40:34 ERROR    sleekxmpp.xmlstream.xmlst **Socket Error #13: Permission denied**
10:40:34 DEBUG    sleekxmpp.xmlstream.xmlst reconnecting...

This is config which i am using for same .

BACKEND = 'Hipchat'  # Errbot will start in text mode (console only mode) and will answer commands from there.

BOT_DATA_DIR = r'/Users/XXX/errbot/errbot/data'
BOT_EXTRA_PLUGIN_DIR = '/Users/XXXX/errbot/errbot/plugins'

BOT_LOG_FILE = r'/Users/XXXX/errbot/errbot/errbot.log'
BOT_LOG_LEVEL = logging.DEBUG

BOT_ADMINS = ('@XXXXX', )  # !! Don't leave that to "CHANGE ME" if you connect your errbot to a chat system !!

# The identity, or credentials, used to connect to a server
BOT_IDENTITY = {
    'username': 'XXXX',  # The JID of the user you have created for the bot
    'password': 'XXXXX',       # The corresponding password for this user
    'token': 'XXXXXX',
    'endpoint' : 'https://xxxx.xxxx.com',
}

Can someone please let me know what i am doing wrong in above config ?

Or please also suggest any other bot (in python) that works with self hosted Hipchat .


问:
How can I display all the threads for my program when debug in Xcode
How can I display all the threads for my program when debug in Xcode?
I am using eclipse for java debugging, it can show all the current threads in the program
and I can suspend each one of them and show their current stack trace.  Can I do that same in XCode?

Thank you.

答:
Once you run your application the debug area automatically comes up. If it doesen't most likely it's because the visibility of the debug area has been turned off. To turn it on. Toggle the first view control on the top right side of the xcode window and the debug area should appear.

Once you have done that an area like the one in the image below will appear.

Click on the show debug navigator button which is the third last in the controls on the debug navigator.
On the row immediately after next to the name of your project, there are two buttons, click on the second

and select view process by thread.

For the threads to appear your application has to be paused. This can be done by adding a breakpoint at a particular point of the code or manually by clicking the pause button  on the debug bar below the source editor. Once paused the threads appear automatically as shown below.


问:
Integrating SOAP in laravel
I want to integrate soap client in my laravel project to call soap based web services. I have tried laravel-soap but due to lack of resources I am having trouble in getting it started.
Other option is I am trying to get started with php soapclient in my laravel project.
I want some kind of demo working so that I can understand how it is integrated in my laravel project.
Can you guys please provide me some resources?
Help much appreciated. </p>

答: Try this package http://github.com/ACFBentveld/Soap its very easy to use. </p>

Title: Integrating SOAP in laravel


问:
how to rollback on caught exception in Play framework?
I recently got into problem with play framework 2 @Transactional. Based on my tests, in the case of an exception, a transactional method would only rollback if the exception is unchecked (no catch block).
Here's my controller:

```<code>@Transactional
public Result myController(){
    ObjectNode result = Json.newObject();
    try{
        JsonNode json = request().body().asJson();

        someFunction(json);
        //doing some stuff using the json object inside someFunction
        //which I may intentionally throw an exception
        //based on some logic from within
        //(using "throw new RuntimeException()")

        result.put("success", true);
        return ok(Json.toJson(result));
    }catch(Exception e){
        result.put("success", false);
        result.put("msg", e.getMessage());
        return internalServerError(Json.toJson(result));
    }

}
</code>```

I want my controller to always return a JSON in response. But this comes at the expense of not having a database rollback when I throw an exception in my code. I know that in spring you can add this to @Transactional annotation but I'm using play.db.jpa.Transactional. Is there any way I can do a rollback in my catch block without using spring?

答:
The @Transactional annotation basically wraps your action's code in a call to DefaultJpaApi.withTransaction. If you look at the source you can see how this method handles the transaction.

Since you want to catch the exception, but still want to use the withTransaction behaviour, you could try removing the @Transactional annotation and calling withTransaction yourself within the action.

E.g.

```<code>class MyController {
  private final JPAApi jpa;
  @Inject
  public MyController(JPAApi jpa) {
    this.jpa = jpa;
  }

  public myAction() {
    ObjectNode result = Json.newObject();
    try {
      JsonNode json = request().body().asJson();

      // Calls someFunction inside a transaction.
      // If there's an exception, rolls back transaction
      // and rethrows.
      jpa.withTransaction(() -> someFunction(json));

      // Transaction has been committed.
      result.put("success", true);
      return ok(Json.toJson(result));
    } catch(Exception e) {
      // Transaction has been rolled back.
      result.put("success", false);
      result.put("msg", e.getMessage());
      return internalServerError(Json.toJson(result));
    }
  }
}
</code>```

Body:
I recently got into problem with play framework 2 @Transactional. Based on my tests, in the case of an exception, a transactional method would only rollback if the exception is unchecked (no catch block).
Here's my controller:

@Transactional
public Result myController(){
    ObjectNode result = Json.newObject();
    try{
        JsonNode json = request().body().asJson();

        someFunction(json);
        //doing some stuff using the json object inside someFunction
        //which I may intentionally throw an exception
        //based on some logic from within
        //(using "throw new RuntimeException()")

        result.put("success", true);
        return ok(Json.toJson(result));
    }catch(Exception e){
        result.put("success", false);
        result.put("msg", e.getMessage());
        return internalServerError(Json.toJson(result));
    }

}

I want my controller to always return a JSON in response. But this comes at the expense of not having a database rollback when I throw an exception in my code. I know that in spring you can add this to @Transactional annotation but I'm using play.db.jpa.Transactional. Is there any way I can do a rollback in my catch block without using spring?

Body:
The @Transactional annotation basically wraps your action's code in a call to DefaultJpaApi.withTransaction. If you look at the source you can see how this method handles the transaction.

Since you want to catch the exception, but still want to use the withTransaction behaviour, you could try removing the @Transactional annotation and calling withTransaction yourself within the action.

E.g.

class MyController {
  private final JPAApi jpa;
  @Inject
  public MyController(JPAApi jpa) {
    this.jpa = jpa;
  }

  public myAction() {
    ObjectNode result = Json.newObject();
    try {
      JsonNode json = request().body().asJson();

      // Calls someFunction inside a transaction.
      // If there's an exception, rolls back transaction
      // and rethrows.
      jpa.withTransaction(() -> someFunction(json));

      // Transaction has been committed.
      result.put("success", true);
      return ok(Json.toJson(result));
    } catch(Exception e) {
      // Transaction has been rolled back.
      result.put("success", false);
      result.put("msg", e.getMessage());
      return internalServerError(Json.toJson(result));
    }
  }
}


问:
Mysql - php query fetch array results using multiple parameters
I have a mysql table as below,

```<code>+---+-------+-----------+
|Sl | Name  | Status    |
+---+-------+-----------+
| 1 | Name1 | Active    |
| 2 | Name2 | Inactive  |
| 3 | Name3 | Pending   |
| 4 | Name4 | Dont Know |
| 5 | Name5 | Active    |
+---+-------+-----------+
</code>```

I have a sql query $query="select * from table ";
which fetch array and give me all records. But I want to display only specific rows with  Status= Active or Inactive.

答: SELECT * FROM table WHERE Status IN ("Active", "Inactive");</p>

Body:
I have a mysql table as below,

+---+-------+-----------+
|Sl | Name  | Status    |
+---+-------+-----------+
| 1 | Name1 | Active    |
| 2 | Name2 | Inactive  |
| 3 | Name3 | Pending   |
| 4 | Name4 | Dont Know |
| 5 | Name5 | Active    |
+---+-------+-----------+

I have a sql query $query="select * from table ";
which fetch array and give me all records. But I want to display only specific rows with  Status= Active or Inactive.


问:
How to send CTRL+C WITH JSCH?
I'm using jsch ChannelShell to send commands to a remote system, but I can't send special commands like ctrl+c. I tried many things, but have no success.

Any help would be appreciated.

答:
if you want to terminate an operation like tail </p>

```<code>Example -    BufferedReader reader = new BufferedReader(new InputStreamReader(ce.getInputStream()));
         OutputStream out=ce.getOutputStream();
out.write(3); //terminate the tail command

 out.flush();
</code>```

Title: How to send CTRL+C WITH JSCH?

Body:
if you want to terminate an operation like tail

Example -    BufferedReader reader = new BufferedReader(new InputStreamReader(ce.getInputStream()));
         OutputStream out=ce.getOutputStream();
out.write(3); //terminate the tail command

 out.flush();


问:
How to pivot on multiple columns?
I'm trying to pivot on multiple columns and I'm using SQL Server 2014, however, I cannot figure out how to do that. Here's what I've tried so far:

```<code>DECLARE @Table TABLE (
    Name NVARCHAR(MAX),
    TypeId INT,
    TotalOrders INT,
    GrandTotal MONEY
)

INSERT INTO @Table
    (Name, TypeId, TotalOrders, GrandTotal)
VALUES
    ('This Month', 1, 10, 1),
    ('This Month', 2, 5, 7),
    ('This Week', 1, 8, 3),
    ('Last Week', 1, 8, 12),
    ('Yesterday', 1, 10, 1),
    ('Yesterday', 2, 1, 5)
</code>```

Which produces the following result:

```<code>Name                             TypeId      TotalOrders GrandTotal
-------------------------------- ----------- ----------- ---------------------
This Month                       1           10          1.00
This Month                       2           5           7.00
This Week                        1           8           3.00
Last Week                        1           8           12.00
Yesterday                        1           10          1.00
Yesterday                        2           1           5.00
</code>```

To bring those rows into columns, I've tried this:

```<code>SELECT
    TypeId,
    ISNULL([Yesterday], 0) AS YesterdayTotalOrders,
    ISNULL([This Week], 0) AS ThisWeekTotalOrders,
    ISNULL([Last Week], 0) AS LastWeekTotalOrders,
    ISNULL([This Month], 0) AS ThisMonthTotalOrders
FROM
    (SELECT Name, TypeId, TotalOrders FROM @Table) AS src
PIVOT (
    SUM(TotalOrders) FOR Name IN (
        [Yesterday],
        [This Week],
        [Last Week],
        [This Month]
    )
) AS p1
</code>```

Which produces the following result set:

```<code>TypeId      YesterdayTotalOrders ThisWeekTotalOrders LastWeekTotalOrders ThisMonthTotalOrders
----------- -------------------- ------------------- ------------------- --------------------
1           10                   8                   8                   10
2           1                    0                   0                   5
</code>```

Now, I need to have few other columns for GrandTotal such as YesterdayGrandTotal, ThisWeekGrandTotal, and so on and so forth but I can't figure out how to achieve this.

Any help would be highly appreciated.

UPDATE#1: Here's the expected result set:

```<code>TypeId      YesterdayTotalOrders ThisWeekTotalOrders LastWeekTotalOrders ThisMonthTotalOrders YesterdayGrandTotal   ThisWeekGrandTotal    LastWeekGrandTotal    ThisMonthGrandTotal
----------- -------------------- ------------------- ------------------- -------------------- --------------------- --------------------- --------------------- ---------------------
1           10                   8                   8                   10                   1.00                  3.00                  12.00                 1.00
2           1                    0                   0                   5                    5.00                  0.00                  0.00                  7.00
</code>```

答:
Conditional aggregation may be a solution:

```<code>select typeID,
    SUM(case when name = 'Yesterday' then totalOrders else 0 end) as YesterdayTotalOrders,
    SUM(case when name = 'This Week' then totalOrders else 0 end) as ThisWeekTotalOrders,
    SUM(case when name = 'Last Week' then totalOrders else 0 end) as LastWeekTotalOrders,
    SUM(case when name = 'This Month' then totalOrders else 0 end) as ThisMonthTotalOrders,
    SUM(case when name = 'Yesterday' then GrandTotal else 0 end) as YesterdayGrandTotal,
    SUM(case when name = 'This Week' then GrandTotal else 0 end) as ThisWeekGrandTotal,
    SUM(case when name = 'Last Week' then GrandTotal else 0 end) as LastWeekGrandTotal,
    SUM(case when name = 'This Month' then GrandTotal else 0 end) as ThisMonthGrandTotal
from @table
group by typeID
</code>```

or, you can use the CROSS APPLY and PIVOT like this

```<code>SELECT
    TypeId,
    ISNULL([Yesterday], 0) AS YesterdayTotalOrders,
    ISNULL([This Week], 0) AS ThisWeekTotalOrders,
    ISNULL([Last Week], 0) AS LastWeekTotalOrders,
    ISNULL([This Month], 0) AS ThisMonthTotalOrders,
    ISNULL([grant Yesterday], 0) AS YesterdayGrandTotal,
    ISNULL([grant This Week], 0) AS ThisWeekGrandTotal,
    ISNULL([grant Last Week], 0) AS LastWeekGrandTotal,
    ISNULL([grant This Month], 0) AS ThisMonthGrandTotal
FROM
    (
      SELECT t.*
      FROM @Table
      CROSS APPLY (values(Name, TypeId, TotalOrders),
                     ('grant ' + Name, TypeId, GrandTotal))
                     t(Name, TypeId, TotalOrders)
    ) AS src
PIVOT (
    SUM(TotalOrders) FOR Name IN (
        [Yesterday],
        [This Week],
        [Last Week],
        [This Month],
        [grant Yesterday],
        [grant This Week],
        [grant Last Week],
        [grant This Month]
    )
) AS p1
</code>```

demo

Both solutions will scan the input table just once and they have a very similar query plan. Both solutions are better than JOIN of two pivots (the solution that I have originally provided) since two pivots need to scan the input table twice.

Title: How to pivot on multiple columns?

Body:
I'm trying to pivot on multiple columns and I'm using SQL Server 2014, however, I cannot figure out how to do that. Here's what I've tried so far:

DECLARE @Table TABLE (
    Name NVARCHAR(MAX),
    TypeId INT,
    TotalOrders INT,
    GrandTotal MONEY
)

INSERT INTO @Table
    (Name, TypeId, TotalOrders, GrandTotal)
VALUES
    ('This Month', 1, 10, 1),
    ('This Month', 2, 5, 7),
    ('This Week', 1, 8, 3),
    ('Last Week', 1, 8, 12),
    ('Yesterday', 1, 10, 1),
    ('Yesterday', 2, 1, 5)

Which produces the following result:

Name                             TypeId      TotalOrders GrandTotal
-------------------------------- ----------- ----------- ---------------------
This Month                       1           10          1.00
This Month                       2           5           7.00
This Week                        1           8           3.00
Last Week                        1           8           12.00
Yesterday                        1           10          1.00
Yesterday                        2           1           5.00

To bring those rows into columns, I've tried this:

SELECT
    TypeId,
    ISNULL([Yesterday], 0) AS YesterdayTotalOrders,
    ISNULL([This Week], 0) AS ThisWeekTotalOrders,
    ISNULL([Last Week], 0) AS LastWeekTotalOrders,
    ISNULL([This Month], 0) AS ThisMonthTotalOrders
FROM
    (SELECT Name, TypeId, TotalOrders FROM @Table) AS src
PIVOT (
    SUM(TotalOrders) FOR Name IN (
        [Yesterday],
        [This Week],
        [Last Week],
        [This Month]
    )
) AS p1

Which produces the following result set:

TypeId      YesterdayTotalOrders ThisWeekTotalOrders LastWeekTotalOrders ThisMonthTotalOrders
----------- -------------------- ------------------- ------------------- --------------------
1           10                   8                   8                   10
2           1                    0                   0                   5

Now, I need to have few other columns for GrandTotal such as YesterdayGrandTotal, ThisWeekGrandTotal, and so on and so forth but I can't figure out how to achieve this.

Any help would be highly appreciated.

UPDATE#1: Here's the expected result set:

TypeId      YesterdayTotalOrders ThisWeekTotalOrders LastWeekTotalOrders ThisMonthTotalOrders YesterdayGrandTotal   ThisWeekGrandTotal    LastWeekGrandTotal    ThisMonthGrandTotal
----------- -------------------- ------------------- ------------------- -------------------- --------------------- --------------------- --------------------- ---------------------
1           10                   8                   8                   10                   1.00                  3.00                  12.00                 1.00
2           1                    0                   0                   5                    5.00                  0.00                  0.00                  7.00

Body:
Conditional aggregation may be a solution:

select typeID,
    SUM(case when name = 'Yesterday' then totalOrders else 0 end) as YesterdayTotalOrders,
    SUM(case when name = 'This Week' then totalOrders else 0 end) as ThisWeekTotalOrders,
    SUM(case when name = 'Last Week' then totalOrders else 0 end) as LastWeekTotalOrders,
    SUM(case when name = 'This Month' then totalOrders else 0 end) as ThisMonthTotalOrders,
    SUM(case when name = 'Yesterday' then GrandTotal else 0 end) as YesterdayGrandTotal,
    SUM(case when name = 'This Week' then GrandTotal else 0 end) as ThisWeekGrandTotal,
    SUM(case when name = 'Last Week' then GrandTotal else 0 end) as LastWeekGrandTotal,
    SUM(case when name = 'This Month' then GrandTotal else 0 end) as ThisMonthGrandTotal
from @table
group by typeID

or, you can use the CROSS APPLY and PIVOT like this

SELECT
    TypeId,
    ISNULL([Yesterday], 0) AS YesterdayTotalOrders,
    ISNULL([This Week], 0) AS ThisWeekTotalOrders,
    ISNULL([Last Week], 0) AS LastWeekTotalOrders,
    ISNULL([This Month], 0) AS ThisMonthTotalOrders,
    ISNULL([grant Yesterday], 0) AS YesterdayGrandTotal,
    ISNULL([grant This Week], 0) AS ThisWeekGrandTotal,
    ISNULL([grant Last Week], 0) AS LastWeekGrandTotal,
    ISNULL([grant This Month], 0) AS ThisMonthGrandTotal
FROM
    (
      SELECT t.*
      FROM @Table
      CROSS APPLY (values(Name, TypeId, TotalOrders),
                     ('grant ' + Name, TypeId, GrandTotal))
                     t(Name, TypeId, TotalOrders)
    ) AS src
PIVOT (
    SUM(TotalOrders) FOR Name IN (
        [Yesterday],
        [This Week],
        [Last Week],
        [This Month],
        [grant Yesterday],
        [grant This Week],
        [grant Last Week],
        [grant This Month]
    )
) AS p1

demo

Both solutions will scan the input table just once and they have a very similar query plan. Both solutions are better than JOIN of two pivots (the solution that I have originally provided) since two pivots need to scan the input table twice.


问:
MSAL and Azure AD: What scopes should I pass when I just want to get the user ID?
I'm using MSAL to get an ID Token which is then used to access an Web API app. I've got a couple of questions and I was wondering if someone could help me understand what's going on.

Let me start with the authentication process in the client side. In this case, I'm building a Windows Forms app that is using the following code in order to authenticate the current user (ie, in order to get an ID Token which will be used to validate the user when he tries to access a Web API app):

```<code>//constructor code
_clientApp = new PublicClientApplication(ClientId,
                  Authority, //which url here?
                  TokenCacheHelper.GetUserCache());
_scopes = new []{ "user.read" }; //what to put here?

 //inside a helper method
 try {
      return await _clientApp.AcquireTokenSilentAsync(_scopes, _clientApp.Users.FirstOrDefault());
 }
 catch (MsalUiRequiredException ex) {
  try {
            return await _clientApp.AcquireTokenAsync(_scopes);
        }
        catch (MsalException ex) {
            return null;
        }
 }
</code>```

The first thing I'd like to clear is the value that should be used for the authority parameter. In this case, I'm using an URL on the form:

```<code>https://login.microsoftonline.com/{Tenant}/oauth2/v2.0/token
</code>```

However, I'm under the impression that I could also get away with something like this:

https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration

It seems like one endpoint is specific to my Azure AD while the other looks like a general (catch all) URL...Where can I find more information about these endpoints and on what's the purpose of each...

Another thing that I couldn't quite grasp is the scope. I'm not interested in querying MS Graph (or any other Azure related service for that matter). In previous versions of the MSAL library, it was possible to reference one of the default scopes. However, it seems like that is no longer possible (at least, I tried and got an exception saying that I shouldn't pass the default scopes...).

Passing an empty collection (ex.: new List<string>()) or null will also result in an error. So, in this case, I've ended passing the user.read scope (which, if I'm not mistaken, is used by MS Graph API. This is clearly not necessary, but was the only way I've managed to get the authentication process working. Any clues on how to perform the call when you just need to get an ID Token? Should I be calling a different method?

Moving to the server side, I've got a Web API app whose access is limited to calls that pass an ID token in the authentication header (bearer). According to this sample, I should use something like this:

```<code>private void ConfigureAuth(IAppBuilder app) {
   var authority = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration";
   app.UseOAuthBearerAuthentication(
       new OAuthBearerAuthenticationOptions {
          AccessTokenFormat = new JwtFormat(GetTokenValidationParameters(),
                    new OpenIdConnectCachingSecurityTokenProvider(authority)),
                                            Provider = new OAuthBearerAuthenticationProvider {
                                                     OnValidateIdentity = ValidateIdentity
                                            }
                                           });
 }
</code>```

Now, this does work and it will return 401 for all requests which don't have a valid ID Token. There is one question though: is there a way to specify the claim from the Ticket's Identity that should be used for identifying the username (User.Identity.Name of the controller)? In this case, I've ended handling the OnValidateIdentity in order to do that with code that looks like this:

```<code>private Task ValidateIdentity(OAuthValidateIdentityContext arg) {
    //username not getting correctly filled
    //so, i'm handling this event in order to set it up
    //from the preferred_username claim
    if (!arg.HasError && arg.IsValidated) {
        var identity = arg.Ticket.Identity;
        var username = identity.Claims.FirstOrDefault(c => c.Type == "preferred_username")?.Value ?? "";
        if (!string.IsNullOrEmpty(username)) {
            identity.AddClaim(new Claim(ClaimTypes.Name, username));
        }
    }
    return Task.CompletedTask;
}
</code>```

As you can see, I'm searching for the preferred_username claim from the ID Token (which was obtained by the client) and using its value to setup the Name claim. Is there any option that would let me do this automatically? Am I missing something in the configuration of the OAuthBearerAuthenticationMiddleware?

答:
Regarding your First Query -
Where can I find more information about these endpoints and on what's the purpose of each...

Answer -
https://login.microsoftonline.com/{tenant}/v2.0/.well-known/openid-configuration

The {tenant} can take one of four values:

common -
Users with both a personal Microsoft account and a work or school account from Azure Active Directory (Azure AD) can sign in to the application.

organizations -
Only users with work or school accounts from Azure AD can sign in to the application.

consumers -
Only users with a personal Microsoft account can sign in to the application.

8eaef023-2b34-4da1-9baa-8bc8c9d6a490 or contoso.onmicrosoft.com -
Only users with a work or school account from a specific Azure AD tenant can sign in to the application. Either the friendly domain name of the Azure AD tenant or the tenant's GUID identifier can be used.

Regarding your Second Query on Scope -

Answer - Refer to this document - OpenID Connect scopes

Regarding your Third Query on Claim -

Answer - Refer to this GIT Hub sample - active-directory-dotnet-webapp-roleclaims

Body:
I'm using MSAL to get an ID Token which is then used to access an Web API app. I've got a couple of questions and I was wondering if someone could help me understand what's going on.

Let me start with the authentication process in the client side. In this case, I'm building a Windows Forms app that is using the following code in order to authenticate the current user (ie, in order to get an ID Token which will be used to validate the user when he tries to access a Web API app):

//constructor code
_clientApp = new PublicClientApplication(ClientId,
                  Authority, //which url here?
                  TokenCacheHelper.GetUserCache());
_scopes = new []{ "user.read" }; //what to put here?

 //inside a helper method
 try {
      return await _clientApp.AcquireTokenSilentAsync(_scopes, _clientApp.Users.FirstOrDefault());
 }
 catch (MsalUiRequiredException ex) {
  try {
            return await _clientApp.AcquireTokenAsync(_scopes);
        }
        catch (MsalException ex) {
            return null;
        }
 }

The first thing I'd like to clear is the value that should be used for the authority parameter. In this case, I'm using an URL on the form:

https://login.microsoftonline.com/{Tenant}/oauth2/v2.0/token

However, I'm under the impression that I could also get away with something like this:

https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration

It seems like one endpoint is specific to my Azure AD while the other looks like a general (catch all) URL...Where can I find more information about these endpoints and on what's the purpose of each...

Another thing that I couldn't quite grasp is the scope. I'm not interested in querying MS Graph (or any other Azure related service for that matter). In previous versions of the MSAL library, it was possible to reference one of the default scopes. However, it seems like that is no longer possible (at least, I tried and got an exception saying that I shouldn't pass the default scopes...).

Passing an empty collection (ex.: new List<string>()) or null will also result in an error. So, in this case, I've ended passing the user.read scope (which, if I'm not mistaken, is used by MS Graph API. This is clearly not necessary, but was the only way I've managed to get the authentication process working. Any clues on how to perform the call when you just need to get an ID Token? Should I be calling a different method?

Moving to the server side, I've got a Web API app whose access is limited to calls that pass an ID token in the authentication header (bearer). According to this sample, I should use something like this:

private void ConfigureAuth(IAppBuilder app) {
   var authority = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration";
   app.UseOAuthBearerAuthentication(
       new OAuthBearerAuthenticationOptions {
          AccessTokenFormat = new JwtFormat(GetTokenValidationParameters(),
                    new OpenIdConnectCachingSecurityTokenProvider(authority)),
                                            Provider = new OAuthBearerAuthenticationProvider {
                                                     OnValidateIdentity = ValidateIdentity
                                            }
                                           });
 }

Now, this does work and it will return 401 for all requests which don't have a valid ID Token. There is one question though: is there a way to specify the claim from the Ticket's Identity that should be used for identifying the username (User.Identity.Name of the controller)? In this case, I've ended handling the OnValidateIdentity in order to do that with code that looks like this:

private Task ValidateIdentity(OAuthValidateIdentityContext arg) {
    //username not getting correctly filled
    //so, i'm handling this event in order to set it up
    //from the preferred_username claim
    if (!arg.HasError && arg.IsValidated) {
        var identity = arg.Ticket.Identity;
        var username = identity.Claims.FirstOrDefault(c => c.Type == "preferred_username")?.Value ?? "";
        if (!string.IsNullOrEmpty(username)) {
            identity.AddClaim(new Claim(ClaimTypes.Name, username));
        }
    }
    return Task.CompletedTask;
}

As you can see, I'm searching for the preferred_username claim from the ID Token (which was obtained by the client) and using its value to setup the Name claim. Is there any option that would let me do this automatically? Am I missing something in the configuration of the OAuthBearerAuthenticationMiddleware?


问:
Convert ArrayList to Double Array in java
How to Convert ArrayList to Double Array in Java6?

```<code> List lst = new ArrayList();
 double[] dbl=null;
 lst.add(343.34);
 lst.add(432.34);
</code>```

How convert above list to array?

答:
You can directly convert the List to an Array of the wrapper class.
Try the following:

```<code>List<Double> lst = new ArrayList<>();
Double[] dblArray = new Double[lst.size()];
lst.add(343.34);
lst.add(432.34);
dblArray = lst.toArray(dblArray);
</code>```

Body:
How to Convert ArrayList to Double Array in Java6?

 List lst = new ArrayList();
 double[] dbl=null;
 lst.add(343.34);
 lst.add(432.34);

How convert above list to array?

Body:
You can directly convert the List to an Array of the wrapper class.
Try the following:

List<Double> lst = new ArrayList<>();
Double[] dblArray = new Double[lst.size()];
lst.add(343.34);
lst.add(432.34);
dblArray = lst.toArray(dblArray);


问:
Editing a editor with text and after clicking Done button the editor covers the whole page in iOS xamarin app
I have a text editor in iOS and with Done button so when i tap it after typing something for edit the editor covers the whole area of the app and unable to edit.

I want to fix the height of the editor so that will be able to edit and save it.

I have used custom renderer for this and tried setting the height and width but not working as expected

my xaml code

```<code><controls:XEditor x:Name="Editor"  Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" />
</code>```

my custom renderer

```<code> public class XEditorRenderer:EditorRenderer
 {
    protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
    {
        base.OnElementChanged(e);
        Control.SelectAll(Self);
        //this.Control.InputAccessoryView = null;
    }
 }
</code>```

答: This is and Editor issue so i have tweaked it to creating a custom renderer and fix it</p>

Body:
I have a text editor in iOS and with Done button so when i tap it after typing something for edit the editor covers the whole area of the app and unable to edit.

I want to fix the height of the editor so that will be able to edit and save it.

I have used custom renderer for this and tried setting the height and width but not working as expected

my xaml code

<controls:XEditor x:Name="Editor"  Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" />

my custom renderer

 public class XEditorRenderer:EditorRenderer
 {
    protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
    {
        base.OnElementChanged(e);
        Control.SelectAll(Self);
        //this.Control.InputAccessoryView = null;
    }
 }


问:
How do I open a new window/tab and dynamically fill it with content?
I am building a website that displays recipes. Each recipe appears as part of a blog entry, and will have a link at the bottom to Print this recipe.

What I want to happen is a click on the link opens a new window and fills it with a print-friendly-styled version of the recipe, which is already inside its own
.

Can I do this with JS/jQuery alone, or do I need to process from the server side? Any ideas how to do this?

EDIT: What would be ideal would be to generate a PDF on the fly, but in lieu of that I'd like a new window, containing only the recipe, for the visitor to print out or save, as they see fit. Print-styles are nice, but most people don't know they exist and can't be bothered to check and see by printing out a page that doesn't look print ready.

答:
There is no need to load a different stylesheet and the only javascript you will need is for triggering the printing dialog.

With CSS alone you can add rules that are only used when printing, you can either use media queries

```<code><style type="text/css">
@media print{
    //css printing rules
}
</style>
</code>```

or use the link tag:

```<code><link rel="stylesheet" media="print" href="styles.css" type="text/css" />
</code>```

UPDATE: If you want to update the stylesheet on the fly without openning a new window i suggest you check out this Nettuts article or a simpler solution:

```<code>$("#css-switch").click(function() {
     $("link[rel=stylesheet]").attr({href : "red.css"});
});
</code>```

Body:
There is no need to load a different stylesheet and the only javascript you will need is for triggering the printing dialog.

With CSS alone you can add rules that are only used when printing, you can either use media queries

<style type="text/css">
@media print{
    //css printing rules
}
</style>

or use the link tag:

<link rel="stylesheet" media="print" href="styles.css" type="text/css" />

UPDATE: If you want to update the stylesheet on the fly without openning a new window i suggest you check out this Nettuts article or a simpler solution:

$("#css-switch").click(function() {
     $("link[rel=stylesheet]").attr({href : "red.css"});
});


问:
HTTP Error 405 Method not allowed while calling web api delete method?
I am trying to call from MVC controller application to WEBAPI applicaiton method. I am getting error 405 method not allowed. Its working fine while calling GET and POST.

MVC Applicaiton:

```<code>[HttpPost]
public HttpResponseMessage DeleteService(int id) {
        //code for webapi
    }
</code>```

WEB API application:

```<code>[HttpDelete]
public HttpResponseMessage DeleteService(int id) {
        try {
            ServicesModel service = dbContext.Services.Find(id);
            IEnumerable<ServicePropertiesModel> serviceProperies = dbContext.ServiceProperties.Where(x => x.ServiceId == id);
            if (service != null) {

                foreach (ServicePropertiesModel s in serviceProperies) {
                    dbContext.ServiceProperties.Remove(s);
                }
                dbContext.Services.Remove(service);
                dbContext.SaveChanges();
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        } catch {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }
</code>```

Thnaking you.
  Regards,Sekhar

答: The methods PUT and DELETE are not allowed by default. You have to allow them in your web applications web.config.</p>

Body:
I am trying to call from MVC controller application to WEBAPI applicaiton method. I am getting error 405 method not allowed. Its working fine while calling GET and POST.

MVC Applicaiton:

[HttpPost]
public HttpResponseMessage DeleteService(int id) {
        //code for webapi
    }

WEB API application:

[HttpDelete]
public HttpResponseMessage DeleteService(int id) {
        try {
            ServicesModel service = dbContext.Services.Find(id);
            IEnumerable<ServicePropertiesModel> serviceProperies = dbContext.ServiceProperties.Where(x => x.ServiceId == id);
            if (service != null) {

                foreach (ServicePropertiesModel s in serviceProperies) {
                    dbContext.ServiceProperties.Remove(s);
                }
                dbContext.Services.Remove(service);
                dbContext.SaveChanges();
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        } catch {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }

Thnaking you.
  Regards,Sekhar


问:
Converting ArrayList of Characters to a String?
How to convert an ArrayList<Character> to a String in Java?

The List.toString method returns it as [a,b,c] string - I want to get rid of the brackets (etcetera) and store it as abc.

答:
```<code> private void countChar() throws IOException {
    HashMap hashMap = new HashMap();
    List list = new ArrayList();
    list = "aammit".chars().mapToObj(r -> (char) r).collect(Collectors.toList());
    list.stream().forEach(e -> {
        hashMap.computeIfPresent(e, (K, V) -> (int) V + 1);
        hashMap.computeIfAbsent(e, (V) -> 1);
    });

    System.out.println(hashMap);

}
</code>```

ContentLicense: CC BY-SA 4.0


问:
Get duration of Video after upload
What is best way to get?

I have a field where user will upload video.

When you click the upload button, Video get uploaded. This work perfectly.

I needed the duration of the video from physical path, I tried:

```<code>using WMPLib;
WindowsMediaPlayer wmp = new WindowsMediaPlayerClass();
IWMPMedia mediaInfo = wmp.newMedia(Server.MapPath("~/Uploads/test.mp4"));
double duration = mediaInfo.duration;
</code>```

But its not working, I get error:

The type 'WMPLib.WindowsMediaPlayerClass' has no constructors defined Interop type 'WMPLib.WindowsMediaPlayerClass' cannot be embedded.

How to catch the duration?

答:
Following code snippet may help you guys :

```<code>using WMPLib;
// ...your code here...

var player = new WindowsMediaPlayer();
var clip = player.newMedia(VideoFilePath);
Console.WriteLine(TimeSpan.FromSeconds(clip.duration));
</code>```

and don't forget to add the reference of wmp.dll which will be
  present in System32 folder.

Title: Get duration of Video after upload

Body:
What is best way to get?

I have a field where user will upload video.

When you click the upload button, Video get uploaded. This work perfectly.

I needed the duration of the video from physical path, I tried:

using WMPLib;
WindowsMediaPlayer wmp = new WindowsMediaPlayerClass();
IWMPMedia mediaInfo = wmp.newMedia(Server.MapPath("~/Uploads/test.mp4"));
double duration = mediaInfo.duration;

But its not working, I get error:

The type 'WMPLib.WindowsMediaPlayerClass' has no constructors defined Interop type 'WMPLib.WindowsMediaPlayerClass' cannot be embedded.

How to catch the duration?

Body:
Following code snippet may help you guys :

using WMPLib;
// ...your code here...

var player = new WindowsMediaPlayer();
var clip = player.newMedia(VideoFilePath);
Console.WriteLine(TimeSpan.FromSeconds(clip.duration));

and don't forget to add the reference of wmp.dll which will be
  present in System32 folder.


问:
Uncaught SyntaxError: Unexpected token U in JSON at position 0 at JSON.parse (<anonymous>) at Response.Body.json
I am working on an angular2 project. I am stuck with these errors. The error occured when I tried to send the JSON objects to the backend. It may be due the parsing of JSON objects. I am new to angualar, so please do help

Signup.service.ts

```<code>import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map' ;
@Injectable()
    export class SignupService{
        constructor (private http: Http){}
        insertform(newreg: any ){
            console.log();
            var headers = new Headers ();
            headers.append('Content-Type','application/json');
            return this.http.post('http://localhost:3000/api/users', JSON.stringify(newreg),{headers: headers})
            .map(res=> res.json());
         }
     }
</code>```

signup.component.ts

```<code>import { Component, AfterViewInit } from '@angular/core';
import {SignupService} from '../../services/signup.service';
import {Signup} from '../../../signup';
declare var $: any;
 @Component({
 moduleId: module.id,
 selector: 'signup',
 templateUrl: 'signup.component.html',
  providers: [SignupService]
 })
 export class SignupComponent {
 datas: Signup[];
 data: any;
 first_name: string;
 last_name: string;
 address: string;
 email: string;
 pwd:string;
 pwdcnf:string;
 phone:number;
 constructor(private signupService: SignupService){ };
 ngAfterViewInit() {
    $('#textarea1').trigger('autoresize');
   };
     regformSubmit(event: any){
    event.preventDefault();
    var newreg = {
     first_name: this.first_name,
      last_name: this.last_name,
     email: this.email,
     address: this.address,
     phone: this.phone,
    pwd:this.pwd,
    pwdcnf:this.pwdcnf
   };
    this.signupService.insertform(newreg)
      .subscribe (data => {
       this.datas.push(data);
        this.first_name='';
         this.last_name ='';
         this.email='';
        this.address='';
         this.phone=0;
    this.pwd='';
    this.pwdcnf='';
      });
  }
 }
</code>```

signup.component.html

```<code> <div class="container light-blue lighten-5">
<form class="col s12" (ngSubmit)="regformSubmit($event)">
  <div class="row">
    <div class="input-field col s6">
      <input  id="first_name" type="text" class="validate" [(ngModel)]="first_name" name="first_name" required>
      <label for="first_name">First Name</label>
    </div>
    <div class="input-field col s6">
      <input id="last_name" type="text" class="validate" [(ngModel)]="last_name" name="last_name" required>
      <label for="last_name">Last Name</label>
    </div>
  </div>
  <div class="row">
    <div class="input-field col s12">
      <textarea id="textarea1" class="materialize-textarea" [(ngModel)]="address" name="address" required></textarea>
      <label for="disabled">Address</label>
    </div>
  </div>
  <div class="row ">
    <div class="input-field col s5">
      <input id="password" type="password" class="validate" [(ngModel)]="pwd" name="pwd" required>
      <label for="password">Password</label>
    </div>
    <div class="input-field col s5 offset-s2">
      <input id="password1" type="password" class="validate" [(ngModel)]="pwdcnf" name="pwdcnf" required>
      <label for="password1">Confirm password</label>
    </div>
  </div>
  <div class="row">
    <div class="input-field col s5">
      <input id="email" type="email" class="validate" [(ngModel)]="email" name="email" required>
      <label for="email">Email</label>
    </div>
    <div class="input-field col s5 offset-s2">
      <input id="password2" type="number" class="validate" [(ngModel)]="phone" name="number" required>
      <label for="password2">Phone</label>
    </div>
  </div>
 <div class="row">
     <div class="input-field col s4 offset-s5">
         <button class="btn waves-effect waves-light" type="submit" name="action">Submit
            <i class="material-icons right">send</i>
        </button>
      </div>
 </div>
</form>
 </div>
 <style>
  .ng-invalid {
   border-bottom-color: red;
  }
</style>
</code>```

The full error message is

```<code>EXCEPTION: Unexpected token U in JSON at position 0
ORIGINAL STACKTRACE:
yntaxError: Unexpected token U in JSON at position 0
at JSON.parse (<anonymous>)
at Response.Body.json (http.umd.js:777)
at MapSubscriber.eval [as project] (signup.service.ts:13)
at MapSubscriber._next (map.ts:75)
at MapSubscriber.Subscriber.next (Subscriber.ts:95)
at XMLHttpRequest.onLoad (http.umd.js:1180)
at ZoneDelegate.invokeTask (zone.js:275)
at Object.onInvokeTask (core.umd.js:3971)
at ZoneDelegate.invokeTask (zone.js:274)
at Zone.runTask (zone.js:151)
at XMLHttpRequest.ZoneTask.invoke (zone.js:345)
Uncaught SyntaxError: Unexpected token U in JSON at position 0
at JSON.parse (<anonymous>)
at Response.Body.json (http.umd.js:777)
at MapSubscriber.eval [as project] (signup.service.ts:13)
at MapSubscriber._next (map.ts:75)
at MapSubscriber.Subscriber.next (Subscriber.ts:95)
at XMLHttpRequest.onLoad (http.umd.js:1180)
at ZoneDelegate.invokeTask (zone.js:275)
at Object.onInvokeTask (core.umd.js:3971)
at ZoneDelegate.invokeTask (zone.js:274)
at Zone.runTask (zone.js:151)
at XMLHttpRequest.ZoneTask.invoke (zone.js:345)
</code>```

答:
```<code>return this.http.post('http://localhost:3000/api/users', JSON.stringify(newreg),{headers: headers})
            .map(res=> res.json());
</code>```

The backend API at http://localhost:3000/api/users has a return type that is not JSON, in your case String beginning with the letter 'U'. Make sure the back end returns json data by using res.json("Your text here"); This is because your map function .map(res=> res.json()); is expecting a json response

Body:
I am working on an angular2 project. I am stuck with these errors. The error occured when I tried to send the JSON objects to the backend. It may be due the parsing of JSON objects. I am new to angualar, so please do help

Signup.service.ts

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map' ;
@Injectable()
    export class SignupService{
        constructor (private http: Http){}
        insertform(newreg: any ){
            console.log();
            var headers = new Headers ();
            headers.append('Content-Type','application/json');
            return this.http.post('http://localhost:3000/api/users', JSON.stringify(newreg),{headers: headers})
            .map(res=> res.json());
         }
     }

signup.component.ts

import { Component, AfterViewInit } from '@angular/core';
import {SignupService} from '../../services/signup.service';
import {Signup} from '../../../signup';
declare var $: any;
 @Component({
 moduleId: module.id,
 selector: 'signup',
 templateUrl: 'signup.component.html',
  providers: [SignupService]
 })
 export class SignupComponent {
 datas: Signup[];
 data: any;
 first_name: string;
 last_name: string;
 address: string;
 email: string;
 pwd:string;
 pwdcnf:string;
 phone:number;
 constructor(private signupService: SignupService){ };
 ngAfterViewInit() {
    $('#textarea1').trigger('autoresize');
   };
     regformSubmit(event: any){
    event.preventDefault();
    var newreg = {
     first_name: this.first_name,
      last_name: this.last_name,
     email: this.email,
     address: this.address,
     phone: this.phone,
    pwd:this.pwd,
    pwdcnf:this.pwdcnf
   };
    this.signupService.insertform(newreg)
      .subscribe (data => {
       this.datas.push(data);
        this.first_name='';
         this.last_name ='';
         this.email='';
        this.address='';
         this.phone=0;
    this.pwd='';
    this.pwdcnf='';
      });
  }
 }

signup.component.html

<form class="col s12" (ngSubmit)="regformSubmit($event)">

      <input  id="first_name" type="text" class="validate" [(ngModel)]="first_name" name="first_name" required>
      First Name

      <input id="last_name" type="text" class="validate" [(ngModel)]="last_name" name="last_name" required>
      Last Name

      <textarea id="textarea1" class="materialize-textarea" [(ngModel)]="address" name="address" required></textarea>
      Address

      <input id="password" type="password" class="validate" [(ngModel)]="pwd" name="pwd" required>
      Password

      <input id="password1" type="password" class="validate" [(ngModel)]="pwdcnf" name="pwdcnf" required>
      Confirm password

      <input id="email" type="email" class="validate" [(ngModel)]="email" name="email" required>
      Email

      <input id="password2" type="number" class="validate" [(ngModel)]="phone" name="number" required>
      Phone

         <button class="btn waves-effect waves-light" type="submit" name="action">Submit
            send
        </button>

</form>

The full error message is

EXCEPTION: Unexpected token U in JSON at position 0
ORIGINAL STACKTRACE:
yntaxError: Unexpected token U in JSON at position 0
at JSON.parse (<anonymous>)
at Response.Body.json (http.umd.js:777)
at MapSubscriber.eval [as project] (signup.service.ts:13)
at MapSubscriber._next (map.ts:75)
at MapSubscriber.Subscriber.next (Subscriber.ts:95)
at XMLHttpRequest.onLoad (http.umd.js:1180)
at ZoneDelegate.invokeTask (zone.js:275)
at Object.onInvokeTask (core.umd.js:3971)
at ZoneDelegate.invokeTask (zone.js:274)
at Zone.runTask (zone.js:151)
at XMLHttpRequest.ZoneTask.invoke (zone.js:345)
Uncaught SyntaxError: Unexpected token U in JSON at position 0
at JSON.parse (<anonymous>)
at Response.Body.json (http.umd.js:777)
at MapSubscriber.eval [as project] (signup.service.ts:13)
at MapSubscriber._next (map.ts:75)
at MapSubscriber.Subscriber.next (Subscriber.ts:95)
at XMLHttpRequest.onLoad (http.umd.js:1180)
at ZoneDelegate.invokeTask (zone.js:275)
at Object.onInvokeTask (core.umd.js:3971)
at ZoneDelegate.invokeTask (zone.js:274)
at Zone.runTask (zone.js:151)
at XMLHttpRequest.ZoneTask.invoke (zone.js:345)

Body:
return this.http.post('http://localhost:3000/api/users', JSON.stringify(newreg),{headers: headers})
            .map(res=> res.json());

The backend API at http://localhost:3000/api/users has a return type that is not JSON, in your case String beginning with the letter 'U'. Make sure the back end returns json data by using res.json("Your text here"); This is because your map function .map(res=> res.json()); is expecting a json response


问:
Coding Standard Wiki
At my place of work I've been put in charge of creating a coding standards document. Generally we follow what FxCop and StyleCop tools report to some degree but what we really require is document that will explain when to use a convention, why and maybe even a simple example.

This could be extended in the future for other purposes as well.

The first thing that came to my mind is to have an internal wiki site that we could build up and change easily over time but I've never used a wiki-based engine before and would like some recommendations.

If possible the engine should be in C# so we're able to tweak it to our needs if required.

If you think a wiki solution is the wrong way to go about this then please give an alternative :)

Update

I've just been informed, although we do have a php server it wont be staying, so I'm afraid php-based wiki ideas are off the table.

Update 2

Could you also (if possible) let me know if any of these solutions work with Active Directory?

Cheers
Tony

答:
I am confused by what you mean when you say you don't have a php server. It runs on every platform known to man. I am noticing most Visual Studio Developers don't know that PHP runs on IIS.

I would go with mediawiki It has the biggest feature set and most add-ons developed for it in case you ever need to port your data elsewhere. If you need to modify your wiki you are  doing it wrong.

Title: Coding Standard Wiki

OwnerDisplayName: Update


问:
Is it possible to create a category of the "Block" object in Objective-C
I would like to add functions by creating a category for Objective-C Blocks.

```<code>__block int (^aBlock)(int) = ^int( int n ){
    if( n <= 1 ) return n;
    return aBlock( n - 1 ) + aBlock( n - 2 );
};
</code>```

Instead of just allowing the normal [aBlock copy], [aBlock retain], [aBlock release], [aBlock autorelease]. I could do thing like:

```<code>[aBlock mapTo:anArray];
</code>```

Possible Category

```<code>@interface UnknownBlockClass (map)

- (NSArray *)mapTo:(NSArray *)array_;

@end
</code>```

答:
@pwc is correct in that you can't create a category for a class that you can't see.

However...

WHAT I AM ABOUT TO TELL YOU SHOULD BE USED STRICTLY AS AN EXERCISE IN LEARNING, AND NEVER IN ANY SORT OF PRODUCTION SETTING.

Some runtime introspection reveals some interesting information.  There are a number of classes that contain the word "Block".  Some of them look promising: __NSStackBlock, __NSMallocBlock, __NSAutoBlock, and NSBlock.

Some more introspection shows that the promising classes inherit from NSBlock

So it looks like any block is going to be some instance or subclass of NSBlock.

You can create a method on an object, like so:

```<code>@implementation Foo
- (void) doFoo {
  //do something awesome with self, a block
  //however, you can't do "self()".
  //You'll have to cast it to a block-type variable and use that
}
@end
</code>```

Then at runtime, you can move that method to the NSBlock class:

```<code>Method m = class_getInstanceMethod([Foo class], @selector(doFoo));
IMP doFoo = method_getImplementation(m);
const char *type = method_getTypeEncoding(m);
Class nsblock = NSClassFromString(@"NSBlock");
class_addMethod(nsblock, @selector(doFoo), doFoo, type);
</code>```

After this, blocks should respond to the doFoo message.

USE AT YOUR OWN RISK, AND ONLY FOR EXPERIMENTING.

Body:
I would like to add functions by creating a category for Objective-C Blocks.

__block int (^aBlock)(int) = ^int( int n ){
    if( n <= 1 ) return n;
    return aBlock( n - 1 ) + aBlock( n - 2 );
};

Instead of just allowing the normal [aBlock copy], [aBlock retain], [aBlock release], [aBlock autorelease]. I could do thing like:

[aBlock mapTo:anArray];

Possible Category

@interface UnknownBlockClass (map)

- (NSArray *)mapTo:(NSArray *)array_;

@end

Body:
@pwc is correct in that you can't create a category for a class that you can't see.

However...

WHAT I AM ABOUT TO TELL YOU SHOULD BE USED STRICTLY AS AN EXERCISE IN LEARNING, AND NEVER IN ANY SORT OF PRODUCTION SETTING.

Some runtime introspection reveals some interesting information.  There are a number of classes that contain the word "Block".  Some of them look promising: __NSStackBlock, __NSMallocBlock, __NSAutoBlock, and NSBlock.

Some more introspection shows that the promising classes inherit from NSBlock

So it looks like any block is going to be some instance or subclass of NSBlock.

You can create a method on an object, like so:

@implementation Foo
- (void) doFoo {
  //do something awesome with self, a block
  //however, you can't do "self()".
  //You'll have to cast it to a block-type variable and use that
}
@end

Then at runtime, you can move that method to the NSBlock class:

Method m = class_getInstanceMethod([Foo class], @selector(doFoo));
IMP doFoo = method_getImplementation(m);
const char *type = method_getTypeEncoding(m);
Class nsblock = NSClassFromString(@"NSBlock");
class_addMethod(nsblock, @selector(doFoo), doFoo, type);

After this, blocks should respond to the doFoo message.

USE AT YOUR OWN RISK, AND ONLY FOR EXPERIMENTING.


问:
Profile Antlr grammar
I found this question here in which OP asks for a way to profile an ANTLTR grammar.

However the answer is somewhat unsatisfying as it is limited to grammars without actions and - even more important - it is an automated profiling that will (as I see it) use the defaul constructor of the generated lexer/parser to construct it.

I need to profile a grammar, that does contain actions and that has to be constructed using a custom constructor. Therefore I'd need to be able to instantiate the lexer + parser myself and then profile it.

I was unable to find any information on this topic. I know there is a profiler for IntelliJ but it works quite similar to the one described in the linked question's answer (maybe it's even the same).

Does anyone know how I can profile my grammar with this special needs? I don't need any fancy GUI. I'd be satisified if I get the result printed to the console or something like that.

To wrap it up: I'm searching for either a tool or a hint on how to write some code that lets me profile my ANTLR grammar (with self-instantiated lexer/parser).

Btw my target language is Java so I guess the profiler has to be in Java as well.

答:
A good start is setting Parser.setProfile() to true and examine what you get from Parser.getParseInfo() after a parse run. I haven't yet looked closer what's provided in detail by the profiling result, but it's on the todo list for my vscode extension for ANTLR4 to provide profiling info for grammars to help improving them.

A hint for getting from the decision info to a specific rule: there's a decision number, which is an index into ATN.decisionToState. The DecisionState instance you can get by this is an ATNState descendant, which allows to get a ATNState.ruleIndex from it. The rule index then can be used with your parser's ruleNames property to find the name of that rule. The value is also what is used for the rule's enum entry.

Title: Profile Antlr grammar


问:
Django REST framework custom format for all out responses
In my project I use DRF as backend and Angular as frontend.

Django==1.10
djangorestframework==3.7.1

I need all responses from DRF to be in the following format.

```<code>{
 "status": "",  //  200,400,.....etc
 "error": "",   //  True, False
 "data": [],    //  data
 "message": ""  //  Success messages
}
</code>```

Currently it is in

```<code>[
    {
        "id": 1,
        "name": ""
    },
    {
        "id": 2,
        "name": ""
    }
]
</code>```

it should be

```<code>{
     "status": "200",
     "error": "False",
     "data": [
               {
                   "id": 1,
                   "name": ""
                },
                {
                   "id": 2,
                   "name": ""
                }
            ],
     "message": "Success"
}
</code>```

for this i have written a custom viewset and overridden the functions list, detail, create, update

```<code>class ResponseModelViewSet(viewsets.ModelViewSet):
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        custom_data = {
            "status": True,
            "error": False,
            "message": 'message',
            "data": serializer.data
        }
        return Response(custom_data)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        custom_data = {
            "status": True,
            "error": False,
            "message": 'message',
            "data": serializer.data
        }

        return Response(custom_data, status=status.HTTP_201_CREATED, headers=headers)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        custom_data = {
            "status": True,
            "error": False,
            "message": 'message',
            "data": serializer.data
        }
        return Response(custom_data)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        custom_data = {
            "status": True,
            "error": False,
            "message": 'message',
            "data": serializer.data
        }
        return Response(custom_data)
</code>```

and in views i use my custom viewset

```<code>from common.baseview import ResponseModelViewSet

class PositionViewsets(ResponseModelViewSet):
    serializer_class = PositionSerializer
    permission_classes = (IsAuthenticated,)
    model = Position

    def get_queryset(self):
        return Position.objects.filter(order__user=self.request.user)
</code>```

I am not sure if this is the correct way of doing it or there is some other efficient way to do it.
Anyway this works for my custom apps but not for the Authentication app
i used the default rest apps

```<code>'rest_framework.authtoken',
'rest_auth',
</code>```

For login using username and password  and get  the success response as follows.

```<code>{
    "key": "e642efd0b78e08b57bf34fa999f49b70a7bfe21a"
}
</code>```

Instead  i need this.

```<code>{
 "status": "200",
 "error": "False",
 "data": [
          {
           "token":{
                     "key":"e642efd0b78e08b57bf34fa999f49b70a7bfe21a"
                    }
           }
         ],
 "message": "Login Sucess"
}
</code>```

for error

```<code>{
 "status": "error",
 "error": "True",
 "data": [
           {
            "email": ["Enter a valid email address."]
            }
         ],
 "message": "Login Failed"
}
</code>```

答:
After some research I found a way to do this. I had to override the default behaviour of the ModelViewSet to output a different response.

I created a custom Response format initially:

```<code>class ResponseInfo(object):
    def __init__(self, user=None, **args):
        self.response = {
            "status": args.get('status', True),
            "error": args.get('error', 200),
            "data": args.get('data', []),
            "message": args.get('message', 'success')
        }
</code>```

Then use this custom format in every method of the ModelViewSet:

```<code>class ResponseModelViewSet(viewsets.ModelViewSet):
    def __init__(self, **kwargs):
        self.response_format = ResponseInfo().response
        super(ResponseModelViewSet, self).__init__(**kwargs)

    def list(self, request, *args, **kwargs):
        response_data = super(ResponseModelViewSet, self).list(request, *args, **kwargs)
        self.response_format["data"] = response_data.data
        self.response_format["status"] = True
        if not response_data.data:
            self.response_format["message"] = "List empty"
        return Response(self.response_format)

    def create(self, request, *args, **kwargs):
        response_data = super(ResponseModelViewSet, self).create(request, *args, **kwargs)
        self.response_format["data"] = response_data.data
        self.response_format["status"] = True
        return Response(self.response_format)

    def retrieve(self, request, *args, **kwargs):
        response_data = super(ResponseModelViewSet, self).retrieve(request, *args, **kwargs)
        self.response_format["data"] = response_data.data
        self.response_format["status"] = True
        if not response_data.data:
            self.response_format["message"] = "Empty"
        return Response(self.response_format)

    def update(self, request, *args, **kwargs):
        response_data = super(ResponseModelViewSet, self).update(request, *args, **kwargs)
        self.response_format["data"] = response_data.data
        self.response_format["status"] = True

        return Response(self.response_format)

    def destroy(self, request, *args, **kwargs):
        response_data = super(ResponseModelViewSet, self).destroy(request, *args, **kwargs)
        self.response_format["data"] = response_data.data
        self.response_format["status"] = True
        return Response(self.response_format)
</code>```

Body:
In my project I use DRF as backend and Angular as frontend.

Django==1.10
djangorestframework==3.7.1

I need all responses from DRF to be in the following format.

{
 "status": "",  //  200,400,.....etc
 "error": "",   //  True, False
 "data": [],    //  data
 "message": ""  //  Success messages
}

Currently it is in

[
    {
        "id": 1,
        "name": ""
    },
    {
        "id": 2,
        "name": ""
    }
]

it should be

{
     "status": "200",
     "error": "False",
     "data": [
               {
                   "id": 1,
                   "name": ""
                },
                {
                   "id": 2,
                   "name": ""
                }
            ],
     "message": "Success"
}

for this i have written a custom viewset and overridden the functions list, detail, create, update

class ResponseModelViewSet(viewsets.ModelViewSet):
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        custom_data = {
            "status": True,
            "error": False,
            "message": 'message',
            "data": serializer.data
        }
        return Response(custom_data)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        custom_data = {
            "status": True,
            "error": False,
            "message": 'message',
            "data": serializer.data
        }

        return Response(custom_data, status=status.HTTP_201_CREATED, headers=headers)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        custom_data = {
            "status": True,
            "error": False,
            "message": 'message',
            "data": serializer.data
        }
        return Response(custom_data)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        custom_data = {
            "status": True,
            "error": False,
            "message": 'message',
            "data": serializer.data
        }
        return Response(custom_data)

and in views i use my custom viewset

from common.baseview import ResponseModelViewSet

class PositionViewsets(ResponseModelViewSet):
    serializer_class = PositionSerializer
    permission_classes = (IsAuthenticated,)
    model = Position

    def get_queryset(self):
        return Position.objects.filter(order__user=self.request.user)

I am not sure if this is the correct way of doing it or there is some other efficient way to do it.
Anyway this works for my custom apps but not for the Authentication app
i used the default rest apps

'rest_framework.authtoken',
'rest_auth',

For login using username and password  and get  the success response as follows.

{
    "key": "e642efd0b78e08b57bf34fa999f49b70a7bfe21a"
}

Instead  i need this.

{
 "status": "200",
 "error": "False",
 "data": [
          {
           "token":{
                     "key":"e642efd0b78e08b57bf34fa999f49b70a7bfe21a"
                    }
           }
         ],
 "message": "Login Sucess"
}

for error

{
 "status": "error",
 "error": "True",
 "data": [
           {
            "email": ["Enter a valid email address."]
            }
         ],
 "message": "Login Failed"
}

Body:
After some research I found a way to do this. I had to override the default behaviour of the ModelViewSet to output a different response.

I created a custom Response format initially:

class ResponseInfo(object):
    def __init__(self, user=None, **args):
        self.response = {
            "status": args.get('status', True),
            "error": args.get('error', 200),
            "data": args.get('data', []),
            "message": args.get('message', 'success')
        }

Then use this custom format in every method of the ModelViewSet:

class ResponseModelViewSet(viewsets.ModelViewSet):
    def __init__(self, **kwargs):
        self.response_format = ResponseInfo().response
        super(ResponseModelViewSet, self).__init__(**kwargs)

    def list(self, request, *args, **kwargs):
        response_data = super(ResponseModelViewSet, self).list(request, *args, **kwargs)
        self.response_format["data"] = response_data.data
        self.response_format["status"] = True
        if not response_data.data:
            self.response_format["message"] = "List empty"
        return Response(self.response_format)

    def create(self, request, *args, **kwargs):
        response_data = super(ResponseModelViewSet, self).create(request, *args, **kwargs)
        self.response_format["data"] = response_data.data
        self.response_format["status"] = True
        return Response(self.response_format)

    def retrieve(self, request, *args, **kwargs):
        response_data = super(ResponseModelViewSet, self).retrieve(request, *args, **kwargs)
        self.response_format["data"] = response_data.data
        self.response_format["status"] = True
        if not response_data.data:
            self.response_format["message"] = "Empty"
        return Response(self.response_format)

    def update(self, request, *args, **kwargs):
        response_data = super(ResponseModelViewSet, self).update(request, *args, **kwargs)
        self.response_format["data"] = response_data.data
        self.response_format["status"] = True

        return Response(self.response_format)

    def destroy(self, request, *args, **kwargs):
        response_data = super(ResponseModelViewSet, self).destroy(request, *args, **kwargs)
        self.response_format["data"] = response_data.data
        self.response_format["status"] = True
        return Response(self.response_format)


问:
How to write a controller method's signature when url has a parameter data after the slash?
In PHP there is the possibility to recognize a parameter in the address bar by passing it in the controller's method ; for example :

```<code>http://192.168.2.49/papsp/index.php/meeting/modif/3
</code>```

In this example the data 3 is taken as parameter value for the meeting controller's method modif :

```<code>public modif($key) { ... }
</code>```

So how to proceed analogically in Spring ?

答:
You need to use the @RequestMapping annotation, along with @PathVariable with your method param. And your url will be like this /meeting/modif/{key}.

Here's how should be your code:

```<code>@RequestMapping(value = "/meeting/modif/{key}", method = RequestMethod.POST)
public void modif(@PathVariable int key) {
</code>```

Body:
In PHP there is the possibility to recognize a parameter in the address bar by passing it in the controller's method ; for example :

http://192.168.2.49/papsp/index.php/meeting/modif/3

In this example the data 3 is taken as parameter value for the meeting controller's method modif :

public modif($key) { ... }

So how to proceed analogically in Spring ?

Body:
You need to use the @RequestMapping annotation, along with @PathVariable with your method param. And your url will be like this /meeting/modif/{key}.

Here's how should be your code:

@RequestMapping(value = "/meeting/modif/{key}", method = RequestMethod.POST)
public void modif(@PathVariable int key) {


问:
How do I strip down a URL into separate parts in Bash?
I have a URL (https://example.com/someone/something) that I'd like to strip down into three variables:

https://example.com/

someone

something

I'm wondering how I can do this in Bash using grep or awk or some other tool.

To clarify, I'm not asking if there's a way to get all three variables at one go. It's perfectly fine to run three separate commands for each variable. Something like,

```<code>URL="https://example.com/someone/something"

DOMAIN=$(echo ${URL} | <some wizardry here>)

USER=$(echo ${URL} | <some wizardry here>)

THING=$(echo ${URL} | <some wizardry here>)
</code>```

答:
Pure  bash solution:

```<code>url_str="https://example.com/someone/something"
if [[ "$url_str" =~ ^(http.+)/([^/]+)/([^/]+)$ ]]; then
    domain="${BASH_REMATCH[1]}"
    section1="${BASH_REMATCH[2]}"
    section2="${BASH_REMATCH[3]}"
fi
</code>```

Results:

```<code>$ echo $domain
https://example.com
$ echo $section1
someone
$ echo $section2
something
</code>```

Body:
I have a URL (https://example.com/someone/something) that I'd like to strip down into three variables:

https://example.com/

someone

something

I'm wondering how I can do this in Bash using grep or awk or some other tool.

To clarify, I'm not asking if there's a way to get all three variables at one go. It's perfectly fine to run three separate commands for each variable. Something like,

URL="https://example.com/someone/something"

DOMAIN=$(echo ${URL} | <some wizardry here>)

USER=$(echo ${URL} | <some wizardry here>)

THING=$(echo ${URL} | <some wizardry here>)

Body:
Pure  bash solution:

url_str="https://example.com/someone/something"
if [[ "$url_str" =~ ^(http.+)/([^/]+)/([^/]+)$ ]]; then
    domain="${BASH_REMATCH[1]}"
    section1="${BASH_REMATCH[2]}"
    section2="${BASH_REMATCH[3]}"
fi

Results:

$ echo $domain
https://example.com
$ echo $section1
someone
$ echo $section2
something


问:
how to get multiple columns using HBase shell
I have Randonnee Table with 2 family columns

```<code>Info: Name, region, suite
Tech: distance, denivele
</code>```

I have this Data on my Table Randonnee

```<code>      (id, Name, region, distance, denivele, suite)

      (1, 'Monts du Djurdjura', 'Tizi Ouzou', 35, 1000, NULL);

      (2, 'Circuit de Misserghin', 'Oran', 25 , 514, NULL);

      (3, 'Montagne de Murdjadju', 'Oran', 31, 1100, NULL);

      (4, 'Canastel', 'Oran', 18, 890, 3);

      (5, 'Yama Gouraya', 'Bejaia', 19, 900, NULL);

      (6, 'Sidi Makhlouf', 'Blida', 8, 165, 8);

      (7, 'Tikjda', 'Tizi Ouzou', 10, 1900, NULL);

      (8, 'Feroukha', 'Blida', 14.18, 454, NULL);

      (9, 'Chrea Azzazga', 'Tizi Ouzou', 6.23, 1548, 11);
</code>```

I want to get the distance of randonne where Name is 'Montagne de Murdjadu'

I tryed this query :

```<code>scan 'randonnee',{COLUMN=>'info:Name',FILTER=>"ValueFilter(=, 'binary:Montagne de Murdjadju')"}
</code>```

but the problem that she gives me the id in return, not the distance

```<code>ROW                   COLUMN+CELL
  3                    column=info:nom, timestamp=1509960875652, value=Montagne de Murdjadju
</code>```

How I get the distance?

答:
You can use the SingleColumnValueFilter. In hbase shell you can do the following to get the distance

```<code>import org.apache.hadoop.hbase.filter.CompareFilter
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter
import org.apache.hadoop.hbase.util.Bytes

scan 'randonnee', {COLUMNS=>['tech:distance'], FILTER=>SingleColumnValueFilter.new(Bytes.toBytes('info'),Bytes.toBytes('name'),CompareFilter::CompareOp.valueOf('EQUAL'),Bytes.toBytes('Montagne de Murdjadju'))}
</code>```

Body:
I have Randonnee Table with 2 family columns

Info: Name, region, suite
Tech: distance, denivele

I have this Data on my Table Randonnee

      (id, Name, region, distance, denivele, suite)

      (1, 'Monts du Djurdjura', 'Tizi Ouzou', 35, 1000, NULL);

      (2, 'Circuit de Misserghin', 'Oran', 25 , 514, NULL);

      (3, 'Montagne de Murdjadju', 'Oran', 31, 1100, NULL);

      (4, 'Canastel', 'Oran', 18, 890, 3);

      (5, 'Yama Gouraya', 'Bejaia', 19, 900, NULL);

      (6, 'Sidi Makhlouf', 'Blida', 8, 165, 8);

      (7, 'Tikjda', 'Tizi Ouzou', 10, 1900, NULL);

      (8, 'Feroukha', 'Blida', 14.18, 454, NULL);

      (9, 'Chrea Azzazga', 'Tizi Ouzou', 6.23, 1548, 11);

I want to get the distance of randonne where Name is 'Montagne de Murdjadu'

I tryed this query :

scan 'randonnee',{COLUMN=>'info:Name',FILTER=>"ValueFilter(=, 'binary:Montagne de Murdjadju')"}

but the problem that she gives me the id in return, not the distance

ROW                   COLUMN+CELL
  3                    column=info:nom, timestamp=1509960875652, value=Montagne de Murdjadju

How I get the distance?

Body:
You can use the SingleColumnValueFilter. In hbase shell you can do the following to get the distance

import org.apache.hadoop.hbase.filter.CompareFilter
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter
import org.apache.hadoop.hbase.util.Bytes

scan 'randonnee', {COLUMNS=>['tech:distance'], FILTER=>SingleColumnValueFilter.new(Bytes.toBytes('info'),Bytes.toBytes('name'),CompareFilter::CompareOp.valueOf('EQUAL'),Bytes.toBytes('Montagne de Murdjadju'))}


问:
Virtual box Host only Network Interface
When I am trying to add a new Network Interface for Host only network, Virtual Box version :Version 5.0.22 r108108.

I am getting a following error:

```
Could not find Host Interface Networking driver! Please reinstall.

Result Code:
E_FAIL (0x80004005)
Component:
HostNetworkInterfaceWrap
Interface:
IHostNetworkInterface {455f8c45-44a0-a470-ba20-27890b96dba9}
```

答: open virtual box -> select the default virtual machine-> setting -> network -> change host-only to bridged networking -> start virtual machine -> Open docker quickStart Terminal to connect</p>

Title: Virtual box Host only Network Interface

Body:
When I am trying to add a new Network Interface for Host only network, Virtual Box version :Version 5.0.22 r108108.

I am getting a following error:

Could not find Host Interface Networking driver! Please reinstall.

Result Code:
E_FAIL (0x80004005)
Component:
HostNetworkInterfaceWrap
Interface:
IHostNetworkInterface {455f8c45-44a0-a470-ba20-27890b96dba9}


问:
Culebra in AndroidViewClient returns "RuntimeError: ERROR: Connecting to <socket... [Errno 111] Connection refused
Trying to use any culebra (AndroidViewClient) command returns following error:

$culebra -G

Traceback (most recent call last): File "/usr/local/bin/culebra", line
  4, in import('pkg_resources').run_script('androidviewclient==13.5.0',
  'culebra') File
  "/usr/lib/python2.7/dist-packages/pkg_resources/init.py", line 739, in
  run_script self.require(requires)[0].run_script(script_name, ns) File
  "/usr/lib/python2.7/dist-packages/pkg_resources/init.py", line 1494,
  in run_script exec(code, namespace, namespace) File
  "/usr/local/lib/python2.7/dist-packages/androidviewclient-13.5.0-py2.7.egg/EGG-INFO/scripts/culebra",
  line 1168, in device, serialno =
  ViewClient.connectToDeviceOrExit(serialno=serialno, **kwargs1) File
  "/usr/local/lib/python2.7/dist-packages/androidviewclient-13.5.0-py2.7.egg/com/dtmilano/android/viewclient.py",
  line 2697, in connectToDeviceOrExit device =
  adbclient.AdbClient(serialno, ignoreversioncheck=ignoreversioncheck,
  timeout=timeout) File
  "/usr/local/lib/python2.7/dist-packages/androidviewclient-13.5.0-py2.7.egg/com/dtmilano/android/adb/adbclient.py",
  line 179, in init self.socket = AdbClient.connect(self.hostname,
  self.port, self.timeout) File
  "/usr/local/lib/python2.7/dist-packages/androidviewclient-13.5.0-py2.7.egg/com/dtmilano/android/adb/adbclient.py",
  line 252, in connect raise RuntimeError("ERROR: Connecting to %s:%d:
  %s.\nIs adb running on your computer?" % (s, port, ex)) RuntimeError:
  ERROR: Connecting to :5037: [Errno 111] Connection refused. Is adb
  running on your computer?

Adb is debinitely running; "adb devices" lists connected device; "adb push", "adb pull","adb shell", all work fine.

Opening firewall, setting path, reinstalling AndroidViewClient, updating software make no difference.

A previous post "[androidviewclient - Can't connect to the device on vm with port forwarding][1]" concerns very similar error.

His solution (below) does not work for me:

Blockquote

Solved - I changed localhost back to 127.0.0.1 in hosts file and it solves an issue...

Blockquote

Any ideas?

androidviewclient - Can't connect to the device on vm with port forwarding

答:
Setting default from JDK 1.7 to JDK 1.8 solved this problem.
Still getting an error message ("...there are no connected devices"), however since adb devices lists the phone, shouldn't be hard to figure out.

Marking this question solved


问:
Toggle Flashlight in Camera2 without Interrupting Preview
Just started using the Camera2 framework because of the increased control it provides over the low-level functions of the camera. However, I am having some trouble turning the flashlight on and off quickly. With the old Camera API, I could toggle flash while supplying a preview by:

```<code>try
{
    android.hardware.Camera.Parameters parameters = c.getParameters();
    if (parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_OFF))
    {
        parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
        Log.i("HeartBeatAlgorithm", "LightOn");
    }
    else if (parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_TORCH))
    {
        parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
        Log.i("HeartBeatAlgorithm", "LightOff");
    }
    c.setParameters(parameters);
}
catch (Exception exception)
{
    c.release();
    c = null;
}
</code>```

And the flashlight would quickly turn on or off, without any noticeable interrupt. With Camera2, however, it seems as though flash mode is a property of the CaptureSession, meaning an entirely new CaptureSession needs to be created to change flash mode, i.e.:

```<code>try
{
    SurfaceTexture texture = mTextureView.getSurfaceTexture();
    assert texture != null;

    texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
    Surface surface = new Surface(texture);
    mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);

    if (mLightNowOn == true)
    {
        mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
    }
    else
    {
        mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
    }

    mPreviewRequestBuilder.addTarget(surface);
    mPreviewRequest = mPreviewRequestBuilder.build();
    mCameraDevice.createCaptureSession(Arrays.asList(surface), mSessionStateCallback, null);
}
catch (CameraAccessException e)
{
    e.printStackTrace();
}
</code>```

As is mentioned in the developer docs, "Creating a session is an expensive operation and can take several hundred milliseconds, since it requires configuring the camera device's internal pipelines and allocating memory buffers for sending images to the desired targets." It definitely does, and there is a noticeable delay in my app when toggling flash mode.

I really need to be able to quickly toggle flash modes without interrupting the preview so much. Is there any way around this, or is it unavoidable due to the new API pipeline?

答:
It's not true that completely new capture session has to be created every time just to change flash mode. Instead, you can create repeating preview request on existing capture session and just setNewRepeating request every time such as this:

mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
...
mPreviewRequest = mPreviewRequestBuilder.build();
...
mCaptureSession.setRepeatingRequest(mPreviewRequest, captureCallBack, backgroundHandler);

You can repeat this sequence numerous times.

Body:
Just started using the Camera2 framework because of the increased control it provides over the low-level functions of the camera. However, I am having some trouble turning the flashlight on and off quickly. With the old Camera API, I could toggle flash while supplying a preview by:

try
{
    android.hardware.Camera.Parameters parameters = c.getParameters();
    if (parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_OFF))
    {
        parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
        Log.i("HeartBeatAlgorithm", "LightOn");
    }
    else if (parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_TORCH))
    {
        parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
        Log.i("HeartBeatAlgorithm", "LightOff");
    }
    c.setParameters(parameters);
}
catch (Exception exception)
{
    c.release();
    c = null;
}

And the flashlight would quickly turn on or off, without any noticeable interrupt. With Camera2, however, it seems as though flash mode is a property of the CaptureSession, meaning an entirely new CaptureSession needs to be created to change flash mode, i.e.:

try
{
    SurfaceTexture texture = mTextureView.getSurfaceTexture();
    assert texture != null;

    texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
    Surface surface = new Surface(texture);
    mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);

    if (mLightNowOn == true)
    {
        mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
    }
    else
    {
        mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
    }

    mPreviewRequestBuilder.addTarget(surface);
    mPreviewRequest = mPreviewRequestBuilder.build();
    mCameraDevice.createCaptureSession(Arrays.asList(surface), mSessionStateCallback, null);
}
catch (CameraAccessException e)
{
    e.printStackTrace();
}

As is mentioned in the developer docs, "Creating a session is an expensive operation and can take several hundred milliseconds, since it requires configuring the camera device's internal pipelines and allocating memory buffers for sending images to the desired targets." It definitely does, and there is a noticeable delay in my app when toggling flash mode.

I really need to be able to quickly toggle flash modes without interrupting the preview so much. Is there any way around this, or is it unavoidable due to the new API pipeline?


问:
Raw html method in typescript
I need to apply different styles for different lines of a paragraph which has binded dynamically in typescript

I tried to split my string variable by line but I am having tags in my variable.Can anyone provide raw html method in typescipt not in html

Can anyone provide me solution in typescript

kindly find below paragraph which is styled differently for different lines which i need as output

答:
You can do that by adding a fade to transparent gradient over your text paragraf.

Example on codepen

HTML

```<code><div class="box">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
     eiusmod tempor incididunt ut labore et dolore
     magna aliqua. Ut enim ad minim veniam, quis nostrud
     exercitation ullamco. </p>
</div>
</code>```

CSS

```<code>.box {
  width: 320px;
  height: 100px;
  border: 2px solid #000;
  margin: 0 auto;
  padding: 1rem;
  overflow: hidden;
}

.box > p {
  margin: 0;
  -webkit-mask-image: -webkit-gradient(linear, left 50%, left bottom, from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
}
</code>```

Title: Raw html method in typescript

Body:
You can do that by adding a fade to transparent gradient over your text paragraf.

Example on codepen

HTML

<div class="box">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
     eiusmod tempor incididunt ut labore et dolore
     magna aliqua. Ut enim ad minim veniam, quis nostrud
     exercitation ullamco. </p>
</div>

CSS

.box {
  width: 320px;
  height: 100px;
  border: 2px solid #000;
  margin: 0 auto;
  padding: 1rem;
  overflow: hidden;
}

.box > p {
  margin: 0;
  -webkit-mask-image: -webkit-gradient(linear, left 50%, left bottom, from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
}