问:
String is not recognized as valid date time
Description:

In my application user is allowed to insert date in string format EX- "01/01/2000"and I'm parsing this string value using DateTime.Parse("01/01/00"); it is working fine. But in few case it is breaking.

Case 1:

Input : "01/01/00"

Code: DateTime.Parse("01/01/00");

Output: 01/01/2000

Case 2:

Input : "01/01/000"

Code: DateTime.Parse("01/01/000");

Output: Getting error "String is not recognized as valid date time."

Case 3:

Input : "01/01/0000"

Code: DateTime.Parse("01/01/0000");

Output: Getting error "String is not recognized as valid date time."

How to parse 000 or 0000 as correct year ?

答:
If you check your inputs you type input="01/01/000" it adds an extra zero and makes value="01/01/0000" which does not exist and thus throws exception. try
input="01/01/100" and you will get output as "01/01/0100"
range is limited to last two digits and if you type any number in range of (00 to 29) you will get date in 2000+ ie if input=("01/01/29") you get output=("01/01/2029") but if you type input=("01/01/30") you will get output=("01/01/1930")


来源: stackexchange

问:
Does scaling the values to [0,1] affect the CNN learning procedure?
I am working on semantic segmentation using CNNs.

I have normalized the values of images to range [0,1]. I have trained my network many times, learning curve seems is learning well, however, the output is always black image. My question is does really scaling affects the learning or should the range of pixel values remains in 0-255 range?

Thanks a lot.

答: In general, it doesn't affect the training. In many situations, [0 1] is actually better than [0 255] for training a DNN since the latter may cause some numerical issues in learning the first layer weights if you don't use lower learning rates in the first layer since w' = y' * x, where ' denotes derivative.</p>

ContentLicense: CC BY-SA 3.0


问:
Google CSE (Custom Search Engine) - How to determine term user searched for (using jQuery)?
I have a Google CSE embedded using this:

```<code>google.load('search', '1', {language : 'en', style : google.loader.themes.SHINY});
google.setOnLoadCallback(function() {
var options = {};
options[google.search.Search.RESTRICT_EXTENDED_ARGS] = {'sort': 'date'};
var customSearchControl = new google.search.CustomSearchControl('',options);
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
customSearchControl.draw('cse');
</code>```

I'd like to determine/display the search term the user searches for, but I can't seem to get the search term out of the Google CSE input after the user clicks "search".

How can I do this?

答: Shouldnt the search terms be available in the header that is returned, I'm wondering if you cant get access to the actual ajax request and then use jquery to access the header object.  I know when doing a regular search on google the keywords are passed along in the header.</p>

Body:
I have a Google CSE embedded using this:

google.load('search', '1', {language : 'en', style : google.loader.themes.SHINY});
google.setOnLoadCallback(function() {
var options = {};
options[google.search.Search.RESTRICT_EXTENDED_ARGS] = {'sort': 'date'};
var customSearchControl = new google.search.CustomSearchControl('',options);
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
customSearchControl.draw('cse');

I'd like to determine/display the search term the user searches for, but I can't seem to get the search term out of the Google CSE input after the user clicks "search".

How can I do this?

ContentLicense: CC BY-SA 2.5


问:
Testing Java Optional
I'm looking into Java Optional and testing some usecases beyond the standard ones.

ok, let's take this example:

```<code>public void increment(Integer value) {
        if (currentValue != null && endValue != null && currentValue < (endValue - value)) {
            currentValue+=value;
        }
    }
</code>```

currentValue and endValue are Integer.

Can the example above be converted in Java8 using Optional?

I was thinking something like that:

```<code>public void increment(Integer value) {
        currentValue.filter(a-> a < (endValue.get()-value)).map(???);
    }
</code>```

where currentValue and endValue are Optional<Integer>

I'm actually stuck with the .map Function.

I would appreciate any suggestion, thanks

答:
How about this?

```<code>currentValue = currentValue.filter(it -> endValue.isPresent())
                           .filter(it -> it < endValue.get() - value)
                           .map(it -> Optional.of(it + value))
                           .orElse(currentValue);
</code>```

OR move the value into left side is more simpler than above.

```<code>currentValue = currentValue.map(it -> it + value)
                           .filter(it -> endValue.isPresent())
                           .filter(result -> result < endValue.get() )
                           .map(Optional::of)
                           .orElse(currentValue);
</code>```

OR

```<code>currentValue = currentValue.filter(it -> it < endValue.map(end -> end - value)
                                                      .orElse(Integer.MIN_VALUE))
                           .map(it -> Optional.of(it + value))
                           .orElse(currentValue);
</code>```

OR move the value into left side is more simpler than above.

```<code>currentValue=currentValue.map(it -> it + value)
                         .filter(result->result<endValue.orElse(Integer.MIN_VALUE))
                         .map(Optional::of)
                         .orElse(currentValue);
</code>```

OR using Optional#flatMap instead:

```<code>currentValue = currentValue.flatMap(it ->
    endValue.filter(end -> it < end - value)
            .map(end -> Optional.of(it + value))
            .orElse(currentValue)
);
</code>```

OR move the value into the left side then can using ternary-operator simplified:

```<code>currentValue = currentValue.map(it -> it + value).flatMap(result ->
    endValue.filter(end -> result < end)
            .isPresent() ? Optional.of(result) : currentValue
);
</code>```

Title: Testing Java Optional

Body:
I'm looking into Java Optional and testing some usecases beyond the standard ones.

ok, let's take this example:

public void increment(Integer value) {
        if (currentValue != null && endValue != null && currentValue < (endValue - value)) {
            currentValue+=value;
        }
    }

currentValue and endValue are Integer.

Can the example above be converted in Java8 using Optional?

I was thinking something like that:

public void increment(Integer value) {
        currentValue.filter(a-> a < (endValue.get()-value)).map(???);
    }

where currentValue and endValue are Optional<Integer>

I'm actually stuck with the .map Function.

I would appreciate any suggestion, thanks

Body:
How about this?

currentValue = currentValue.filter(it -> endValue.isPresent())
                           .filter(it -> it < endValue.get() - value)
                           .map(it -> Optional.of(it + value))
                           .orElse(currentValue);

OR move the value into left side is more simpler than above.

currentValue = currentValue.map(it -> it + value)
                           .filter(it -> endValue.isPresent())
                           .filter(result -> result < endValue.get() )
                           .map(Optional::of)
                           .orElse(currentValue);

OR

currentValue = currentValue.filter(it -> it < endValue.map(end -> end - value)
                                                      .orElse(Integer.MIN_VALUE))
                           .map(it -> Optional.of(it + value))
                           .orElse(currentValue);

OR move the value into left side is more simpler than above.

currentValue=currentValue.map(it -> it + value)
                         .filter(result->result<endValue.orElse(Integer.MIN_VALUE))
                         .map(Optional::of)
                         .orElse(currentValue);

OR using Optional#flatMap instead:

currentValue = currentValue.flatMap(it ->
    endValue.filter(end -> it < end - value)
            .map(end -> Optional.of(it + value))
            .orElse(currentValue)
);

OR move the value into the left side then can using ternary-operator simplified:

currentValue = currentValue.map(it -> it + value).flatMap(result ->
    endValue.filter(end -> result < end)
            .isPresent() ? Optional.of(result) : currentValue
);


问:
Bind dynamically generated forms for ajax validation?
I am generating many forms on a page dynamically using JS.

Each form corresponds to a yii2 model (which has its rules set up for each attribute).

I would like each form to validate all elements (name, email text inputs) to validate with ajax (as they would normally do as if I only had one form).

I am finding that using the method pointed out here:
https://yii2-cookbook.readthedocs.io/forms-activeform-js/

```<code>`$('#contact-form').yiiActiveForm('validateAttribute', 'contactform-name');`
</code>```

gives JS error:

```<code> yii.activeForm.js:276 Uncaught TypeError: Cannot read property 'attributes' of undefined
    at jQuery.fn.init.find (yii.activeForm.js:276)
    at jQuery.fn.init.validateAttribute (yii.activeForm.js:268)
    at jQuery.fn.init.$.fn.yiiActiveForm (yii.activeForm.js:16)
    at HTMLInputElement.<anonymous> (search-follow.js:130)
</code>```

Is there a way to bind dynamically generated forms to yii2 validation?
(not just individual fields but rather entire forms, each with a unique ID).

The documentation on Yii2 js form validation seems not so much unfortunately

help much appreciated

g

答:
I put shortly some code snippets which do ajax form operations using Yii 2.

View (_ajaxForm.php: ajax form)

```<code><?php $form = \yii\widgets\ActiveForm::begin([
    // pay attention this config.
    'id' => 'account-form',
    'enableClientValidation' => true,
    'enableAjaxValidation' => true,
    // validation URL via ajax
    'validationUrl' => \yii\helpers\Url::to(['/account/do-ajax-request', 'userId'=>$model->id, 'op' => 'validate-form']),
]); ?>

<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?>

<?= $form->field($model, 'passwordConfirm')->passwordInput(['maxlength' => true]) ?>

<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>

<div class="form-group">
    <?= \yii\helpers\Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php \yii\widgets\ActiveForm::end(); ?>

<script type="text/javascript">
    $(function () {
        // URL to save form via ajax
        var formSaveUrl='<?= \yii\helpers\Url::to(['/account/do-ajax-request', 'userId'=>$model->id, 'op' => 'save-form']) ?>';

        // post form via ajax to save
        $(document).on('beforeSubmit', '#account-form', function () {
            $.post(formSaveUrl, $(this).serialize(), function (data) {
                alert(data.message);
            });
            return false;
        });

    });
</script>
</code>```

Controller (AccountController.php: function which performs ajax operations)

```<code>public function actionDoAjaxRequest($userId, $op)
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    $model = $this->findModel($userId);
    $model->load(Yii::$app->request->post());

    // validate form
    if ($op == 'validate-form') {
        $data = \yii\widgets\ActiveForm::validate($model);
    // save form
    } else if ($op == 'save-form') {
        if ($model->save()) {
            $data['result'] = true;
            $data['message'] = 'Success!';
        } else {
            $data['result'] = false;
            $data['message'] = 'Failed!';
        }
    }

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

Body:
I am generating many forms on a page dynamically using JS.

Each form corresponds to a yii2 model (which has its rules set up for each attribute).

I would like each form to validate all elements (name, email text inputs) to validate with ajax (as they would normally do as if I only had one form).

I am finding that using the method pointed out here:
https://yii2-cookbook.readthedocs.io/forms-activeform-js/

`$('#contact-form').yiiActiveForm('validateAttribute', 'contactform-name');`

gives JS error:

 yii.activeForm.js:276 Uncaught TypeError: Cannot read property 'attributes' of undefined
    at jQuery.fn.init.find (yii.activeForm.js:276)
    at jQuery.fn.init.validateAttribute (yii.activeForm.js:268)
    at jQuery.fn.init.$.fn.yiiActiveForm (yii.activeForm.js:16)
    at HTMLInputElement.<anonymous> (search-follow.js:130)

Is there a way to bind dynamically generated forms to yii2 validation?
(not just individual fields but rather entire forms, each with a unique ID).

The documentation on Yii2 js form validation seems not so much unfortunately

help much appreciated

g

Body:
I put shortly some code snippets which do ajax form operations using Yii 2.

View (_ajaxForm.php: ajax form)

<?php $form = \yii\widgets\ActiveForm::begin([
    // pay attention this config.
    'id' => 'account-form',
    'enableClientValidation' => true,
    'enableAjaxValidation' => true,
    // validation URL via ajax
    'validationUrl' => \yii\helpers\Url::to(['/account/do-ajax-request', 'userId'=>$model->id, 'op' => 'validate-form']),
]); ?>

<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?>

<?= $form->field($model, 'passwordConfirm')->passwordInput(['maxlength' => true]) ?>

<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>

<div class="form-group">
    <?= \yii\helpers\Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php \yii\widgets\ActiveForm::end(); ?>

<script type="text/javascript">
    $(function () {
        // URL to save form via ajax
        var formSaveUrl='<?= \yii\helpers\Url::to(['/account/do-ajax-request', 'userId'=>$model->id, 'op' => 'save-form']) ?>';

        // post form via ajax to save
        $(document).on('beforeSubmit', '#account-form', function () {
            $.post(formSaveUrl, $(this).serialize(), function (data) {
                alert(data.message);
            });
            return false;
        });

    });
</script>

Controller (AccountController.php: function which performs ajax operations)

public function actionDoAjaxRequest($userId, $op)
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    $model = $this->findModel($userId);
    $model->load(Yii::$app->request->post());

    // validate form
    if ($op == 'validate-form') {
        $data = \yii\widgets\ActiveForm::validate($model);
    // save form
    } else if ($op == 'save-form') {
        if ($model->save()) {
            $data['result'] = true;
            $data['message'] = 'Success!';
        } else {
            $data['result'] = false;
            $data['message'] = 'Failed!';
        }
    }

    return $data;
}


问:
Self-join Query
Is it possible to do parent-child query just using join without looping through temporary table?

Database sample :

```<code>menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0002   Master Nominal      A0001   /master/nominal.aspx
A0003   Master Satuan Other A0001   /master/satuan.aspx
A0004   Master Kondisi      A0000   /master/kondisi.aspx
A0005   Master Tujuan       A0003   /master/tujuan.aspx
A0006   Master Item         A0003   /master/item.aspx
A0007   Master Warehouse    A0000   /master/warehouse.aspx
A0008   Master Kapal        A0006   /master/kapal.aspx
</code>```

Desired result if choosed uri = '/master/kapal.aspx' :

```<code>menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0003   Master Satuan Other A0001   /master/satuan.aspx
A0006   Master Item         A0003   /master/item.aspx
A0008   Master Kapal        A0006   /master/kapal.aspx
</code>```

Desired result if choosed uri = /master/tujuan.aspx' :

```<code>menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0005   Master Tujuan       A0003   /master/tujuan.aspx
</code>```

Sample query :

```<code>declare @menuid varchar(255) = 'menuid'
declare @parent varchar(255) = 'parent'
declare @temp_parent varchar(255)
declare @i smallint = 0

delete from temp_menu
while (@menuid <> @parent)
begin
  if(@i = 0)
  begin
    insert into temp_menu
    select * from menu where uri = '/master/kapal.aspx'
    select @menuid = menuid, @parent = parent from menu where uri = '/master/kapal.aspx'
    set @i = 1;
    end
  else
  begin
    insert into temp_menu
    select * from menu where menuid = @parent
    select @menuid = menuid, @temp_parent = parent from menu where menuid = @parent
    set @parent = @temp_parent;
    end
end
select * from temp_menu
</code>```

Sample with hieararchy :

```<code>A0000
|_______________________
|               |       |
A0001           A0004   A0007
|________
|       |
A0002   A0003
        |_______
        |       |
        A0005   A0006
                |
                A0008
</code>```

UPDATED :
I want to get all rows from  the longest branch possible from nodes parent to menuid and stopped if the parent same with menuid or there is no menuid match with parent.

ADDED WITH SCRIPT AND SAMPLES

```<code>IF OBJECT_ID('dbo.menu', 'U') IS NOT NULL
  DROP TABLE dbo.menu
GO

IF OBJECT_ID('dbo.temp_menu', 'U') IS NOT NULL
  DROP TABLE dbo.temp_menu
GO

IF OBJECTPROPERTY(object_id('dbo.sp_get_parent'), N'IsProcedure') = 1
  DROP PROCEDURE dbo.sp_get_parent
GO

create table dbo.menu (
menuid varchar(255)
, name varchar(255)
, parent varchar(255)
, uri varchar(255)
);

insert into dbo.menu (menuid, name, parent, uri)
values ('A0000', 'Master', 'A0000', '#')
, ('A0001', 'Rekening', 'A0000', '/master/rekening.aspx')
, ('A0002', 'Master Nominal', 'A0001', '/master/nominal.aspx')
, ('A0003', 'Master Satuan Other', 'A0001', '/master/satuan.aspx')
, ('A0004', 'Master Kondisi', 'A0000', '/master/kondisi.aspx')
, ('A0005', 'Master Tujuan', 'A0003', '/master/tujuan.aspx')
, ('A0006', 'Master Item', 'A0003', '/master/item.aspx')
, ('A0007', 'Master Warehouse', 'A0000', '/master/warehouse.aspx')
, ('A0008', 'Master Kapal', 'A0006', '/master/kapal.aspx');

create table dbo.temp_menu (
menuid varchar(255)
, name varchar(255)
, parent varchar(255)
, uri varchar(255)
);

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[sp_get_parent]
@uri VARCHAR (255)
AS

declare @menuid varchar(255) = 'menuid'
declare @parent varchar(255) = 'parent'
declare @temp_parent varchar(255)
declare @i smallint = 0

delete from temp_menu
while (@menuid <> @parent)
begin
  if(@i = 0)
  begin
    insert into temp_menu
    select * from menu where uri = @uri
    select @menuid = menuid, @parent = parent from menu where uri = @uri
    set @i = 1;
  end
  else
  begin
    insert into temp_menu
    select * from menu where menuid = @parent
    select @menuid = menuid, @temp_parent = parent from menu where menuid = @parent
    set @parent = @temp_parent;
  end
end
select * from temp_menu order by menuid asc
GO
</code>```

For desired sample above can try this query :

```<code>sp_get_parent '/master/kapal.aspx'
</code>```

AND

```<code>sp_get_parent '/master/tujuan.aspx'
</code>```

答:
In SQL Server, the answer to every question about how to query hierarchical data is using a recursive common table expression.

In your case, since you want to get the longest branch, you should add a counting column:

```<code>;WITH CTE AS
(
     SELECT menuid, name, parent, url, 0 as level
     FROM menu WHERE parent = menuid -- Usually, the parent column is simply nullable
     UNION ALL
     SELECT menu.menuid, menu.name, menu.parent, menu.url, level + 1
     FROM menu
     INNER JOIN CTE ON menu.parent = CTE.menuid
     AND menu.parent <> CTE.parent -- This is why parent column is nullable :-)
)

SELECT TOP 1 *
FROM CTE
ORDER BY Level DESC
</code>```

This query will get you the leaf that's the furthest away from it's top parent.

Update

Based on your comment, I think this is what you are looking for:

```<code>;WITH CTERecursion AS
(
     SELECT menuid,
            name,
            parent,
            url,
            0 as level,
            menuid as TopLevelParent
     FROM menu WHERE parent = menuid -- Usually, the parent column is simply nullable

     UNION ALL
     SELECT menu.menuid,
            menu.name,
            menu.parent,
            menu.url,
            level + 1,
            TopLevelParent
     FROM menu
     INNER JOIN CTERecursion CTE ON menu.parent = CTE.menuid
     AND menu.menuid <> CTE.menuid -- This is why parent column is nullable :-)

), CTELongestPath AS
(
    SELECT TOP 1 TopLevelParent
    FROM CTERecursion
    ORDER BY Level DESC
)

SELECT menuid, name, parent, url
FROM CTERecursion r
INNER JOIN CTELongestPath l ON r.TopLevelParent = r.TopLevelParent
</code>```

Update #2

Now that your question is changed, you seem to just want to traverse from leaf to top parent. In that case, your recursive CTE should be something like this:

```<code>DECLARE @url varchar(100) = '/master/kapal.aspx';

;WITH CTERecursion AS
(
     SELECT menuid,
            name,
            parent,
            url
     FROM menu
     WHERE url = @url

     UNION ALL
     SELECT menu.menuid,
            menu.name,
            menu.parent,
            menu.url
     FROM menu
     INNER JOIN CTERecursion CTE ON menu.menuid = CTE.parent
     AND menu.menuid <> CTE.menuid -- This is why parent column is nullable :-)
)

SELECT menuid, name, parent, url
FROM CTERecursion
</code>```

Title: Self-join Query

Body:
Is it possible to do parent-child query just using join without looping through temporary table?

Database sample :

menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0002   Master Nominal      A0001   /master/nominal.aspx
A0003   Master Satuan Other A0001   /master/satuan.aspx
A0004   Master Kondisi      A0000   /master/kondisi.aspx
A0005   Master Tujuan       A0003   /master/tujuan.aspx
A0006   Master Item         A0003   /master/item.aspx
A0007   Master Warehouse    A0000   /master/warehouse.aspx
A0008   Master Kapal        A0006   /master/kapal.aspx

Desired result if choosed uri = '/master/kapal.aspx' :

menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0003   Master Satuan Other A0001   /master/satuan.aspx
A0006   Master Item         A0003   /master/item.aspx
A0008   Master Kapal        A0006   /master/kapal.aspx

Desired result if choosed uri = /master/tujuan.aspx' :

menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0005   Master Tujuan       A0003   /master/tujuan.aspx

Sample query :

declare @menuid varchar(255) = 'menuid'
declare @parent varchar(255) = 'parent'
declare @temp_parent varchar(255)
declare @i smallint = 0

delete from temp_menu
while (@menuid <> @parent)
begin
  if(@i = 0)
  begin
    insert into temp_menu
    select * from menu where uri = '/master/kapal.aspx'
    select @menuid = menuid, @parent = parent from menu where uri = '/master/kapal.aspx'
    set @i = 1;
    end
  else
  begin
    insert into temp_menu
    select * from menu where menuid = @parent
    select @menuid = menuid, @temp_parent = parent from menu where menuid = @parent
    set @parent = @temp_parent;
    end
end
select * from temp_menu

Sample with hieararchy :

A0000
|_______________________
|               |       |
A0001           A0004   A0007
|________
|       |
A0002   A0003
        |_______
        |       |
        A0005   A0006
                |
                A0008

UPDATED :
I want to get all rows from  the longest branch possible from nodes parent to menuid and stopped if the parent same with menuid or there is no menuid match with parent.

ADDED WITH SCRIPT AND SAMPLES

IF OBJECT_ID('dbo.menu', 'U') IS NOT NULL
  DROP TABLE dbo.menu
GO

IF OBJECT_ID('dbo.temp_menu', 'U') IS NOT NULL
  DROP TABLE dbo.temp_menu
GO

IF OBJECTPROPERTY(object_id('dbo.sp_get_parent'), N'IsProcedure') = 1
  DROP PROCEDURE dbo.sp_get_parent
GO

create table dbo.menu (
menuid varchar(255)
, name varchar(255)
, parent varchar(255)
, uri varchar(255)
);

insert into dbo.menu (menuid, name, parent, uri)
values ('A0000', 'Master', 'A0000', '#')
, ('A0001', 'Rekening', 'A0000', '/master/rekening.aspx')
, ('A0002', 'Master Nominal', 'A0001', '/master/nominal.aspx')
, ('A0003', 'Master Satuan Other', 'A0001', '/master/satuan.aspx')
, ('A0004', 'Master Kondisi', 'A0000', '/master/kondisi.aspx')
, ('A0005', 'Master Tujuan', 'A0003', '/master/tujuan.aspx')
, ('A0006', 'Master Item', 'A0003', '/master/item.aspx')
, ('A0007', 'Master Warehouse', 'A0000', '/master/warehouse.aspx')
, ('A0008', 'Master Kapal', 'A0006', '/master/kapal.aspx');

create table dbo.temp_menu (
menuid varchar(255)
, name varchar(255)
, parent varchar(255)
, uri varchar(255)
);

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[sp_get_parent]
@uri VARCHAR (255)
AS

declare @menuid varchar(255) = 'menuid'
declare @parent varchar(255) = 'parent'
declare @temp_parent varchar(255)
declare @i smallint = 0

delete from temp_menu
while (@menuid <> @parent)
begin
  if(@i = 0)
  begin
    insert into temp_menu
    select * from menu where uri = @uri
    select @menuid = menuid, @parent = parent from menu where uri = @uri
    set @i = 1;
  end
  else
  begin
    insert into temp_menu
    select * from menu where menuid = @parent
    select @menuid = menuid, @temp_parent = parent from menu where menuid = @parent
    set @parent = @temp_parent;
  end
end
select * from temp_menu order by menuid asc
GO

For desired sample above can try this query :

sp_get_parent '/master/kapal.aspx'

AND

sp_get_parent '/master/tujuan.aspx'

Body:
In SQL Server, the answer to every question about how to query hierarchical data is using a recursive common table expression.

In your case, since you want to get the longest branch, you should add a counting column:

;WITH CTE AS
(
     SELECT menuid, name, parent, url, 0 as level
     FROM menu WHERE parent = menuid -- Usually, the parent column is simply nullable
     UNION ALL
     SELECT menu.menuid, menu.name, menu.parent, menu.url, level + 1
     FROM menu
     INNER JOIN CTE ON menu.parent = CTE.menuid
     AND menu.parent <> CTE.parent -- This is why parent column is nullable :-)
)

SELECT TOP 1 *
FROM CTE
ORDER BY Level DESC

This query will get you the leaf that's the furthest away from it's top parent.

Update

Based on your comment, I think this is what you are looking for:

;WITH CTERecursion AS
(
     SELECT menuid,
            name,
            parent,
            url,
            0 as level,
            menuid as TopLevelParent
     FROM menu WHERE parent = menuid -- Usually, the parent column is simply nullable

     UNION ALL
     SELECT menu.menuid,
            menu.name,
            menu.parent,
            menu.url,
            level + 1,
            TopLevelParent
     FROM menu
     INNER JOIN CTERecursion CTE ON menu.parent = CTE.menuid
     AND menu.menuid <> CTE.menuid -- This is why parent column is nullable :-)

), CTELongestPath AS
(
    SELECT TOP 1 TopLevelParent
    FROM CTERecursion
    ORDER BY Level DESC
)

SELECT menuid, name, parent, url
FROM CTERecursion r
INNER JOIN CTELongestPath l ON r.TopLevelParent = r.TopLevelParent

Update #2

Now that your question is changed, you seem to just want to traverse from leaf to top parent. In that case, your recursive CTE should be something like this:

DECLARE @url varchar(100) = '/master/kapal.aspx';

;WITH CTERecursion AS
(
     SELECT menuid,
            name,
            parent,
            url
     FROM menu
     WHERE url = @url

     UNION ALL
     SELECT menu.menuid,
            menu.name,
            menu.parent,
            menu.url
     FROM menu
     INNER JOIN CTERecursion CTE ON menu.menuid = CTE.parent
     AND menu.menuid <> CTE.menuid -- This is why parent column is nullable :-)
)

SELECT menuid, name, parent, url
FROM CTERecursion


问:
Generate an id starting from one on every new date in C# using SQL server database
Please help me to do this.
Generate an id from database but id should start from one on each new date.
Using c# and SQL server.</p>

答:
Please modify below SQL procedure based on your requirement</p>

```<code>create proc [dbo].[InsertRecord]
    as
    begin
        declare @ID int=0;
        if (select count(1) from table_1 where CONVERT(VARCHAR(10),CurrentDate,10)=CONVERT(VARCHAR(10),GETDATE(),10))=0
            begin
                set @ID=1;
            end
        else
            begin
                set @ID=(select top 1 ID from table_1 order by CurrentDate desc);
                set @ID=isnull(@ID,0)+1;
            end

        insert into table_1(ID,CurrentDate)values(@ID,GETDATE());
        select * from table_1;
    end
</code>```

Body:
Please modify below SQL procedure based on your requirement

create proc [dbo].[InsertRecord]
    as
    begin
        declare @ID int=0;
        if (select count(1) from table_1 where CONVERT(VARCHAR(10),CurrentDate,10)=CONVERT(VARCHAR(10),GETDATE(),10))=0
            begin
                set @ID=1;
            end
        else
            begin
                set @ID=(select top 1 ID from table_1 order by CurrentDate desc);
                set @ID=isnull(@ID,0)+1;
            end

        insert into table_1(ID,CurrentDate)values(@ID,GETDATE());
        select * from table_1;
    end


问:
How can i get ongoing project count in each month using MYSQL?
I have the table like this

```<code>Title    | start_date |end_date   |
------   | ---------- |---------  |
Test_pro1 | 2017-06-06 |2017-08-06 |
Test_pro2 | 2017-07-06 |2017-11-06 |
</code>```

I need the ongoing project count in each month.

```<code>Example 1 : 2017-06-06 project count = 1
Example 2 : 2017-07-06 project count = 2
Example 3 : 2017-11-06 project count = 0
</code>```

How can i write a query in MYSQL?

答:
I think the conceptually easiest way to handle this is to use a calendar table (i.e. a table just containing dates, representing each month), and join this to your current table.  The join condition is that a given year/month falls somewhere inside the range for a current project.  We can then group the result set by year/month (i.e. date), and count how many projects fall into each month.

Note that in the query below I have inlined a makeshift calendar table containing years and months for 2017 alone.  Ideally, you would have a bona fide calendar table in your schema, containing however wide a timespan you would need to cover all projects.

```<code>SELECT
    t1.year,
    t1.month,
    COUNT(t2.start_date) AS project_count
FROM
(
    SELECT 2017 AS year, 1 AS month UNION ALL
    SELECT 2017, 2  UNION ALL
    SELECT 2017, 3  UNION ALL
    SELECT 2017, 4  UNION ALL
    SELECT 2017, 5  UNION ALL
    SELECT 2017, 6  UNION ALL
    SELECT 2017, 7  UNION ALL
    SELECT 2017, 8  UNION ALL
    SELECT 2017, 9  UNION ALL
    SELECT 2017, 10 UNION ALL
    SELECT 2017, 11 UNION ALL
    SELECT 2017, 12
) t1
LEFT JOIN yourTable t2
    ON (t1.year >= YEAR(t2.start_date) AND t1.month >= MONTH(t2.start_date)) AND
       (t1.year <= YEAR(t2.end_date)   AND t1.month <= MONTH(t2.end_date))
GROUP BY t1.year, t1.month;
</code>```

In the output below I show all months for 2017.  If you only wanted to report months having a non zero count for projects, you could either switch the join to INNER JOIN or add a HAVING clause which checks the project count.

Output:

Demo here:

Rextester

Body:
I have the table like this

Title    | start_date |end_date   |
------   | ---------- |---------  |
Test_pro1 | 2017-06-06 |2017-08-06 |
Test_pro2 | 2017-07-06 |2017-11-06 |

I need the ongoing project count in each month.

Example 1 : 2017-06-06 project count = 1
Example 2 : 2017-07-06 project count = 2
Example 3 : 2017-11-06 project count = 0

How can i write a query in MYSQL?

Body:
I think the conceptually easiest way to handle this is to use a calendar table (i.e. a table just containing dates, representing each month), and join this to your current table.  The join condition is that a given year/month falls somewhere inside the range for a current project.  We can then group the result set by year/month (i.e. date), and count how many projects fall into each month.

Note that in the query below I have inlined a makeshift calendar table containing years and months for 2017 alone.  Ideally, you would have a bona fide calendar table in your schema, containing however wide a timespan you would need to cover all projects.

SELECT
    t1.year,
    t1.month,
    COUNT(t2.start_date) AS project_count
FROM
(
    SELECT 2017 AS year, 1 AS month UNION ALL
    SELECT 2017, 2  UNION ALL
    SELECT 2017, 3  UNION ALL
    SELECT 2017, 4  UNION ALL
    SELECT 2017, 5  UNION ALL
    SELECT 2017, 6  UNION ALL
    SELECT 2017, 7  UNION ALL
    SELECT 2017, 8  UNION ALL
    SELECT 2017, 9  UNION ALL
    SELECT 2017, 10 UNION ALL
    SELECT 2017, 11 UNION ALL
    SELECT 2017, 12
) t1
LEFT JOIN yourTable t2
    ON (t1.year >= YEAR(t2.start_date) AND t1.month >= MONTH(t2.start_date)) AND
       (t1.year <= YEAR(t2.end_date)   AND t1.month <= MONTH(t2.end_date))
GROUP BY t1.year, t1.month;

In the output below I show all months for 2017.  If you only wanted to report months having a non zero count for projects, you could either switch the join to INNER JOIN or add a HAVING clause which checks the project count.

Output:

Demo here:

Rextester


问:
How to obtain UCM stream and baseline with cleartool?
For build logging, I need to obtain the current stream/baseline with cleartool, but I am stuck in determining which command will give me this information.

How can I make cleartool tell me which stream/baseline I am currently looking at? It is no problem if the output needs preprocessing or filtering.

答:
If you are in a view, you can:

get the current stream

```
cleartool lsstream -cview
```

get all baselines for a component in that stream

```
cleartool lsbl -comp myComp@\myPVob -stream myStream@\myPVob
```

get all foundation baselines for that stream

```
cleartool descr -fmt "%[found_bls]CXp" stream:myStream@\myPVob
```

Don't forget that in a view on a stream with a modifiable component, what you see is not just a baseline, but a (foundation) baseline plus all the modifications done in the branch associated with said stream.

Body:
If you are in a view, you can:

get the current stream

cleartool lsstream -cview

get all baselines for a component in that stream

cleartool lsbl -comp myComp@\myPVob -stream myStream@\myPVob

get all foundation baselines for that stream

cleartool descr -fmt "%[found_bls]CXp" stream:myStream@\myPVob

Don't forget that in a view on a stream with a modifiable component, what you see is not just a baseline, but a (foundation) baseline plus all the modifications done in the branch associated with said stream.


问:
Android Studio: Flexible Gridlayout
I started to create an app with the gridlayout. After I wrote the XML-knote of the gridlayout I placed within the gridlayout several buttons.

But if I change the Android Device from Nexus N to Nexus S the Layout starts to look like this:

and the same problem with the size goes on with Nexus XL

What should I do to keep the layout size of Nexus N to all the other devices?

答:
DisplayMetrics displayMetrics = new DisplayMetrics();

context.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

height = displayMetrics.heightPixels /NumberOfButtons;

width=displayMetrics.widthPixels/3;

You need to set the button height dynamaically at the runtime
Through above code you can get height and width of screen.

Title: Android Studio: Flexible Gridlayout


问:
PHP mysql function always return false on update query
I have below function to return status, the query can update the table but it still get status ACCT_NOT_FOUND, I've been try $sql->num_rows or $sql->affected_rows but does not work.

```<code>public function user_exit($uid, $mysqli)
{
    if(empty($uid)){
        return false;
    }
    $q  = "UPDATE `users` SET last_logged_out=now() ";
    $q .= "WHERE uid='".$uid."' ";

    $sql = $mysqli->query($q);

    if($sql->num_rows !== 0){
        return true;
    }
    return false;
}

$exit = $api->user_exit($uid, $mysqli);

if($exit !== FALSE){

    $data = array('status'=>'SUCCESS_LOGOUT');

}else{

    $data = array('status'=>'ACCT_NOT_FOUND');
}
</code>```

答:
you should use $mysqli->affected_rows since you are updating not num_rows </p>

```<code> if($mysqli->affected_rows !== 0){
        return true;
    }
</code>```

<p>change the function like below </p>

```<code>public function user_exit($uid, $mysqli)
{
    if(empty($uid)){
        return false;
    }
    $q  = "UPDATE `users` SET last_logged_out=now() ";
    $q .= "WHERE uid='".$uid."' ";

    $sql = $mysqli->query($q);

    if($mysqli->affected_rows !== 0){
        return true;
    }
    return false;
}
</code>```

Body:
I have below function to return status, the query can update the table but it still get status ACCT_NOT_FOUND, I've been try $sql->num_rows or $sql->affected_rows but does not work.

public function user_exit($uid, $mysqli)
{
    if(empty($uid)){
        return false;
    }
    $q  = "UPDATE `users` SET last_logged_out=now() ";
    $q .= "WHERE uid='".$uid."' ";

    $sql = $mysqli->query($q);

    if($sql->num_rows !== 0){
        return true;
    }
    return false;
}

$exit = $api->user_exit($uid, $mysqli);

if($exit !== FALSE){

    $data = array('status'=>'SUCCESS_LOGOUT');

}else{

    $data = array('status'=>'ACCT_NOT_FOUND');
}

Body:
you should use $mysqli->affected_rows since you are updating not num_rows

 if($mysqli->affected_rows !== 0){
        return true;
    }

change the function like below

public function user_exit($uid, $mysqli)
{
    if(empty($uid)){
        return false;
    }
    $q  = "UPDATE `users` SET last_logged_out=now() ";
    $q .= "WHERE uid='".$uid."' ";

    $sql = $mysqli->query($q);

    if($mysqli->affected_rows !== 0){
        return true;
    }
    return false;
}


问:
Selecting multiple divs with same class
I have a HTML structure how this:

```<code><div class="className"></div>
<div class="className"></div>
...
<div class="className"></div>
</code>```

I am trying to select these elements with jQuery. For that, I'd like to know if it's possible target these items within a loop, where N is the number of divs. In the first loop I want to target the first div, in the second loop the second div, etc...

```<code>for (var i = 0; i < N; i++) {
    $(".className")...
};
</code>```

Also, it's possible to know the number of divs with the same class with jQuery?

答:
use this code:</p>

```<code>var elems = $('.className');
N = elems.length; // this gives no. of divs
for (var i = 0; i < N; i++)
{
    $(elems[i])...  // by using this you can point to each div with same class name
}
</code>```

Title: Selecting multiple divs with same class

Body:
I have a HTML structure how this:

...

I am trying to select these elements with jQuery. For that, I'd like to know if it's possible target these items within a loop, where N is the number of divs. In the first loop I want to target the first div, in the second loop the second div, etc...

for (var i = 0; i < N; i++) {
    $(".className")...
};

Also, it's possible to know the number of divs with the same class with jQuery?

Body:
use this code:

var elems = $('.className');
N = elems.length; // this gives no. of divs
for (var i = 0; i < N; i++)
{
    $(elems[i])...  // by using this you can point to each div with same class name
}


问:
how pass data from activity to custom adapter
hi guys i need to pass arraylist from activity to custom adapter class but with my code it doesn't passed...i don't know why!

i use intent to pass data:

ACTIVITY:

```<code>private void azz() {
    int a=0;
    String status="";
    boolean statuss = false;
    String intenttt= path;

    System.out.println("INTENT:"+intenttt);

    file = new File(intenttt);
    System.out.println("FILE:"+file);

    FileInputStream is = null;
    try {
        is = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = null;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    Document doc = null;
    try {
        doc = dBuilder.parse(is);
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Element element = doc.getDocumentElement();
    element.normalize();

    NodeList nList = doc.getElementsByTagName("checkboxes_pizza");

    for (int i = 0; i < nList.getLength(); i++) {
        Node node = nList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element2 = (Element) node;
            //tv1.setText(tv1.getText()+"\nName : " + getValue("name", element2)+"\n");
            String id = getValue("id", element2);
            a = Integer.parseInt(id);
            status = getValue("status", element2);

            statuss= Boolean.parseBoolean(status);

            System.out.println("XML:" + a);

            hm.add(a);

            System.out.println("AZZ:" + hm);

        }

    }

    Intent intent = new Intent(ScrollableTabsActivity.this,PlanetAdapter.class) ;
    intent.putIntegerArrayListExtra("a", hm);
    startActivity(intent);

     // ok();

}
</code>```

CUSTOM ADAPTER TO GET INTENT:

```<code> Intent intent = getIntent();
        Arraylist<Integer> email=intent.getIntegerArrayListExtra("a");
</code>```

moreover getIntent() is written in red by IDE...

答:
To pass an array I would suggest to create a static array variable in your adapter like this:
Arraylist<Integer> variable

and then pass the value by using
adapterFileName.variable = hm (where hm is an arrayList as it looks you call it like that) in the activity just before you start activity.

Body:
hi guys i need to pass arraylist from activity to custom adapter class but with my code it doesn't passed...i don't know why!

i use intent to pass data:

ACTIVITY:

private void azz() {
    int a=0;
    String status="";
    boolean statuss = false;
    String intenttt= path;

    System.out.println("INTENT:"+intenttt);

    file = new File(intenttt);
    System.out.println("FILE:"+file);

    FileInputStream is = null;
    try {
        is = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = null;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    Document doc = null;
    try {
        doc = dBuilder.parse(is);
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Element element = doc.getDocumentElement();
    element.normalize();

    NodeList nList = doc.getElementsByTagName("checkboxes_pizza");

    for (int i = 0; i < nList.getLength(); i++) {
        Node node = nList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element2 = (Element) node;
            //tv1.setText(tv1.getText()+"\nName : " + getValue("name", element2)+"\n");
            String id = getValue("id", element2);
            a = Integer.parseInt(id);
            status = getValue("status", element2);

            statuss= Boolean.parseBoolean(status);

            System.out.println("XML:" + a);

            hm.add(a);

            System.out.println("AZZ:" + hm);

        }

    }

    Intent intent = new Intent(ScrollableTabsActivity.this,PlanetAdapter.class) ;
    intent.putIntegerArrayListExtra("a", hm);
    startActivity(intent);

     // ok();

}

CUSTOM ADAPTER TO GET INTENT:

 Intent intent = getIntent();
        Arraylist<Integer> email=intent.getIntegerArrayListExtra("a");

moreover getIntent() is written in red by IDE...


问:
Submit an ng-form if focus is not in the textarea

 <ng-form name="ctrl.scaleItemForm" ng-submit="ctrl.submit()">
      <input type="text"
      ng-model="ctrl.scaleItemPF.tareValue"
      name="tare-val-si">

      <textarea name="sectionLayouts"
      ng-trim="false"
      autocomplete="off"
      autocorrect="off"
      autocapitalize="off"
      spellcheck="false">
      </textarea>

      <button type="submit"
      class="button-save">
      Save
      </button>
 </ng-form>```

I am using Angular 1.5.8, In my view, I have a ng-form with ng-submit attached to it so as to trigger submit function on entering key press. I have a textarea inside the ng-form, default behavior when pressing an enter key inside a textarea is a newline, which is happening alongside the submit of the form and I don't want to submit the form if the focus is on texture, instead I need a new line. If replaced with form tag instead of ng-form its working as expected. Is this a bug associated with ng-form or am I doing something wrong

To wrap the question. Don't want to submit the form on entering key press if the focus is on textarea, otherwise, the form should be submitted.

答:
if (event && event.target.nodeName === 'TEXTAREA'
          && event.keyCode === 13) {
            return undefined;
}```

Fixed the issue by passing $event to the submit function and checking to see if current input is a textarea and enter key has triggered the submit function returned 'undefined' so as to continue with default behavior of textarea to move cursor to next line.

Body:
 <ng-form name="ctrl.scaleItemForm" ng-submit="ctrl.submit()">
      <input type="text"
      ng-model="ctrl.scaleItemPF.tareValue"
      name="tare-val-si">

      <textarea name="sectionLayouts"
      ng-trim="false"
      autocomplete="off"
      autocorrect="off"
      autocapitalize="off"
      spellcheck="false">
      </textarea>

      <button type="submit"
      class="button-save">
      Save
      </button>
 </ng-form>

I am using Angular 1.5.8, In my view, I have a ng-form with ng-submit attached to it so as to trigger submit function on entering key press. I have a textarea inside the ng-form, default behavior when pressing an enter key inside a textarea is a newline, which is happening alongside the submit of the form and I don't want to submit the form if the focus is on texture, instead I need a new line. If replaced with form tag instead of ng-form its working as expected. Is this a bug associated with ng-form or am I doing something wrong

To wrap the question. Don't want to submit the form on entering key press if the focus is on textarea, otherwise, the form should be submitted.

Body:
if (event && event.target.nodeName === 'TEXTAREA'
          && event.keyCode === 13) {
            return undefined;
}

Fixed the issue by passing $event to the submit function and checking to see if current input is a textarea and enter key has triggered the submit function returned 'undefined' so as to continue with default behavior of textarea to move cursor to next line.


问:
RxJava multiple loop with condition
I am learning RxJava for a few week, i have some java code like below

Code:

```<code>String[] strings1 = new String[]{"a", "b", "c", "d", "e"};
Integer[] integers = {1, 2, 3, 4, 5};
String[] strings2 = new String[]{"f", "g", "h", "i"};

for (String str : strings1) {
    for (Integer integer : integers) {
        System.out.println(str + ":" + integer);
        if(integer == 4){
            for (String str2 : strings2) {
                System.out.println(str2 + ":" + integer);
            }
        }
    }
}
</code>```

How can i translate it to RxJava code?

I trying to use flatMapIterable with flatMap but still can not reached it.

答:
There you go

```<code>@Test
public void thirdDeepLevel() {
    Observable.from(Arrays.asList("a", "b", "c", "d", "e"))
            .flatMap(letter -> Observable.from(Arrays.asList(1, 2, 3, 4, 5))
                    .map(number -> {
                        System.out.println(letter + ":" + number);
                        return number;
                    })
                    .filter(number -> number == 4)
                    .flatMap(number -> Observable.from(Arrays.asList("f", "g", "h", "i"))
                            .map(leter2 -> {
                                System.out.println(letter + ":" + number);
                                return leter2;
                            })))
            .subscribe();
}
</code>```

You can see more examples to lear Rx here https://github.com/politrons/reactive

Title: RxJava multiple loop with condition

Body:
I am learning RxJava for a few week, i have some java code like below

Code:

String[] strings1 = new String[]{"a", "b", "c", "d", "e"};
Integer[] integers = {1, 2, 3, 4, 5};
String[] strings2 = new String[]{"f", "g", "h", "i"};

for (String str : strings1) {
    for (Integer integer : integers) {
        System.out.println(str + ":" + integer);
        if(integer == 4){
            for (String str2 : strings2) {
                System.out.println(str2 + ":" + integer);
            }
        }
    }
}

How can i translate it to RxJava code?

I trying to use flatMapIterable with flatMap but still can not reached it.

Body:
There you go

@Test
public void thirdDeepLevel() {
    Observable.from(Arrays.asList("a", "b", "c", "d", "e"))
            .flatMap(letter -> Observable.from(Arrays.asList(1, 2, 3, 4, 5))
                    .map(number -> {
                        System.out.println(letter + ":" + number);
                        return number;
                    })
                    .filter(number -> number == 4)
                    .flatMap(number -> Observable.from(Arrays.asList("f", "g", "h", "i"))
                            .map(leter2 -> {
                                System.out.println(letter + ":" + number);
                                return leter2;
                            })))
            .subscribe();
}

You can see more examples to lear Rx here https://github.com/politrons/reactive


问:
How to categorize TestNG failures based on type of failure?
I'm trying to categorize TestNG failures based on the type of exception/error causing the error. Is there some way to do this? I'm relatively new to TestNG, so would appreciate any help possible</p>

答:
Yes you can do this by following the below overall approach.

Build a custom reporter implementation that implements the TestNG interface org.testng.IReporter

Within this interface implementatation wherein you will get access to ITestResult object which represents the results of a test method and then examine its exception via org.testng.ITestResult#getThrowable and then include your logic to classify failures.

Here's a draft implementation

```<code>public class SampleReporter implements IReporter {
    @Override
    public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
        for (ISuite suite : suites) {
            Map<String, ISuiteResult> suiteResults = suite.getResults();
            for (ISuiteResult sr : suiteResults.values()) {
                ITestContext tc = sr.getTestContext();
                Set<ITestResult> failedResults = tc.getFailedTests().getAllResults();
                for (ITestResult failedResult : failedResults) {
                    Throwable throwable = failedResult.getThrowable();
                    if (throwable instanceof WebDriverException) {
                        //classify this as a selenium exception
                    }
                }
            }
        }
    }
}
</code>```

You can now decide to wire in this listener using one of the below options

Using the @Listeners annotation on your test class.

Using the <listeners> tag in your suite xml file

Using the ServiceLoader approach

You can refer to this blog post of mine to learn more about TestNG listeners in general and all the above listed ways of listener injection.

Body:
Yes you can do this by following the below overall approach.

Build a custom reporter implementation that implements the TestNG interface org.testng.IReporter

Within this interface implementatation wherein you will get access to ITestResult object which represents the results of a test method and then examine its exception via org.testng.ITestResult#getThrowable and then include your logic to classify failures.

Here's a draft implementation

public class SampleReporter implements IReporter {
    @Override
    public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
        for (ISuite suite : suites) {
            Map<String, ISuiteResult> suiteResults = suite.getResults();
            for (ISuiteResult sr : suiteResults.values()) {
                ITestContext tc = sr.getTestContext();
                Set<ITestResult> failedResults = tc.getFailedTests().getAllResults();
                for (ITestResult failedResult : failedResults) {
                    Throwable throwable = failedResult.getThrowable();
                    if (throwable instanceof WebDriverException) {
                        //classify this as a selenium exception
                    }
                }
            }
        }
    }
}

You can now decide to wire in this listener using one of the below options

Using the @Listeners annotation on your test class.

Using the <listeners> tag in your suite xml file

Using the ServiceLoader approach

You can refer to this blog post of mine to learn more about TestNG listeners in general and all the above listed ways of listener injection.


问:
PySpark - How to do split on multiple dictionary values
After some processing on raw data I got my result as bellow , its like a Key with multiple values and the values are dictionary values - I want to make as Key + each dictionary values

```<code>[('HOMICIDE', {'2017': 1}),
('DECEPTIVE PRACTICE', {'2015': 2, '2017': 2, '2016': 8}),
('ROBBERY', {'2016': 2}),
('OTHER OFFENSE', {'2016': 3}),
('MOTOR VEHICLE THEFT', {'2017': 2, '2016': 2})]
</code>```

How can I make the above to

```<code>('HOMICIDE', '2017': 1),
('DECEPTIVE PRACTICE', '2015': 2 ),
('DECEPTIVE PRACTICE', '2017': 2,),
('DECEPTIVE PRACTICE', '2016': 8),
('ROBBERY', '2016': 2),
('OTHER OFFENSE', '2016': 3),
('MOTOR VEHICLE THEFT', '2017': 2)
('MOTOR VEHICLE THEFT', '2016': 2)]
</code>```

Whether I need to move the dictionary to a List and from there I need to process ?

答:
The bellow got worked -
rdd.flatMapValues(lambda data: data.items()).collect()

Thanks to @StackPointer and @user8119199

Body:
After some processing on raw data I got my result as bellow , its like a Key with multiple values and the values are dictionary values - I want to make as Key + each dictionary values

[('HOMICIDE', {'2017': 1}),
('DECEPTIVE PRACTICE', {'2015': 2, '2017': 2, '2016': 8}),
('ROBBERY', {'2016': 2}),
('OTHER OFFENSE', {'2016': 3}),
('MOTOR VEHICLE THEFT', {'2017': 2, '2016': 2})]

How can I make the above to

('HOMICIDE', '2017': 1),
('DECEPTIVE PRACTICE', '2015': 2 ),
('DECEPTIVE PRACTICE', '2017': 2,),
('DECEPTIVE PRACTICE', '2016': 8),
('ROBBERY', '2016': 2),
('OTHER OFFENSE', '2016': 3),
('MOTOR VEHICLE THEFT', '2017': 2)
('MOTOR VEHICLE THEFT', '2016': 2)]

Whether I need to move the dictionary to a List and from there I need to process ?


问:
Liferay7 : Delete title from FORM
Hello ,

I am working with Liferay 7 and I have no idea how to delete the Title and description from Liferay FORM application.

Thank you

答: Just leave them blank, the'y won't appear in UI. Or if you are asking about portlet title, go to look and feel and choose Application Decorators' asBarebone`.

Title: Liferay7 : Delete title from FORM


问:
how to display formatted String from console.log to an html div
Say I have a formatted string str written in my backend java code like this :

```<code>name    : xxx       company : qwe
address : yyy       age     : asd
country : zzz
</code>```

now I managed to display it on the browser console via

```<code>console.log(str);
</code>```

and when I checked it is also formatted just the way it is

```<code>name    : xxx       company : qwe
address : yyy       age     : asd
country : zzz
</code>```

but when I use Jquery to show it in a div in my html file, say for example

```<code>$('.divclass').text(str);
</code>```

it will just be one line

```<code>name    : xxx       company : qweaddress : yyy       age     : asdcountry : zzz
</code>```

this is all expected, but I was wondering if there is an implementation where I could possibly display the console.log to my html tag and still keep the format that I had before, instead of having to format it again, I guess my question is if there is a way to present console.log to the html in my case.

答:
Just replace \n with
 and put the string (wrapped into the ```</code> tag) in the div as inner html.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var str = "name    : xxx       company : qwe\n"+
"address : yyy       age     : asd\n"+
"country : zzz    \n";

console.log(str);

str = str.replace(/\n/g, "<br>");

$(".divclass").html("```"+str+"```");</code>```

```

Body:
Say I have a formatted string str written in my backend java code like this :

name    : xxx       company : qwe
address : yyy       age     : asd
country : zzz

now I managed to display it on the browser console via

console.log(str);

and when I checked it is also formatted just the way it is

name    : xxx       company : qwe
address : yyy       age     : asd
country : zzz

but when I use Jquery to show it in a div in my html file, say for example

$('.divclass').text(str);

it will just be one line

name    : xxx       company : qweaddress : yyy       age     : asdcountry : zzz

this is all expected, but I was wondering if there is an implementation where I could possibly display the console.log to my html tag and still keep the format that I had before, instead of having to format it again, I guess my question is if there is a way to present console.log to the html in my case.

Body:
Just replace \n with <br> and put the string (wrapped into the <pre> tag) in the div as inner html.

var str = "name    : xxx       company : qwe\n"+
"address : yyy       age     : asd\n"+
"country : zzz    \n";

console.log(str);

str = str.replace(/\n/g, "<br>");

$(".divclass").html("<pre>"+str+"</pre>");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divclass">
</div>


问:
Calculate date persons becomes a certain age
I'm trying to calculate the date a person turns 18, taking into account leap years.

One might think that just adding 18 years to a date is enough:

```<code>birthDay.AddYears(18);
</code>```

But if the birthday is February 29, 2000, this leads to february 28, 2018. I believe the correct answer would have to be March 1, 2018.

I found a way to do it, but I wonder if there isn't a simpler way.

```<code>birthday.AddDays(-1).AddYears(18).AddDays(1);
</code>```

I would think an answer to this question would already exist on StackOverflow, but all my searches only turn up questions about calculating age on a specific date.

I don't think my question is a duplicate of Behavior of DateTime.AddYears on leap year as that one only explains why AddYears works as it does. It does not contain code to perform the calculation.

I found a quora article stating that the official date you turn 18 is different in New Sealand from the UK.

答:
I suggest hiding the logic (rounding up to 1 Mar instead of rounding down to 28 Feb) into an extension method:

```<code>public static partial class DateTimeExtensions {
  public static DateTime AddYearsUp(this DateTime value, int amount) {
    // Business as usual: neither days are leap days or both days are leap days
    if (value.Month != 2 || value.Day != 29 || DateTime.IsLeapYear(value.Year + amount))
      return value.AddYears(amount);

    // We want 29 Feb to be turned into 1 Mar (not 28 Feb)
    return new DateTime(value.Year + amount, 3, 1,
                        value.Hour, value.Minute, value.Second, value.Millisecond);
  }
}
</code>```

Then use the method implemented:

```<code>var result = birthDay.AddYearsUp(18);
</code>```

Please, notice, that you current logic

```<code>birthday.AddDays(-1).AddYears(18).AddDays(1);
</code>```

is not correct; the counter example is

```<code>// 1 Mar 1998
var birthday = new DateTime(1998, 3, 1);

// Expected:  1 Mar 2016
// Actual:   29 Feb 2016
var result = birthday.AddDays(-1).AddYears(18).AddDays(1);
</code>```

Body:
I'm trying to calculate the date a person turns 18, taking into account leap years.

One might think that just adding 18 years to a date is enough:

birthDay.AddYears(18);

But if the birthday is February 29, 2000, this leads to february 28, 2018. I believe the correct answer would have to be March 1, 2018.

I found a way to do it, but I wonder if there isn't a simpler way.

birthday.AddDays(-1).AddYears(18).AddDays(1);

I would think an answer to this question would already exist on StackOverflow, but all my searches only turn up questions about calculating age on a specific date.

I don't think my question is a duplicate of Behavior of DateTime.AddYears on leap year as that one only explains why AddYears works as it does. It does not contain code to perform the calculation.

I found a quora article stating that the official date you turn 18 is different in New Sealand from the UK.

Body:
I suggest hiding the logic (rounding up to 1 Mar instead of rounding down to 28 Feb) into an extension method:

public static partial class DateTimeExtensions {
  public static DateTime AddYearsUp(this DateTime value, int amount) {
    // Business as usual: neither days are leap days or both days are leap days
    if (value.Month != 2 || value.Day != 29 || DateTime.IsLeapYear(value.Year + amount))
      return value.AddYears(amount);

    // We want 29 Feb to be turned into 1 Mar (not 28 Feb)
    return new DateTime(value.Year + amount, 3, 1,
                        value.Hour, value.Minute, value.Second, value.Millisecond);
  }
}

Then use the method implemented:

var result = birthDay.AddYearsUp(18);

Please, notice, that you current logic

birthday.AddDays(-1).AddYears(18).AddDays(1);

is not correct; the counter example is

// 1 Mar 1998
var birthday = new DateTime(1998, 3, 1);

// Expected:  1 Mar 2016
// Actual:   29 Feb 2016
var result = birthday.AddDays(-1).AddYears(18).AddDays(1);


问:
Breeze does not work with predictate in aspnetcore project
I am building an ASP.NET Core project, which uses breezejs and typescript. The mysterious thing is that when I load data without a predicate, all the things work fine, but when a predicate is added to filter the data, there is an error:'500 Internal Server Error' . I tried to debug in the controller, when browser make the request, it can get to the controller.

But, in the js side, the request has no return, which means the js code cannot go through the breakpoint.

```<code>executeQuery(query) {
    return this.manager
        .executeQuery(query.using(breeze.FetchStrategy.FromServer || this.fetchStrategy))
        .then(function (data) {
            return data.results;//my breakpoint
        });
}
</code>```

The contorller:

```<code>using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Jumpstart.Web.Data;
using Microsoft.AspNetCore.Authorization;
using Jumpstart.Model;
using Breeze.AspNetCore;
using Newtonsoft.Json.Linq;
using Breeze.Persistence;

namespace Jumpstart.Web.Controllers
{
[Produces("application/json")]
[Route("breeze/[controller]/[action]")]
[BreezeQueryFilter]
public class JumpstartController : Controller
{
    private readonly IUnitOfWork _uitOfWork;

    public JumpstartController(IUnitOfWork uitOfWork)
    {
        _uitOfWork = uitOfWork;
    }

    /// <summary>
    /// Get public tenants
    /// </summary>
    /// <returns>IQueryable tenants</returns>
    [HttpGet]
    [AllowAnonymous]
    public IQueryable<Tenant> Tenants()
    {
        return _uitOfWork.TenantRepository.All();

    }
</code>```

The request :

```<code>Request URL:http://localhost:50481/breeze/Jumpstart/tenants?$filter=Id%20eq%20guid%2709ae9363-240a-46d7-b5a6-30529e7dee63%27&
Request Method:GET
Status Code:500 Internal Server Error
</code>```

答:
Found the reason. The breeze.core(server end) only permit json format predicate, but the default in breeze front end is not.

the solution is :

```<code>  breeze.config.initializeAdapterInstance("uriBuilder", "json");
</code>```

Body:
I am building an ASP.NET Core project, which uses breezejs and typescript. The mysterious thing is that when I load data without a predicate, all the things work fine, but when a predicate is added to filter the data, there is an error:'500 Internal Server Error' . I tried to debug in the controller, when browser make the request, it can get to the controller.

But, in the js side, the request has no return, which means the js code cannot go through the breakpoint.

executeQuery(query) {
    return this.manager
        .executeQuery(query.using(breeze.FetchStrategy.FromServer || this.fetchStrategy))
        .then(function (data) {
            return data.results;//my breakpoint
        });
}

The contorller:

using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Jumpstart.Web.Data;
using Microsoft.AspNetCore.Authorization;
using Jumpstart.Model;
using Breeze.AspNetCore;
using Newtonsoft.Json.Linq;
using Breeze.Persistence;

namespace Jumpstart.Web.Controllers
{
[Produces("application/json")]
[Route("breeze/[controller]/[action]")]
[BreezeQueryFilter]
public class JumpstartController : Controller
{
    private readonly IUnitOfWork _uitOfWork;

    public JumpstartController(IUnitOfWork uitOfWork)
    {
        _uitOfWork = uitOfWork;
    }

    ///
    /// Get public tenants
    ///
    /// <returns>IQueryable tenants</returns>
    [HttpGet]
    [AllowAnonymous]
    public IQueryable<Tenant> Tenants()
    {
        return _uitOfWork.TenantRepository.All();

    }

The request :

Request URL:http://localhost:50481/breeze/Jumpstart/tenants?$filter=Id%20eq%20guid%2709ae9363-240a-46d7-b5a6-30529e7dee63%27&
Request Method:GET
Status Code:500 Internal Server Error

Body:
Found the reason. The breeze.core(server end) only permit json format predicate, but the default in breeze front end is not.

the solution is :

  breeze.config.initializeAdapterInstance("uriBuilder", "json");


问:
iOS:Objective-C:Output issue due to ipad time display 12Hour / 24Hour
In my application i am using one function to change date format to replace / with - and date format also.

When Device is set to 12 Hour, everything works fine. But when i set it to 24Hour it returns wrong value.

```<code>NSDate *newdate = [self convertDateSlashToDash:[obj valueForKey:@"TaskStartDateTime"]]);

//input date is  : 6/6/2017 6:38:00 PM
-(NSDate *)convertDateSlashToDash:(NSString *)dateStr{

if ([dateStr isKindOfClass:[NSDate class]]) {
    return (NSDate*)dateStr;
}

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//Set the AM and PM symbols
[dateFormatter setAMSymbol:@"AM"];
[dateFormatter setPMSymbol:@"PM"];
//Specify only 1 M for month, 1 d for day and 1 h for hour
[dateFormatter setDateFormat:@"M/d/yyyy h:mm:ss a"];

// in ms 1469077819000 without ms 1469077819 for 7/21/2016 5:10:19 AM
NSTimeInterval ti = [[dateFormatter dateFromString:dateStr] timeIntervalSince1970];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:ti];
NSDateFormatter *formatter= [[NSDateFormatter alloc] init];

// [formatter setLocale:[NSLocale currentLocale]];

[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss aa"];
NSString *dateString = [formatter stringFromDate:date];
NSDate *parsedDate = [formatter dateFromString:dateString];

return dateString;
}
 //output of this is (24hrs): 1970-01-01 05:30:00AM

 //output of this is (12hrs): 2017-06-06 06:38:00 PM
</code>```

Why it is not working?
Please suggest.

Thank you.

答: The 12-hour and 24-hour are specified differently with a date formatter. Make sure that you are using the right format. I see you are using h for hour along with a at the end which configures the formatter to a 12-hour format. For a 24-hour format, you need H or HH depending on your needs. You can refer to this link to get a better understanding of different formats

Body:
In my application i am using one function to change date format to replace / with - and date format also.

When Device is set to 12 Hour, everything works fine. But when i set it to 24Hour it returns wrong value.

NSDate *newdate = [self convertDateSlashToDash:[obj valueForKey:@"TaskStartDateTime"]]);

//input date is  : 6/6/2017 6:38:00 PM
-(NSDate *)convertDateSlashToDash:(NSString *)dateStr{

if ([dateStr isKindOfClass:[NSDate class]]) {
    return (NSDate*)dateStr;
}

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//Set the AM and PM symbols
[dateFormatter setAMSymbol:@"AM"];
[dateFormatter setPMSymbol:@"PM"];
//Specify only 1 M for month, 1 d for day and 1 h for hour
[dateFormatter setDateFormat:@"M/d/yyyy h:mm:ss a"];

// in ms 1469077819000 without ms 1469077819 for 7/21/2016 5:10:19 AM
NSTimeInterval ti = [[dateFormatter dateFromString:dateStr] timeIntervalSince1970];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:ti];
NSDateFormatter *formatter= [[NSDateFormatter alloc] init];

// [formatter setLocale:[NSLocale currentLocale]];

[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss aa"];
NSString *dateString = [formatter stringFromDate:date];
NSDate *parsedDate = [formatter dateFromString:dateString];

return dateString;
}
 //output of this is (24hrs): 1970-01-01 05:30:00AM

 //output of this is (12hrs): 2017-06-06 06:38:00 PM

Why it is not working?
Please suggest.

Thank you.


问:
libxml-ruby failed to load at x86_64
We are having problem with libxml-ruby gem at the server side
Possible because it uses x86_64 architecture:

$ uname -a
Linux ip-10-228-171-64 2.6.21.7-2.fc8xen-ec2-v1.0 #1 SMP Tue Sep 1 10:25:30 EDT 2009 x86_64 GNU/Linux

```<code>require 'libxml'
LoadError: /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/libxml-ruby-1.1.4/lib/libxml_ruby.so: invalid ELF header - /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/libxml-ruby-1.1.4/lib/libxml_ruby.so
from /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/libxml-ruby-1.1.4/lib/libxml_ruby.so
from /usr/local/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
from /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in'
from /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
from /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/libxml-ruby-1.1.4/lib/libxml.rb:9
from /usr/local/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /usr/local/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
from /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in'
from /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
from (irb):1
</code>```

gem version 1.1.4

Reinstalling the gem doesn't help
Can somebody suggest what to do?

答:
For some reason on Linux, sometimes gem gets confused and installs the Windows DLL for libxml-ruby.  You can verify this by doing a file on (ruby lib path)/ruby/gems/1.8/gems/libxml-ruby-1.1.4/lib/libxml_ruby.so and it says that libxml_ruby.so is a Windows PE DLL.

The way I've found to work around this is to force the platform, i.e:

gem install libxml-ruby --platform ruby

Title: libxml-ruby failed to load at x86_64

Body:
We are having problem with libxml-ruby gem at the server side
Possible because it uses x86_64 architecture:

$ uname -a
Linux ip-10-228-171-64 2.6.21.7-2.fc8xen-ec2-v1.0 #1 SMP Tue Sep 1 10:25:30 EDT 2009 x86_64 GNU/Linux

require 'libxml'
LoadError: /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/libxml-ruby-1.1.4/lib/libxml_ruby.so: invalid ELF header - /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/libxml-ruby-1.1.4/lib/libxml_ruby.so
from /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/libxml-ruby-1.1.4/lib/libxml_ruby.so
from /usr/local/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
from /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in'
from /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
from /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/libxml-ruby-1.1.4/lib/libxml.rb:9
from /usr/local/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /usr/local/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
from /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in'
from /usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
from (irb):1

gem version 1.1.4

Reinstalling the gem doesn't help
Can somebody suggest what to do?


问:
Android M - check runtime permission - how to determine if the user checked "Never ask again"?
According to this: http://developer.android.com/preview/features/runtime-permissions.html#coding an app can check for runtime permissions and request permissions if it hasn't been granted already. The following dialog will be displayed then:

In case the user declines an important permission, imo an app should display an explanation why the permission is needed and what impact declining has. That dialog has two options:

re-try again (permission is requested again)

deny (app will work without that permission).

If the user checks Never ask again however, the second dialog with the explanation shouldn't be shown, especially if the user already declined once before.
Now the question is: how does my app know whether the user has checked the Never ask again? IMO the onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) doesn't give me that information.

A second question would be: does Google have plans to incorporate a custom message in the permission dialog that would explain why the app needs the permission? That way there would never be a second dialog which would certainly make for a better ux.

答:
The method shouldShowRequestPermissionRationale() can be used to check whether the user selected the 'never asked again' option and denied the permission.
There's plenty of code examples, so I would rather explain how to use it for such a purpose, because I think its name and its implementation makes this more complicated that it actually is.

As explained in Requesting Permissions at Run Time, that method  returns true if the option 'never ask again' is visible, false otherwise; so it returns false the very first time a dialog is shown, then from the second time on it returns true, and only if the user deny the permission selecting the option, at that point it returns false again.

To detect such a case, either you can detect the sequence false-true-false, or (more simple) you can have a flag which keeps track of the initial time the dialog is shown. After that, that method returns either true or false, where the false will allow you to detect when the option is selected.

ContentLicense: CC BY-SA 4.0


问:
How to mock a SOAP Service class in C#
I want to fake the getCustomerName Service call here and mock it with fake Data

My class is "CustomerName" which calls a SOAPService call which returns the CustomerName for an CustomerNumber.I want to fake the SOAPService call to return some fakedata.

CustomerName class:

```<code>using (WebService.WebServiceClient CustomerData = new WebService.WebServiceClient ())
{
      WebServiceClient.TestResponse resp = CustomerData.getCustomerName(customerNumber);
      resp.CustomerName;
}
</code>```

I tried doing these

```<code>var FakeWebService = A.Fake<WebServiceClient>();
var FakeCustomerName=A.Fake<CustomerName>();
</code>```

Then I faked the Calls here and Fake response is some value

```<code>    A.CallTo(WebServiceClient.CustomerNumber).WithNonVoidReturnType().Returns(FakeResponse);
fakeCustomerName = FakeCustomerData.GetCustomerName(CustomerNumber);
</code>```

The problem I face is it's getting the data from the actual endpoint instead of fakedata?

I am not clear on how to do it..

答:
Instead of refering to the webservice directly and hence try to mock the webservice itself, create an interface instead which holds the functionality the webservice provides.

```<code>public interface ICustomerData
{
    CustomerName GetCustomerName(CustomerNumber number);
}
</code>```

Then, make two implementations. One which calls the actual webservice, and one which you can use for testing:

```<code>public class CustomerData : ICustomerData
{
    CustomerName GetCustomerName(CustomerNumber number)
    {
        return CustomerData.GetCustomerName(number);
    }

    public CustomerData()
    {
        CustomerData = new WebService.WebServiceClient ();
    }
    private WebService.WebServiceClient CustomerData;
}

public class DelegatedCustomerData : ICustomerData
{
    public Func<CustomerNumber,CustomerName> GetCustomerName {get;set;}

    CustomerName ICustomerData.GetCustomerName(CustomerNumber number) => GetCustomerName(number);

}
</code>```

The latter delegated class is just an example on how to mock the class, but which i personally prefer.

Title: How to mock a SOAP Service class in C#

Body:
I want to fake the getCustomerName Service call here and mock it with fake Data

My class is "CustomerName" which calls a SOAPService call which returns the CustomerName for an CustomerNumber.I want to fake the SOAPService call to return some fakedata.

CustomerName class:

using (WebService.WebServiceClient CustomerData = new WebService.WebServiceClient ())
{
      WebServiceClient.TestResponse resp = CustomerData.getCustomerName(customerNumber);
      resp.CustomerName;
}

I tried doing these

var FakeWebService = A.Fake<WebServiceClient>();
var FakeCustomerName=A.Fake<CustomerName>();

Then I faked the Calls here and Fake response is some value

    A.CallTo(WebServiceClient.CustomerNumber).WithNonVoidReturnType().Returns(FakeResponse);
fakeCustomerName = FakeCustomerData.GetCustomerName(CustomerNumber);

The problem I face is it's getting the data from the actual endpoint instead of fakedata?

I am not clear on how to do it..

Body:
Instead of refering to the webservice directly and hence try to mock the webservice itself, create an interface instead which holds the functionality the webservice provides.

public interface ICustomerData
{
    CustomerName GetCustomerName(CustomerNumber number);
}

Then, make two implementations. One which calls the actual webservice, and one which you can use for testing:

public class CustomerData : ICustomerData
{
    CustomerName GetCustomerName(CustomerNumber number)
    {
        return CustomerData.GetCustomerName(number);
    }

    public CustomerData()
    {
        CustomerData = new WebService.WebServiceClient ();
    }
    private WebService.WebServiceClient CustomerData;
}

public class DelegatedCustomerData : ICustomerData
{
    public Func<CustomerNumber,CustomerName> GetCustomerName {get;set;}

    CustomerName ICustomerData.GetCustomerName(CustomerNumber number) => GetCustomerName(number);

}

The latter delegated class is just an example on how to mock the class, but which i personally prefer.


问:
How to return middle element of list?
How to define function which returns the middle element of list, assuming an odd number of elements?

(all-but-last list) returns all but the last element of list;
(middle list) returns the middle element of list

to make use of "cdr" and "all-but-last" for the definition of “middle.”

答:
This is a probably a homework question which expects you to solve the problem recursively.
You should try to distinguish the base cases of the recursion to build up the general definition of middle. Also, we stick to the problem and assume there is always an odd number of elements in the input list.

So first, what is the middle of a list with a single element ?

Then, given that you have to use cdr and all-but-last as basic constructs, try to define the problems using those constructs for the general case. How can you reduce the problem into recursive sub-problems using those constructs? How do you combine the recursive results to make a result?

For example, try with the next odd-sized list, a list of 3 elements and try to see how you could find the middle element using your basic construct and a recursive call.

 Consider a list with elements a, e0, e1, ..., en, z. Then the middle of  this list is the same as the middle of the list e0, e1, ..., en, namely the list with the first and last elements removed.

You could start with something like this, and fill the blanks:

```<code>(defun middle (list)
  (if (endp (cdr list))
      ...
      (middle ...)))
</code>```

Title: How to return middle element of list?

Body:
This is a probably a homework question which expects you to solve the problem recursively.
You should try to distinguish the base cases of the recursion to build up the general definition of middle. Also, we stick to the problem and assume there is always an odd number of elements in the input list.

So first, what is the middle of a list with a single element ?

Then, given that you have to use cdr and all-but-last as basic constructs, try to define the problems using those constructs for the general case. How can you reduce the problem into recursive sub-problems using those constructs? How do you combine the recursive results to make a result?

For example, try with the next odd-sized list, a list of 3 elements and try to see how you could find the middle element using your basic construct and a recursive call.

 Consider a list with elements a, e0, e1, ..., en, z. Then the middle of  this list is the same as the middle of the list e0, e1, ..., en, namely the list with the first and last elements removed.

You could start with something like this, and fill the blanks:

(defun middle (list)
  (if (endp (cdr list))
      ...
      (middle ...)))


问:
Rename Play-store App
I am facing issue with app published in google play-store. I like to rename the app through google play console. but couldn't able to do it.

Is anyone know about it ?

答:
Try the following steps -

open Google play-console.

Select your app from the list of apps.

Expand Store Presence > Now click on store Listing.

Now rename Title.

Finally click on Submit Update.

Title: Rename Play-store App


问:
Why my scrapy ouput result is array
Scrapy seems will format my output from dict to array while all i need was just string object.The output:

{"title": ["some title some title"], "url": ["https://www.example.com/"], "upDate": ["2017/06/07 10:23:00"]}
```

<p>
and the code:</p>

<pre class="lang-html prettyprint-override"><code>    l = ItemLoader(item=RoomInfoItem(), response=response)
    updateStr = '2017-' + res.css('td[class="time"]::text').extract_first()
    l.add_value('upDate', upDateStr)
    ownerurl = response.css('span[class="from"] a::attr(href)').extract_first()
    l.add_value('ownerUrl', ownerurl)
    title = response.css('div[id="content"] h1::text').extract_first()
    l.add_value('title', title)
    yield l.load_item()
</code>```

the scrapy resource it seems like when add new value to item, scrapy will turn the argument to  an iterable by scrapy.utils.misc.arg_to_iter().
If there any other method can add values to the items while not change the value data struct?
The output i want may look like this:

{"title": "some title some title", "url": "https://www.example.com/", "upDate": "2017/06/07 10:23:00"}
```

答:
well, i solve this problem by give up use the ItemLoader object. I use the item directly which will not change my data struct automatic.
The code :

item=RoomInfoItem()
item['url'] = resUrl
item['upDate'] = upDateStr
item['title'] = title
yield item
```

Title: Why my scrapy ouput result is array

Body:
Scrapy seems will format my output from dict to array while all i need was just string object.The output:

{"title": ["some title some title"], "url": ["https://www.example.com/"], "upDate": ["2017/06/07 10:23:00"]}

and the code:

    l = ItemLoader(item=RoomInfoItem(), response=response)
    updateStr = '2017-' + res.css('td[class="time"]::text').extract_first()
    l.add_value('upDate', upDateStr)
    ownerurl = response.css('span[class="from"] a::attr(href)').extract_first()
    l.add_value('ownerUrl', ownerurl)
    title = response.css('div[id="content"] h1::text').extract_first()
    l.add_value('title', title)
    yield l.load_item()

the scrapy resource it seems like when add new value to item, scrapy will turn the argument to  an iterable by scrapy.utils.misc.arg_to_iter().
If there any other method can add values to the items while not change the value data struct?
The output i want may look like this:

{"title": "some title some title", "url": "https://www.example.com/", "upDate": "2017/06/07 10:23:00"}


问:
Error sending to the following VALID addresses Jenkins
I will receive emails when I trigger using build now manually, but I don't receive emails when I tried to using it in batch mode. Below is the log I obtain when triggered in batch mode.

```<code>Email was triggered for: Always
Sending email for trigger: Always
Sending email to: abc@example.com
Error sending to the following VALID addresses: abc@example.com
</code>```

Note: There are no build logs attached while sending email.

答: If every thing fails, try restarting jenkins process. That solved for me. Somehow the Jenkins system was unable to load all of the configs? But give it a try.</p>

Body:
I will receive emails when I trigger using build now manually, but I don't receive emails when I tried to using it in batch mode. Below is the log I obtain when triggered in batch mode.

Email was triggered for: Always
Sending email for trigger: Always
Sending email to: abc@example.com
Error sending to the following VALID addresses: abc@example.com

Note: There are no build logs attached while sending email.


问:
Merging two multi-dimensional arrays using key and adding values
I want to merge two array's using key(product_id) and adding that values(usage).
Array 1

```
Array
(
    [0] => Array
        (
            [name] => Reschedule A Service
            [usage] => 1
            [product_id] => 8
        )

    [1] => Array
        (
            [name] => Adding An Image
            [usage] => 1
            [product_id] => 5
        )

    [2] => Array
        (
            [name] => Each Calendar Event
            [usage] => 1
            [product_id] => 14
        )

)
```

Array 2

```
Array
(
    [0] => Array
        (
            [name] => Adding An Image
            [usage] => 1
            [product_id] => 5
        )

    [1] => Array
        (
            [name] => Schedule A Service
            [usage] => 3
            [product_id] => 11
        )

    [2] => Array
        (
            [name] => Each Calendar Event
            [usage] => 2
            [product_id] => 14
        )

    [3] => Array
        (
            [name] => Sales Performance Dashboard
            [usage] => 2
            [product_id] => 30
        )

    [4] => Array
        (
            [name] => Quote
            [usage] => 1
            [product_id] => 32
        )

)
```

I need an out put like this merging and adding usage values.

```
Array
(
    [0] => Array
        (
            [name] => Adding An Image
            [usage] => 2
            [product_id] => 5
        )

    [1] => Array
        (
            [name] => Schedule A Service
            [usage] => 3
            [product_id] => 11
        )

    [2] => Array
        (
            [name] => Each Calendar Event
            [usage] => 3
            [product_id] => 14
        )

    [3] => Array
        (
            [name] => Sales Performance Dashboard
            [usage] => 2
            [product_id] => 30
        )

    [4] => Array
        (
            [name] => Quote
            [usage] => 1
            [product_id] => 32
        )

    [5] => Array
        (
            [name] => Reschedule A Service
            [usage] => 1
            [product_id] => 8
        )

)
```

This is my code for creating arrays

```

    foreach($query->rows as $product){

     $top_products[]=array(
        'name'=>$product['name'],
        'usage'=>$product['pusage'],
        'product_id'=>$product['product_id']
     );

    }

```

```

    foreach($query_2->rows as $product){

         $top_point_products[]=array(
           'name'=>$product['name'],
           'usage'=>$product['p_usage'],
           'product_id'=>$product['product_id']
         );

    }

```

答:
Use the array_merge function, like this:

```<code>$C = array_merge($A, $B);
print_r($C);
</code>```

Read manual Array merge

Body:
I want to merge two array's using key(product_id) and adding that values(usage).
Array 1

Array
(
    [0] => Array
        (
            [name] => Reschedule A Service
            [usage] => 1
            [product_id] => 8
        )

    [1] => Array
        (
            [name] => Adding An Image
            [usage] => 1
            [product_id] => 5
        )

    [2] => Array
        (
            [name] => Each Calendar Event
            [usage] => 1
            [product_id] => 14
        )

)

Array 2

Array
(
    [0] => Array
        (
            [name] => Adding An Image
            [usage] => 1
            [product_id] => 5
        )

    [1] => Array
        (
            [name] => Schedule A Service
            [usage] => 3
            [product_id] => 11
        )

    [2] => Array
        (
            [name] => Each Calendar Event
            [usage] => 2
            [product_id] => 14
        )

    [3] => Array
        (
            [name] => Sales Performance Dashboard
            [usage] => 2
            [product_id] => 30
        )

    [4] => Array
        (
            [name] => Quote
            [usage] => 1
            [product_id] => 32
        )

)

I need an out put like this merging and adding usage values.

Array
(
    [0] => Array
        (
            [name] => Adding An Image
            [usage] => 2
            [product_id] => 5
        )

    [1] => Array
        (
            [name] => Schedule A Service
            [usage] => 3
            [product_id] => 11
        )

    [2] => Array
        (
            [name] => Each Calendar Event
            [usage] => 3
            [product_id] => 14
        )

    [3] => Array
        (
            [name] => Sales Performance Dashboard
            [usage] => 2
            [product_id] => 30
        )

    [4] => Array
        (
            [name] => Quote
            [usage] => 1
            [product_id] => 32
        )

    [5] => Array
        (
            [name] => Reschedule A Service
            [usage] => 1
            [product_id] => 8
        )

)

This is my code for creating arrays

    foreach($query->rows as $product){

     $top_products[]=array(
        'name'=>$product['name'],
        'usage'=>$product['pusage'],
        'product_id'=>$product['product_id']
     );

    }

    foreach($query_2->rows as $product){

         $top_point_products[]=array(
           'name'=>$product['name'],
           'usage'=>$product['p_usage'],
           'product_id'=>$product['product_id']
         );

    }

Body:
Use the array_merge function, like this:

$C = array_merge($A, $B);
print_r($C);

Read manual Array merge