问:
How to navigate to another stack's screen while using deep linking in react-navigation v5?
In this case, a screen may be opened through deep linking. There's a <BackButton /> component and I wish the button's behavior like this:

if this screen was opened by navigator.navigate, then go back.

if this screen was opened by deep-linking, then go to the Home screen.

The navigator struct like this

Root (stack navigator)

Tab (bottom tab navigator)

Home

Personal

Main (stack navigator)

Store

In the begining, I wrote code like this:

const onBackButtonPress = useCallback(() => {
  if (navigation.canGoBack()) {
    navigation.goBack()
  } else {
    navigation.navigate('Tab', { screen: 'Home' })
  }
), [navigation])
```

<p>This code works, however using <code>navigation.navigate()</code> function cause a push effect (new screen comes from the right edge), not go back (new screen comes from the left edge).</p>

<p>Then I tried to use <code>navigation.replace()</code> and <code>navigation.reset()</code></p>

<pre class="lang-js prettyprint-override"><code>navigation.reset({
  index: 0,
  routes: [{ name: 'Tab', state: { routes: [{ name: 'Home' }, { name: 'Personal' }] } }],
})
</code>```

And the navigator seems couldn't handle this route (I think this is because we're in the Main stack now, and it couldn't handle the params).

What can I do to correct the behavior of navigation?

答:
And the navigator seems couldn't handle this route (I think this is because we're in the Main stack now, and it couldn't handle the params).

Maybe unlike navigate, in this case, navigation cannot handle this route when using replace and reset, so I try to use its parent navigator and it is just exactly the behavior I've wanted!

const onBackButtonPress = useCallback(() => {
  if (navigation.canGoBack()) {
    navigation.goBack()
  } else {
    const parentNaigator = navigation.dangerouslyGetParent()
    parentNaigator?.replace('Tab', { screen: 'Home' })
  }
), [navigation])

```

According to official document, navigation actions are intended to handled by current navigator and bubble up if couldn't be handled. Maybe it is a bug of replace and reset.

Body:
In this case, a screen may be opened through deep linking. There's a <BackButton /> component and I wish the button's behavior like this:

if this screen was opened by navigator.navigate, then go back.

if this screen was opened by deep-linking, then go to the Home screen.

The navigator struct like this

Root (stack navigator)

Tab (bottom tab navigator)

Home

Personal

Main (stack navigator)

Store

In the begining, I wrote code like this:

const onBackButtonPress = useCallback(() => {
  if (navigation.canGoBack()) {
    navigation.goBack()
  } else {
    navigation.navigate('Tab', { screen: 'Home' })
  }
), [navigation])

This code works, however using navigation.navigate() function cause a push effect (new screen comes from the right edge), not go back (new screen comes from the left edge).

Then I tried to use navigation.replace() and navigation.reset()

navigation.reset({
  index: 0,
  routes: [{ name: 'Tab', state: { routes: [{ name: 'Home' }, { name: 'Personal' }] } }],
})

And the navigator seems couldn't handle this route (I think this is because we're in the Main stack now, and it couldn't handle the params).

What can I do to correct the behavior of navigation?

Body:
And the navigator seems couldn't handle this route (I think this is because we're in the Main stack now, and it couldn't handle the params).

Maybe unlike navigate, in this case, navigation cannot handle this route when using replace and reset, so I try to use its parent navigator and it is just exactly the behavior I've wanted!

const onBackButtonPress = useCallback(() => {
  if (navigation.canGoBack()) {
    navigation.goBack()
  } else {
    const parentNaigator = navigation.dangerouslyGetParent()
    parentNaigator?.replace('Tab', { screen: 'Home' })
  }
), [navigation])

According to official document, navigation actions are intended to handled by current navigator and bubble up if couldn't be handled. Maybe it is a bug of replace and reset.


来源: stackexchange

问:
Does async pipe unsubscribes from an observable defined in a service and pointed to from a component variable?
I have a BehaviourSubject defined in a service, and i point to that subject with a variable i define in another component, in that component's view i subscribe to the subject using that variable, example:

service:

```<code>public exampleSubjebt$ = new BehaviorSubject<boolean>(true);
</code>```

component.ts:

```<code>ngOninit() {
let someVariable = this.service.exampleSubject$;
}
</code>```

component's view:

```<code><app-something [options]="someVariable | async"></app-something>
</code>```

My question is, does the fact the the observable sits in the service and I call it directly from there using the variable, make it so that the async pipe will not unsubscribe on the component's destruction?

答: The subscription lies into the component, not into the service so the async pipe will unsubscribe correctly when the component get destroyed.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a BehaviourSubject defined in a service, and i point to that subject with a variable i define in another component, in that component's view i subscribe to the subject using that variable, example:

service:

public exampleSubjebt$ = new BehaviorSubject<boolean>(true);

component.ts:

ngOninit() {
let someVariable = this.service.exampleSubject$;
}

component's view:

<app-something [options]="someVariable | async"></app-something>

My question is, does the fact the the observable sits in the service and I call it directly from there using the variable, make it so that the async pipe will not unsubscribe on the component's destruction?


问:
Text Highlights as CSS masks?
I'm wondering if it's possible to reproduce this text effect:

It should appear as if the text highlights were reducing the opacity of the images. I guess what you need is a copy of the background layer getting masked in the shapes/positions of the text highlights. But is there a way to really make these masks automatically resize/reposition according to the lines of text? Or any other way to achieve the effect?

This might better explain what I'm after:

答:
You might be looking for the css property background-attachment: fixed. This does have the caveat that the background will no longer scroll with the page and remain static, but this way you can guarantee the overlap between the element background and the container background remain the same. There is a fix for the scrolling issue via javascript, for a minor overhead cost, depending on how heavy the graphics are for the browser to render/reposition.

Then you simply apply the same background to the background containing element(.wrap in my case) and the text containing element(wrap in my case) and you get your desired effect as shown in your second image.

Then put the mark in a paragraph element and repeat the text twice. Once in the paragraph, once within the mark.

Then set the paragraph to position relative, and the mark to absolute, so they overlap each other perfectly. This is to counteract the wrap being transparent and not showing the text properly, as the text also becoming transparent.

.wrap, .wrap mark {
   background-image: url('https://i.imgur.com/hAodNjT.jpg');
   background-attachment: fixed;
}
.wrap p {
  position: relative;
}
.wrap mark {
   position: absolute;
   top: 0px;
   left: 0px;
   opacity: 0.4;
}
img {
   width: 300px;
   height: auto;
}
.wrap {
   padding-top:160px;
   position: relative;
   width: 400px;
   height: 400px;
}
.wrap img {
   position:absolute;
   top:60px;

   z-index:0;
}
.wrap p {
    position:relative;
    z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <img src="https://i.imgur.com/cULI8TG.png">
  <p>some text that runs over the image<mark>some text that runs over the image</mark></p>
  <p>some other text that runs over the image<mark>some other text that runs over the image</mark></p>
</div></code>```

with a background scroll fix, does introduce more overhead when scrolling

var $affected = $('.wrap, .wrap mark');
let handler = (e) => {
    $affected.css({'background-position' : '-'+window.scrollX+'px -'+window.scrollY+'px'});
}
$(window).on('resize scroll', handler);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrap, .wrap mark {
   background-image: url('https://i.imgur.com/hAodNjT.jpg');
   background-attachment: fixed;
}
.wrap p {
  position: relative;
}
.wrap mark {
   position: absolute;
   top: 0px;
   left: 0px;
   opacity: 0.4;
}
img {
   width: 300px;
   height: auto;
}
.wrap {
   padding-top:160px;
   position: relative;
   width: 400px;
   height: 400px;
}
.wrap img {
   position:absolute;
   top:60px;

   z-index:0;
}
.wrap p {
    position:relative;
    z-index: 1;
}</code>```

some text that runs over the imagesome text that runs over the image

some other text that runs over the imagesome other text that runs over the image

```

Title: Text Highlights as CSS masks?

Body:
You might be looking for the css property background-attachment: fixed. This does have the caveat that the background will no longer scroll with the page and remain static, but this way you can guarantee the overlap between the element background and the container background remain the same. There is a fix for the scrolling issue via javascript, for a minor overhead cost, depending on how heavy the graphics are for the browser to render/reposition.

Then you simply apply the same background to the background containing element(.wrap in my case) and the text containing element(wrap in my case) and you get your desired effect as shown in your second image.

Then put the mark in a paragraph element and repeat the text twice. Once in the paragraph, once within the mark.

Then set the paragraph to position relative, and the mark to absolute, so they overlap each other perfectly. This is to counteract the wrap being transparent and not showing the text properly, as the text also becoming transparent.

.wrap, .wrap mark {
   background-image: url('https://i.imgur.com/hAodNjT.jpg');
   background-attachment: fixed;
}
.wrap p {
  position: relative;
}
.wrap mark {
   position: absolute;
   top: 0px;
   left: 0px;
   opacity: 0.4;
}
img {
   width: 300px;
   height: auto;
}
.wrap {
   padding-top:160px;
   position: relative;
   width: 400px;
   height: 400px;
}
.wrap img {
   position:absolute;
   top:60px;

   z-index:0;
}
.wrap p {
    position:relative;
    z-index: 1;
}

<div class="wrap">
  <img src="https://i.imgur.com/cULI8TG.png">
  <p>some text that runs over the image<mark>some text that runs over the image</mark></p>
  <p>some other text that runs over the image<mark>some other text that runs over the image</mark></p>
</div>

with a background scroll fix, does introduce more overhead when scrolling

var $affected = $('.wrap, .wrap mark');
let handler = (e) => {
    $affected.css({'background-position' : '-'+window.scrollX+'px -'+window.scrollY+'px'});
}
$(window).on('resize scroll', handler);

.wrap, .wrap mark {
   background-image: url('https://i.imgur.com/hAodNjT.jpg');
   background-attachment: fixed;
}
.wrap p {
  position: relative;
}
.wrap mark {
   position: absolute;
   top: 0px;
   left: 0px;
   opacity: 0.4;
}
img {
   width: 300px;
   height: auto;
}
.wrap {
   padding-top:160px;
   position: relative;
   width: 400px;
   height: 400px;
}
.wrap img {
   position:absolute;
   top:60px;

   z-index:0;
}
.wrap p {
    position:relative;
    z-index: 1;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap">
  <img src="https://i.imgur.com/cULI8TG.png">
  <p>some text that runs over the image<mark>some text that runs over the image</mark></p>
  <p>some other text that runs over the image<mark>some other text that runs over the image</mark></p>
</div>


问:
res.redirect after res.json in node.js
I have the following code below
I want to redirect and return the response as well, can someone help me in this?
What is the better solution for this? </p>

```<code>try {
  res.json(await example.preview(access_token, context, id, body))
  res.redirect(`${sso.host}/session/login?grant_type=bearer&access_token=${access_token}&remember_me=true&redirect_uri=${encodeURIComponent(
 'https://example.com'
 )}`);
} catch (e) {
  logger.info(e);
  next(e);
}
</code>```

答:
You can use res.json to return a regular 200 response, with any data you wish and also add a redirectURL item, which will be handled on the client side.

Example on client side:

```<code>// Simulate a mouse click:
window.location.href = redirectURL;

// Simulate an HTTP redirect:
window.location.replace(redirectURL);
</code>```

Title: res.redirect after res.json in node.js

Body:
I have the following code below
I want to redirect and return the response as well, can someone help me in this?
What is the better solution for this?

try {
  res.json(await example.preview(access_token, context, id, body))
  res.redirect(`${sso.host}/session/login?grant_type=bearer&access_token=${access_token}&remember_me=true&redirect_uri=${encodeURIComponent(
 'https://example.com'
 )}`);
} catch (e) {
  logger.info(e);
  next(e);
}

Body:
You can use res.json to return a regular 200 response, with any data you wish and also add a redirectURL item, which will be handled on the client side.

Example on client side:

// Simulate a mouse click:
window.location.href = redirectURL;

// Simulate an HTTP redirect:
window.location.replace(redirectURL);


问:
Bangla font in pdf not show correctly in iReport
I have used iReport 5.6.0 for building report.I used SolaimanLipi font in my static field. iReport internal view no problem but after save as pdf(Open in pdf reader or any browser) bangla font not show correctly.

jrxml code:

```<code> <?xml version="1.0" encoding="UTF-8"?>
 <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="challanReport" language="groovy" pageWidth="842" pageHeight="595" orientation="Landscape" whenNoDataType="AllSectionsNoDetail" columnWidth="770" leftMargin="54" rightMargin="18" topMargin="20" bottomMargin="20" uuid="9126e000-dc70-4a76-9013-4a4fa290f0df">
<pageHeader>
    <band height="273" splitType="Stretch">
        <staticText>
            <reportElement x="13" y="10" width="403" height="20" uuid="1d2c7070-63f4-4a43-b3a2-63dc4c27c6f2"/>
            <textElement>
                <font fontName="SolaimanLipi" pdfEncoding="Identity-H"/>
            </textElement>
            <text><![CDATA[বাংলাদেশ ব্যাংক/সোনালী ব্যাংকের ....ঢাকা....জেলার....মহাখালী....শাখায় টাকা জমা দেওয়ার চালান ।]]></text>
        </staticText>
        <staticText>
            <reportElement x="429" y="10" width="69" height="20" uuid="21401d70-386e-4f01-bf34-586d58991b62"/>
            <box>
                <topPen lineWidth="0.25"/>
                <leftPen lineWidth="0.25"/>
                <bottomPen lineWidth="0.25"/>
                <rightPen lineWidth="0.25"/>
            </box>
            <textElement textAlignment="Center">
                <font fontName="SolaimanLipi" pdfFontName="Helvetica" pdfEncoding="Identity-H" isPdfEmbedded="true"/>
            </textElement>
            <text><![CDATA[১ম(মূল)কপি]]></text>
        </staticText>
        <staticText>
            <reportElement x="13" y="50" width="512" height="60" uuid="ee6769a0-b25e-4f60-b783-58b535f955d7"/>
            <box leftPadding="4">
                <topPen lineWidth="0.25"/>
                <leftPen lineWidth="0.25"/>
                <bottomPen lineWidth="0.25"/>
                <rightPen lineWidth="0.25"/>
            </box>
            <textElement>
                <font fontName="SolaimanLipi" pdfEncoding="Identity-H"/>
            </textElement>
            <text><![CDATA[বিভাগের নাম এবং চালানের পৃষ্ঠাংকনকারী  কর্মকর্তার নাম, পদবী ও দপ্তর l *]]></text>
        </staticText>
        <staticText>
            <reportElement x="13" y="30" width="512" height="20" uuid="1e86fa4b-88a3-4e05-b37a-3a4dbd0b2963"/>
            <box>
                <topPen lineWidth="0.25"/>
                <leftPen lineWidth="0.25"/>
                <bottomPen lineWidth="0.25"/>
                <rightPen lineWidth="0.25"/>
            </box>
            <textElement textAlignment="Center">
                <font fontName="SolaimanLipi" pdfEncoding="Identity-H" isPdfEmbedded="true"/>
            </textElement>
            <text><![CDATA[জমা প্রদানকারী কর্তৃক পূরণ করিতে হইবে |]]></text>
        </staticText>
    </band>
</pageHeader>
</code>```

iReport internal view:

iReport outside view:

How can solve this?

答:
Any Kind of Unicode font correctly showing process in pdf using jasper report

Step-1

Download your desire Unicode font xxx.ttf extension

Install this font in jasper studio font Installation instruction

Now use this custom font in your report

Step-2

Export your custom font jar from Jaspersoft-studio

Add this font jar in java build path or install this font in maven repository

If you manually add font in your project build path then ignore font installation process.

Font installation command

```<code>mvn install:install-file -Dfile=/your-jar-file-directory/fontName.jar -DgroupId=bangla -DartifactId=bangla -Dversion=1.0 -Dpackaging=jar
</code>```

After install font jar you need to add dependency in your pom file

Sample Dependency example

```<code>       <dependency>
            <groupId>bangla</groupId>
            <artifactId>bangla</artifactId>
            <version>1.0</version>
        </dependency>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have used iReport 5.6.0 for building report.I used SolaimanLipi font in my static field. iReport internal view no problem but after save as pdf(Open in pdf reader or any browser) bangla font not show correctly.

jrxml code:

 <?xml version="1.0" encoding="UTF-8"?>
 <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="challanReport" language="groovy" pageWidth="842" pageHeight="595" orientation="Landscape" whenNoDataType="AllSectionsNoDetail" columnWidth="770" leftMargin="54" rightMargin="18" topMargin="20" bottomMargin="20" uuid="9126e000-dc70-4a76-9013-4a4fa290f0df">
<pageHeader>
    <band height="273" splitType="Stretch">
        <staticText>
            <reportElement x="13" y="10" width="403" height="20" uuid="1d2c7070-63f4-4a43-b3a2-63dc4c27c6f2"/>
            <textElement>

            </textElement>
            <text><![CDATA[বাংলাদেশ ব্যাংক/সোনালী ব্যাংকের ....ঢাকা....জেলার....মহাখালী....শাখায় টাকা জমা দেওয়ার চালান ।]]></text>
        </staticText>
        <staticText>
            <reportElement x="429" y="10" width="69" height="20" uuid="21401d70-386e-4f01-bf34-586d58991b62"/>
            <box>
                <topPen lineWidth="0.25"/>
                <leftPen lineWidth="0.25"/>
                <bottomPen lineWidth="0.25"/>
                <rightPen lineWidth="0.25"/>
            </box>
            <textElement textAlignment="Center">

            </textElement>
            <text><![CDATA[১ম(মূল)কপি]]></text>
        </staticText>
        <staticText>
            <reportElement x="13" y="50" width="512" height="60" uuid="ee6769a0-b25e-4f60-b783-58b535f955d7"/>
            <box leftPadding="4">
                <topPen lineWidth="0.25"/>
                <leftPen lineWidth="0.25"/>
                <bottomPen lineWidth="0.25"/>
                <rightPen lineWidth="0.25"/>
            </box>
            <textElement>

            </textElement>
            <text><![CDATA[বিভাগের নাম এবং চালানের পৃষ্ঠাংকনকারী  কর্মকর্তার নাম, পদবী ও দপ্তর l *]]></text>
        </staticText>
        <staticText>
            <reportElement x="13" y="30" width="512" height="20" uuid="1e86fa4b-88a3-4e05-b37a-3a4dbd0b2963"/>
            <box>
                <topPen lineWidth="0.25"/>
                <leftPen lineWidth="0.25"/>
                <bottomPen lineWidth="0.25"/>
                <rightPen lineWidth="0.25"/>
            </box>
            <textElement textAlignment="Center">

            </textElement>
            <text><![CDATA[জমা প্রদানকারী কর্তৃক পূরণ করিতে হইবে |]]></text>
        </staticText>
    </band>
</pageHeader>

iReport internal view:

iReport outside view:

How can solve this?

Body:
Any Kind of Unicode font correctly showing process in pdf using jasper report

Step-1

Download your desire Unicode font xxx.ttf extension

Install this font in jasper studio font Installation instruction

Now use this custom font in your report

Step-2

Export your custom font jar from Jaspersoft-studio

Add this font jar in java build path or install this font in maven repository

If you manually add font in your project build path then ignore font installation process.

Font installation command

mvn install:install-file -Dfile=/your-jar-file-directory/fontName.jar -DgroupId=bangla -DartifactId=bangla -Dversion=1.0 -Dpackaging=jar

After install font jar you need to add dependency in your pom file

Sample Dependency example

       <dependency>
            <groupId>bangla</groupId>
            <artifactId>bangla</artifactId>
            <version>1.0</version>
        </dependency>


问:
how to select distinct values from 2 tables in sql
table1

```<code>id
1
2
3
4
5
</code>```

table2

```<code>id
4
5
6
7
8
</code>```

I want to result in this way:

```<code>id
1
2
3
6
7
8
</code>```

答:
you can use

DISTINCT

your example:

```<code>SELECT DISTINCT id from  table1 a, table2 b where a.id =b.id
</code>```

Body:
table1

id
1
2
3
4
5

table2

id
4
5
6
7
8

I want to result in this way:

id
1
2
3
6
7
8

Body:
you can use

DISTINCT

your example:

SELECT DISTINCT id from  table1 a, table2 b where a.id =b.id


问:
How to import css file from assets folder in nuxt.js
```<code><template>
  <div class="container">
    <head>
      <link rel="stylesheet" href="~assets/css/style-light.css" />
      <link rel="stylesheet" href="~assets/css/login-light.css" />
    </head>
  </div>
</template>
</code>```

Importing css like above results in this error

```<code>vue.runtime.esm.js:5717 GET http://localhost:3000/~assets/css/login-light.css net::ERR_ABORTED 404 (Not Found)
</code>```

Is there really no other way loading css other than putting the whole css in the template?

答:
You could bring your files in using the head method like so :

```<code>head () {
return {
  link: [
    { rel: 'stylesheet', href: '/style-light.css' },
    { rel: 'stylesheet', href: '/login-light.css' }
  ]
}
</code>```

}

You should also move these css files into the static folder. See this discussion on the Vue forum https://forum.vuejs.org/t/nuxt-import-css-file-and-js-file/42498

Body:
<template>

      <link rel="stylesheet" href="~assets/css/style-light.css" />
      <link rel="stylesheet" href="~assets/css/login-light.css" />

</template>

Importing css like above results in this error

vue.runtime.esm.js:5717 GET http://localhost:3000/~assets/css/login-light.css net::ERR_ABORTED 404 (Not Found)

Is there really no other way loading css other than putting the whole css in the template?

Body:
You could bring your files in using the head method like so :

head () {
return {
  link: [
    { rel: 'stylesheet', href: '/style-light.css' },
    { rel: 'stylesheet', href: '/login-light.css' }
  ]
}

}

You should also move these css files into the static folder. See this discussion on the Vue forum https://forum.vuejs.org/t/nuxt-import-css-file-and-js-file/42498


问:
Disable past date in DatePickerDialog
I want to add code .getDatePicker().setMinDate(newDate.getTime() - (newDate.getTime()%(24*60*60*1000)))for disable the past date but suddenly .show() cannot be used.

Can someone teach me how to solve this kind of problem?

Code:

```<code>btnDate.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            selectDate();
                        }
                    });

private void selectDate()
{
    DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            String selectedDate = dateFormat.format(calendar.getTime());

            btnDate.setText(selectedDate);
            btnDate.setTextColor(getResources().getColor(colorPrimaryDark));
        }
    };

    Date newDate = calendar.getTime();

    new DatePickerDialog(TutorAddNewTimeSlotActivity.this,  dateSetListener,
            calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
}
</code>```

答:
First of all declare as following:

```<code>private Calendar myCalendar = Calendar.getInstance();
</code>```

then like your code:-

```<code>DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

        String selectedDate = dateFormat.format(calendar.getTime());

        btnDate.setText(selectedDate);
        btnDate.setTextColor(getResources().getColor(colorPrimaryDark));
    }
};
</code>```

make this change in your code instead of your last two lines:

```<code>`Date newDate = calendar.getTime();

new DatePickerDialog(TutorAddNewTimeSlotActivity.this,  dateSetListener,
        calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();`
</code>```

change it and make it like following:

datePickerDialog.getDatePicker().setMinDate(myCalendar.getTimeInMillis());
                datePickerDialog.show();

which will disable past date.

Title: Disable past date in DatePickerDialog

Body:
I want to add code .getDatePicker().setMinDate(newDate.getTime() - (newDate.getTime()%(24*60*60*1000)))for disable the past date but suddenly .show() cannot be used.

Can someone teach me how to solve this kind of problem?

Code:

btnDate.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            selectDate();
                        }
                    });

private void selectDate()
{
    DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            String selectedDate = dateFormat.format(calendar.getTime());

            btnDate.setText(selectedDate);
            btnDate.setTextColor(getResources().getColor(colorPrimaryDark));
        }
    };

    Date newDate = calendar.getTime();

    new DatePickerDialog(TutorAddNewTimeSlotActivity.this,  dateSetListener,
            calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
}

Body:
First of all declare as following:

private Calendar myCalendar = Calendar.getInstance();

then like your code:-

DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

        String selectedDate = dateFormat.format(calendar.getTime());

        btnDate.setText(selectedDate);
        btnDate.setTextColor(getResources().getColor(colorPrimaryDark));
    }
};

make this change in your code instead of your last two lines:

`Date newDate = calendar.getTime();

new DatePickerDialog(TutorAddNewTimeSlotActivity.this,  dateSetListener,
        calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();`

change it and make it like following:

datePickerDialog.getDatePicker().setMinDate(myCalendar.getTimeInMillis());
                datePickerDialog.show();

which will disable past date.


问:
Display laravel retrun result in html table using jquery- Ajax
In Laravel Blade I have a script for searching

```<code> <script type="text/javascript">
    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
        url: "{{ URL::asset('upload-panel/search')}}",
        data: dataString,
        dataType:"JSON",
        cache: false,
        success: function(result) {
        var FinalResult=result.CallDetails
        num_rows = result.length;
        console.log(result)

        },error:function(x,e) {
            setTimeout(function() {searchPhoneCalls();}, 2000);
        }
    })
</script>
</code>```

search function in controller returns is below

return  json_encode($users);

In console am getting the result as an array like below

```<code>0: {Short_name: "GO120762", Date: "21-01-2020"}
1: {Short_name: "GO120764", Date: "21-01-2020"}
2: {Short_name: "GO120766", Date: "21-01-2020"}
</code>```

I want to display those result in a HTML  table  like below

```<code>+----------+------------+
| Name     | Date       |
+----------+------------+
| GO120762 | 21-01-2020 |
+----------+------------+
| GO120764 | 21-01-2020 |
+----------+------------+
| GO120766 | 21-01-2020 |
+----------+------------+

</code>```

答:
It has nothing to deal with Laravel, it's pure HTML / jQuery "problem".

There is no such key named CallDetails exists in received JSON

You can build an array in your HTML :

```<code><table id="table-search"></table>
</code>```

And in your JS :

```<code>var $tableSearch = $('#table-search');
$tableSearch.html('');
//var FinalResult = result.CallDetails
result.forEach(function(row) {
    $tableSearch.append('<tr><td>'+ row.Short_name +'</td><td>'+ row.Date +'</td></tr>');
});
</code>```

Body:
In Laravel Blade I have a script for searching

search function in controller returns is below

return  json_encode($users);

In console am getting the result as an array like below

0: {Short_name: "GO120762", Date: "21-01-2020"}
1: {Short_name: "GO120764", Date: "21-01-2020"}
2: {Short_name: "GO120766", Date: "21-01-2020"}

I want to display those result in a HTML  table  like below

+----------+------------+
| Name     | Date       |
+----------+------------+
| GO120762 | 21-01-2020 |
+----------+------------+
| GO120764 | 21-01-2020 |
+----------+------------+
| GO120766 | 21-01-2020 |
+----------+------------+

Body:
It has nothing to deal with Laravel, it's pure HTML / jQuery "problem".

There is no such key named CallDetails exists in received JSON

You can build an array in your HTML :

<table id="table-search"></table>

And in your JS :

var $tableSearch = $('#table-search');
$tableSearch.html('');
//var FinalResult = result.CallDetails
result.forEach(function(row) {
    $tableSearch.append('<tr><td>'+ row.Short_name +'</td><td>'+ row.Date +'</td></tr>');
});


问:
Not all kafka consumers are getting assigned to partitions
I have 10 consumers and 10 partitions.
I take the number of partitions

```<code>int partitionCount = getPartitionCount(kafkaUrl);
</code>```

and I create the same number of consumers with the same group.id.

```<code>    public void listen() {
        try {
            String kafkaUrl = getKafkaUrl();
            int partitionCount = getPartitionCount(kafkaUrl);
            Stream.iterate(0, i -> i + 1)
                    .limit(partitionCount)
                    .forEach(index -> executorService.execute(() ->
                            consumerTask.invokeKafkaConsumerTask(prepareConsumerConfig(index, kafkaUrl), INPUT_TOPIC)));
        } catch (Exception exception) {
            logger.error("Cannot receive event from kafka ", exception);
        }

    public void invokeKafkaConsumerTask(Properties properties, String topicName) {
        try(KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties)) {
            consumer.subscribe(Collections.singletonList(topicName));
            logger.info("[KAFKA] consumer created");
            invokeKafkaConsumer(consumer);
        } catch (IllegalArgumentException exception) {
            logger.error("Cannot create kafka consumer ", exception);
        }
    }

    private void invokeKafkaConsumer(KafkaConsumer<String, String> consumer) {
        try {
            while (true) {
                ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofSeconds(4));
                if (consumerRecords.count() > 0) {
                    consumeRecords(consumerRecords);
                    consumer.commitSync();
                }
            }
        } catch (Exception e) {
            logger.error("Error while receiving records ", e);
        }
    }
</code>```

method getPartitionCount
return 10 partitions so it's working right

config looks like this

```<code>Properties properties = new Properties();
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaUrl);
properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.put(ConsumerConfig.GROUP_ID_CONFIG, CONSUMER_CLIENT_ID);
properties.put(ConsumerConfig.CLIENT_ID_CONFIG, CONSUMER_CLIENT_ID + index);
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
properties.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "300000");
properties.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, "10000");
properties.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, String.valueOf(Integer.MAX_VALUE));
properties.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, "org.apache.kafka.clients.consumer.RoundRobinAssignor");
</code>```

what I see after assigning consumers to the partition

```<code>TOPIC      PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CLIENT-ID
topicName  1          89391           89391           0               consumer0
topicName  3          88777           88777           0               consumer1
topicName  5          89280           89280           0               consumer2
topicName  4          88776           88776           0               consumer2
topicName  0          4670991         4670991         0               consumer0
topicName  9          23307           89343           66036           consumer4
topicName  7          89610           89610           0               consumer3
topicName  8          88167           88167           0               consumer4
topicName  2          89138           89138           0               consumer1
topicName  6          88967           88967           0               consumer3
</code>```

only half of the consumers have been assigned to the partitions
why did this happen?
There should be one consumer per partition acording to documentation.
 Am I doing something wrong?
 kafka version 2.1.1.

I also find few this logs ->

```<code>Setting newly assigned partitions:[empty]
</code>```

答: [solution] interesting case I changed group.id and partition.assignment.strategy, added auto.offset.reset=earliest and it looks like it works...</p>

Body:
I have 10 consumers and 10 partitions.
I take the number of partitions

int partitionCount = getPartitionCount(kafkaUrl);

and I create the same number of consumers with the same group.id.

    public void listen() {
        try {
            String kafkaUrl = getKafkaUrl();
            int partitionCount = getPartitionCount(kafkaUrl);
            Stream.iterate(0, i -> i + 1)
                    .limit(partitionCount)
                    .forEach(index -> executorService.execute(() ->
                            consumerTask.invokeKafkaConsumerTask(prepareConsumerConfig(index, kafkaUrl), INPUT_TOPIC)));
        } catch (Exception exception) {
            logger.error("Cannot receive event from kafka ", exception);
        }

    public void invokeKafkaConsumerTask(Properties properties, String topicName) {
        try(KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties)) {
            consumer.subscribe(Collections.singletonList(topicName));
            logger.info("[KAFKA] consumer created");
            invokeKafkaConsumer(consumer);
        } catch (IllegalArgumentException exception) {
            logger.error("Cannot create kafka consumer ", exception);
        }
    }

    private void invokeKafkaConsumer(KafkaConsumer<String, String> consumer) {
        try {
            while (true) {
                ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofSeconds(4));
                if (consumerRecords.count() > 0) {
                    consumeRecords(consumerRecords);
                    consumer.commitSync();
                }
            }
        } catch (Exception e) {
            logger.error("Error while receiving records ", e);
        }
    }

method getPartitionCount
return 10 partitions so it's working right

config looks like this

Properties properties = new Properties();
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaUrl);
properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.put(ConsumerConfig.GROUP_ID_CONFIG, CONSUMER_CLIENT_ID);
properties.put(ConsumerConfig.CLIENT_ID_CONFIG, CONSUMER_CLIENT_ID + index);
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
properties.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "300000");
properties.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, "10000");
properties.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, String.valueOf(Integer.MAX_VALUE));
properties.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, "org.apache.kafka.clients.consumer.RoundRobinAssignor");

what I see after assigning consumers to the partition

TOPIC      PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CLIENT-ID
topicName  1          89391           89391           0               consumer0
topicName  3          88777           88777           0               consumer1
topicName  5          89280           89280           0               consumer2
topicName  4          88776           88776           0               consumer2
topicName  0          4670991         4670991         0               consumer0
topicName  9          23307           89343           66036           consumer4
topicName  7          89610           89610           0               consumer3
topicName  8          88167           88167           0               consumer4
topicName  2          89138           89138           0               consumer1
topicName  6          88967           88967           0               consumer3

only half of the consumers have been assigned to the partitions
why did this happen?
There should be one consumer per partition acording to documentation.
 Am I doing something wrong?
 kafka version 2.1.1.

I also find few this logs ->

Setting newly assigned partitions:[empty]


Title: Arranging timestamp according to required condition

Body:
I've list of timestamp values stored in a nested list below.

[[1462692695.0, 1462857370.0, 1463297496.0],

[1466695088.0, 1466933174.0, 1467067583.0, 1467252502.0, 1467253381.0],

[1455009108.0, 1455218354.0, 1455221295.0],

[1456098479.0, 1456242604.0, 1456277812.0, 1456683177.0]]

And I want to find the difference between second and first, third and second and so on.. for each of the nested list values.

For example:
The newly created difference list:

[[164675,440126],
 [...,...,...,...],
....]

Body:
This answer might be helpful (using only built-in python functions):

x = [[1462692695.0, 1462857370.0, 1463297496.0], [1466695088.0, 1466933174.0, 1467067583.0, 1467252502.0, 1467253381.0], [1455009108.0, 1455218354.0, 1455221295.0], [1456098479.0, 1456242604.0, 1456277812.0, 1456683177.0]]
[[t - s for s, t in zip(a, a[1:])] for a in x]

Result:

[[164675.0, 440126.0],
[238086.0, 134409.0, 184919.0, 879.0],
[209246.0, 2941.0],
[144125.0, 35208.0, 405365.0]]


问:
how to display product detail description on product listing page?
I want to show a detailed product description after a short description on the product listing page.

I'm doing this

```<code><?
echo $_product->getDescription();
?>
</code>```

but nothing shows up.

I also tried this

```<code>Mage::getModel('catalog/product')->load($_product->getProductId())->getDescription();
</code>```

but to no success.

答:
The correct code is:</p>

```<code><?php

$my_product = Mage::getModel('catalog/product')->load($_product->getId());

echo $my_product->getDescription();

?>
</code>```

Body:
I want to show a detailed product description after a short description on the product listing page.

I'm doing this

<?
echo $_product->getDescription();
?>

but nothing shows up.

I also tried this

Mage::getModel('catalog/product')->load($_product->getProductId())->getDescription();

but to no success.

Body:
The correct code is:

<?php

$my_product = Mage::getModel('catalog/product')->load($_product->getId());

echo $my_product->getDescription();

?>


问:
Wordpress blocks: async REST calls in registerBlockType edit function
I'm writing a WordPress plugin that creates a block, the block needs to pull data using a custom REST endpoint that returns, in the example below, a simple string. I'd like to include this string in the return from edit() and save() in my registerBlockType config but. I'm using fetch() to call the REST endpoint but this, obviously, is async. Any thoughts on the best way to do this appreciated, thanks:</p>

```<code>const { registerBlockType } = wp.blocks

registerBlockType( 'daisy-views/da-test', {
    title:      'Daisy Test: Test Block',
    icon:       'format-gallery',
    category:   'common',
    attributes: {
        gid: {
            default: 2,
            type:   'integer'
        },
    },

    edit( props ) {

        const restEP = daRestUrl + 'test'

        fetch( restEP, {
            body: JSON.stringify( {p: 'test param'}),  // test parameters
            cache: 'no-cache',
            method: 'POST',
            redirect: 'follow',
            referrer: 'no-referrer',
            headers : {
                'Access-Control-Allow-Origin' : '*',
                'X-WP-Nonce' : wpApiSettings.nonce,
            }
        })
            .then( response => {
                response.json()
                    .then( data => {
                        var returnValue = data.data                     // REST test, returns a string
                        console.log( 'Fetch returns: ', returnValue )
                    })
            })

        return <div>
            test block edit
                {/* return value from fetch here */}
            </div>
    },
    save( props ) {

        return <div>
            Test Block
            {/* return value from fetch here */}
            </div>
    }
} );
</code>```

答: My best solution, to date, is to add a code attribute and have the fetch call fill that attribute with HTML. if fetch is called directly in the edit function there needs to be a check to prevent it from being called in an endless loop when it updates the attribute.</p>

Body:
I'm writing a WordPress plugin that creates a block, the block needs to pull data using a custom REST endpoint that returns, in the example below, a simple string. I'd like to include this string in the return from edit() and save() in my registerBlockType config but. I'm using fetch() to call the REST endpoint but this, obviously, is async. Any thoughts on the best way to do this appreciated, thanks:

const { registerBlockType } = wp.blocks

registerBlockType( 'daisy-views/da-test', {
    title:      'Daisy Test: Test Block',
    icon:       'format-gallery',
    category:   'common',
    attributes: {
        gid: {
            default: 2,
            type:   'integer'
        },
    },

    edit( props ) {

        const restEP = daRestUrl + 'test'

        fetch( restEP, {
            body: JSON.stringify( {p: 'test param'}),  // test parameters
            cache: 'no-cache',
            method: 'POST',
            redirect: 'follow',
            referrer: 'no-referrer',
            headers : {
                'Access-Control-Allow-Origin' : '*',
                'X-WP-Nonce' : wpApiSettings.nonce,
            }
        })
            .then( response => {
                response.json()
                    .then( data => {
                        var returnValue = data.data                     // REST test, returns a string
                        console.log( 'Fetch returns: ', returnValue )
                    })
            })

        return

            test block edit
                {/* return value from fetch here */}

    },
    save( props ) {

        return

            Test Block
            {/* return value from fetch here */}

    }
} );


问:
How to select the members who has transacted on the last date of every month from a large data
I have data of members who have transacted everyday, I need list of all the members who have transacted on the last date of each month for the whole year.

My output needs to have a list of members (with all the columns) who have transacted on 31-Jan-2019, 28-Feb-2019 and so on upto 31-Dec-2019.

答:
Okay here a pretty inefficient code (relatively new to R), but I think it works if you only want to do this for the year 2019.</p>

```<code>#create a manual dataframe with the last days of the months in 2019
LastDays <- structure(list(Date = structure(c(7L, 2L, 10L, 4L, 11L, 5L,
12L, 13L, 6L, 8L, 3L, 1L, 9L), .Label = c("10-12-2019", "28-2-2019",
"30-11-2019", "30-4-2019", "30-6-2019", "30-9-2019", "31-1-2019",
"31-10-2019", "31-12-2019", "31-3-2019", "31-5-2019", "31-7-2019",
"31-8-2019"), class = "factor")), class = "data.frame", row.names = c(NA,
-13L))

#remove transactions on other dates in a new dataframe
df_subset <- df[which(df$Date %in% LastDays$Date),]

#find Members which did transactions on all the last days of the month
Members <- df_subset %>% group_by(Member, Date) %>% summarise_all(funs(mean)) %>% select(Member, Date) %>% filter(n() >11)
Members <- unique(Members$Member)

#The information of all the members which transacted on all last dates of the year
df[which(df$Member %in% Members),]
</code>```

Body:
Okay here a pretty inefficient code (relatively new to R), but I think it works if you only want to do this for the year 2019.

#create a manual dataframe with the last days of the months in 2019
LastDays <- structure(list(Date = structure(c(7L, 2L, 10L, 4L, 11L, 5L,
12L, 13L, 6L, 8L, 3L, 1L, 9L), .Label = c("10-12-2019", "28-2-2019",
"30-11-2019", "30-4-2019", "30-6-2019", "30-9-2019", "31-1-2019",
"31-10-2019", "31-12-2019", "31-3-2019", "31-5-2019", "31-7-2019",
"31-8-2019"), class = "factor")), class = "data.frame", row.names = c(NA,
-13L))

#remove transactions on other dates in a new dataframe
df_subset <- df[which(df$Date %in% LastDays$Date),]

#find Members which did transactions on all the last days of the month
Members <- df_subset %>% group_by(Member, Date) %>% summarise_all(funs(mean)) %>% select(Member, Date) %>% filter(n() >11)
Members <- unique(Members$Member)

#The information of all the members which transacted on all last dates of the year
df[which(df$Member %in% Members),]


问:
perl - matching greater than charater in regex
```<code>$string1="<a href='/channels/folder1'>Alpha-Seeking";
$string2="<a href='/channels/folder2'>No Underlying Index ,";
</code>```

I need to extract "Alpha-Seeking" and "No Underlying Index ," from the above 2 strings.
Basically, need everything from ('>) to the last character of the string.

Tried two ways,

1) The standard intuitive

```<code>($string1=~ /\'>(.*?)/) {print "got $1";}
</code>```

but this does not seem to work on '>' symbol.

2) Also tried

```<code>if ($string1=~ /(?=>)(.*?)/) {print "got $1";}
</code>```

based on inputs from Greater than and less than symbol in regular expressions, but it is not working.

Any inputs will be useful.

PS: Also, if the answer can include matching the "less than" symbo ("<"), that will be great!

Thanks

答:
While exploring various options, I managed to get this working with the following:

Replace the greater than sign with some other generic symbol (like a pipe)

```<code>$string=~ s/>/\|/g;                 #Interestingly, '>' matches here without any issues
</code>```

After that, split on the pipe char, and print/parse the second part:

```<code>    ($o1,$o2) = split(/\|/, $string);
    print "$o2|";
</code>```

Works perfectly as a work-around.

Body:
$string1="Alpha-Seeking";
$string2="No Underlying Index ,";

I need to extract "Alpha-Seeking" and "No Underlying Index ," from the above 2 strings.
Basically, need everything from ('>) to the last character of the string.

Tried two ways,

1) The standard intuitive

($string1=~ /\'>(.*?)/) {print "got $1";}

but this does not seem to work on '>' symbol.

2) Also tried

if ($string1=~ /(?=>)(.*?)/) {print "got $1";}

based on inputs from Greater than and less than symbol in regular expressions, but it is not working.

Any inputs will be useful.

PS: Also, if the answer can include matching the "less than" symbo ("<"), that will be great!

Thanks

Body:
While exploring various options, I managed to get this working with the following:

Replace the greater than sign with some other generic symbol (like a pipe)

$string=~ s/>/\|/g;                 #Interestingly, '>' matches here without any issues

After that, split on the pipe char, and print/parse the second part:

    ($o1,$o2) = split(/\|/, $string);
    print "$o2|";

Works perfectly as a work-around.


问:
Angular test how to mock ActivatedRoute data
I have a real big problem with mocking ActivatedRoute data property. No matter what I am doing all it ends up with error message : Error: <spyOnProperty> : Property data does not have access type get. Moving stub const to separate mock class also not solving the issue. I have found that this should be straight forward but I am struggling with this for a few days now.

Component

```<code>@Component({
  selector: 'app-notifications',
  templateUrl: './notifications.component.html',
  styleUrls: ['./notifications.component.css']
})
export class NotificationsComponent implements OnInit {
  notifications: NotificationEntry[];

  constructor(
    private route: ActivatedRoute,
    private modalService: ModalService,
    private messageBoxService: MessageBoxService,
    private notificationsService: NotificationsService
  ) {}

  ngOnInit() {
    this.route.data.subscribe(
      (data: { notifications: NotificationEntry[] }) => {
        this.notifications = data.notifications;
      }
    );
  }
}
</code>```

Component.spec

```<code>describe('NotificationsComponent', () => {
  let component: NotificationsComponent;
  let fixture: ComponentFixture<NotificationsComponent>;

  const registryVersionBasicData = new RegistryVersionBasicData(
    false,
    'versionId',
    new JsonDate('Unspecified', 631894104000000000),
    'user',
    'comment'
  )

  const notifications = new NotificationEntry(
    new JsonDate('Unspecified', 631894104000000000),
    'summary',
    'message',
    NotificationEntityType.StressScenario,
    'instance name',
    'instance key',
    registryVersionBasicData,
    'additional information')

  const notificationsArray = [notifications]

  beforeEach(() => {
    const activatedRouteStub = { data: of({ notifications: notificationsArray }) };
    const modalServiceStub = {};
    const messageBoxServiceStub = {};
    const notificationsServiceStub = {};

    TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [NotificationsComponent, OrderPipe, RenderDatePipe, VersionInfoPipe],
      providers: [
        { provide: ActivatedRoute, useValue: activatedRouteStub },
        { provide: ModalService, useValue: modalServiceStub },
        { provide: MessageBoxService, useValue: messageBoxServiceStub },
        { provide: NotificationsService, useValue: notificationsServiceStub },
      ]
    }).compileComponents();

    fixture = TestBed.createComponent(NotificationsComponent);
    component = fixture.componentInstance;
  });

  it('can load instance', () => {
    expect(component).toBeTruthy();
  });

  describe('ngOnInit', () => {
    it('should get notifications entry', () => {
      const activatedRouteStub = TestBed.get(ActivatedRoute);
      spyOnProperty(activatedRouteStub, 'data')

      component.ngOnInit();

      expect(component.notifications).toEqual(notificationsArray)
    });
  });
});
</code>```

答:
```<code>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { NotificationsComponent } from './notifications.component';
import { ActivatedRoute } from '@angular/router';
import { ModalService, MessageBoxService, NotificationsService, NotificationEntry, JsonDate, NotificationEntityType, RegistryVersionBasicData } from 'src/app/shared';
import { OrderPipe } from 'ngx-order-pipe';
import { RenderDatePipe } from 'src/app/shared/pipes/renderdate.pipe';
import { VersionInfoPipe } from 'src/app/shared/pipes/versioninfo.pipe';
import { of } from 'rxjs';

fdescribe('NotificationsComponent', () => {
  let component: NotificationsComponent;
  let fixture: ComponentFixture<NotificationsComponent>;

  const registryVersionBasicData = new RegistryVersionBasicData(
    false,
    'versionId',
    new JsonDate('Unspecified', 631894104000000000),
    'user',
    'comment'
  );

  const notifications = new NotificationEntry(
    new JsonDate('Unspecified', 631894104000000000),
    'summary',
    'message',
    NotificationEntityType.StressScenario,
    'instance name',
    'instance key',
    registryVersionBasicData,
    'additional information');

  const route = { data: of({ notifications: [notifications] }) };

  beforeEach(() => {
    const modalServiceStub = {};
    const messageBoxServiceStub = {};
    const notificationsServiceStub = {};

    TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [NotificationsComponent, OrderPipe, RenderDatePipe, VersionInfoPipe],
      providers: [
        { provide: ActivatedRoute, useValue: route },
        { provide: ModalService, useValue: modalServiceStub },
        { provide: MessageBoxService, useValue: messageBoxServiceStub },
        { provide: NotificationsService, useValue: notificationsServiceStub },
      ]
    });

    fixture = TestBed.createComponent(NotificationsComponent);
    component = fixture.componentInstance;
  });

  it('can load instance', () => {
    expect(component).toBeTruthy();
  });

  describe('ngOnInit', () => {
    it('should get notifications entry', () => {
      component.ngOnInit();
      expect(component.notifications).toEqual([notifications]);
    });
  });
});
</code>```

Simplest possible solution. Use:

```<code>const route = { data: of({ notifications: [notifications] }) };
</code>```

.. and then, use this value in component providers:

```<code>{ provide: ActivatedRoute, useValue: route }
</code>```

.. as a primitive mock for ActivatedRoute. Then, your test case can look like this (no TestBed needed):

```<code>  describe('ngOnInit', () => {
    it('should get notifications entry', () => {
      component.ngOnInit();
      expect(component.notifications).toEqual([notifications]);
    });
  });
</code>```

Body:
I have a real big problem with mocking ActivatedRoute data property. No matter what I am doing all it ends up with error message : Error: <spyOnProperty> : Property data does not have access type get. Moving stub const to separate mock class also not solving the issue. I have found that this should be straight forward but I am struggling with this for a few days now.

Component

@Component({
  selector: 'app-notifications',
  templateUrl: './notifications.component.html',
  styleUrls: ['./notifications.component.css']
})
export class NotificationsComponent implements OnInit {
  notifications: NotificationEntry[];

  constructor(
    private route: ActivatedRoute,
    private modalService: ModalService,
    private messageBoxService: MessageBoxService,
    private notificationsService: NotificationsService
  ) {}

  ngOnInit() {
    this.route.data.subscribe(
      (data: { notifications: NotificationEntry[] }) => {
        this.notifications = data.notifications;
      }
    );
  }
}

Component.spec

describe('NotificationsComponent', () => {
  let component: NotificationsComponent;
  let fixture: ComponentFixture<NotificationsComponent>;

  const registryVersionBasicData = new RegistryVersionBasicData(
    false,
    'versionId',
    new JsonDate('Unspecified', 631894104000000000),
    'user',
    'comment'
  )

  const notifications = new NotificationEntry(
    new JsonDate('Unspecified', 631894104000000000),
    'summary',
    'message',
    NotificationEntityType.StressScenario,
    'instance name',
    'instance key',
    registryVersionBasicData,
    'additional information')

  const notificationsArray = [notifications]

  beforeEach(() => {
    const activatedRouteStub = { data: of({ notifications: notificationsArray }) };
    const modalServiceStub = {};
    const messageBoxServiceStub = {};
    const notificationsServiceStub = {};

    TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [NotificationsComponent, OrderPipe, RenderDatePipe, VersionInfoPipe],
      providers: [
        { provide: ActivatedRoute, useValue: activatedRouteStub },
        { provide: ModalService, useValue: modalServiceStub },
        { provide: MessageBoxService, useValue: messageBoxServiceStub },
        { provide: NotificationsService, useValue: notificationsServiceStub },
      ]
    }).compileComponents();

    fixture = TestBed.createComponent(NotificationsComponent);
    component = fixture.componentInstance;
  });

  it('can load instance', () => {
    expect(component).toBeTruthy();
  });

  describe('ngOnInit', () => {
    it('should get notifications entry', () => {
      const activatedRouteStub = TestBed.get(ActivatedRoute);
      spyOnProperty(activatedRouteStub, 'data')

      component.ngOnInit();

      expect(component.notifications).toEqual(notificationsArray)
    });
  });
});

Body:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { NotificationsComponent } from './notifications.component';
import { ActivatedRoute } from '@angular/router';
import { ModalService, MessageBoxService, NotificationsService, NotificationEntry, JsonDate, NotificationEntityType, RegistryVersionBasicData } from 'src/app/shared';
import { OrderPipe } from 'ngx-order-pipe';
import { RenderDatePipe } from 'src/app/shared/pipes/renderdate.pipe';
import { VersionInfoPipe } from 'src/app/shared/pipes/versioninfo.pipe';
import { of } from 'rxjs';

fdescribe('NotificationsComponent', () => {
  let component: NotificationsComponent;
  let fixture: ComponentFixture<NotificationsComponent>;

  const registryVersionBasicData = new RegistryVersionBasicData(
    false,
    'versionId',
    new JsonDate('Unspecified', 631894104000000000),
    'user',
    'comment'
  );

  const notifications = new NotificationEntry(
    new JsonDate('Unspecified', 631894104000000000),
    'summary',
    'message',
    NotificationEntityType.StressScenario,
    'instance name',
    'instance key',
    registryVersionBasicData,
    'additional information');

  const route = { data: of({ notifications: [notifications] }) };

  beforeEach(() => {
    const modalServiceStub = {};
    const messageBoxServiceStub = {};
    const notificationsServiceStub = {};

    TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [NotificationsComponent, OrderPipe, RenderDatePipe, VersionInfoPipe],
      providers: [
        { provide: ActivatedRoute, useValue: route },
        { provide: ModalService, useValue: modalServiceStub },
        { provide: MessageBoxService, useValue: messageBoxServiceStub },
        { provide: NotificationsService, useValue: notificationsServiceStub },
      ]
    });

    fixture = TestBed.createComponent(NotificationsComponent);
    component = fixture.componentInstance;
  });

  it('can load instance', () => {
    expect(component).toBeTruthy();
  });

  describe('ngOnInit', () => {
    it('should get notifications entry', () => {
      component.ngOnInit();
      expect(component.notifications).toEqual([notifications]);
    });
  });
});

Simplest possible solution. Use:

const route = { data: of({ notifications: [notifications] }) };

.. and then, use this value in component providers:

{ provide: ActivatedRoute, useValue: route }

.. as a primitive mock for ActivatedRoute. Then, your test case can look like this (no TestBed needed):

  describe('ngOnInit', () => {
    it('should get notifications entry', () => {
      component.ngOnInit();
      expect(component.notifications).toEqual([notifications]);
    });
  });


问:
How to pass arguments in native sql query in Repository file in java?
This is my query, I have written in Repository file.

```<code>@Query(value = "select * from A a join B b ON a.allocateBy = b.empNo join D d ON b.departmentName = d.departmentName where a.allocateBy in (:allocateByList)",  nativeQuery = true)

ArrayList<A> findAllByAllocateByIn(@Param("allocateByList") String allocateByList);
</code>```

There are no errors but :allocateByList is not getting data. I have printed the value of allocateByList just before. It has data.

Am I missing Something?

答:
As you mentionned in your comment, "allocateByList" has, for example, the value "'M06','M81'".

So you are doing the following request:

```<code>select *
from A a
join B b ON a.allocateBy = b.empNo
join D d ON b.departmentName = d.departmentName
where a.allocateBy in ('''M06'',''M81''')
</code>```

You are looking for a value "a" having an "allocateBy" value at " 'M06','M81' ".

I believe you want one which have either the value "M06" or the value "M81".

So you have to do the following modifications:

1) Modify the type of allocateByList from String to List<String>

2) Format the searched value correctly: you have to split on , and then remove the ' wrapping your values.

So:

```<code>String allocateByListInitial = "'M06','M81'";

String[] allocateByListSplitted = allocateByListInitial.split(",");

// allocateByListSplitted = ["'M06'", "'M81'"] (with single quote wrapping each value)

List<String> allocateByList = Arrays.stream(allocateByListSplitted)
                                    .map(str -> str.substring(1, str.length() - 1)) // Remove first and last character of the string
                                    .collect(Collectors.toList());

// allocateByList = ["M06", "M81"] (without the single quote)

List<PointAllocation> pointAllocations = myRepo.findAllByAllocateByIn(allocateByList);
</code>```

Body:
This is my query, I have written in Repository file.

@Query(value = "select * from A a join B b ON a.allocateBy = b.empNo join D d ON b.departmentName = d.departmentName where a.allocateBy in (:allocateByList)",  nativeQuery = true)

ArrayList findAllByAllocateByIn(@Param("allocateByList") String allocateByList);

There are no errors but :allocateByList is not getting data. I have printed the value of allocateByList just before. It has data.

Am I missing Something?

Body:
As you mentionned in your comment, "allocateByList" has, for example, the value "'M06','M81'".

So you are doing the following request:

select *
from A a
join B b ON a.allocateBy = b.empNo
join D d ON b.departmentName = d.departmentName
where a.allocateBy in ('''M06'',''M81''')

You are looking for a value "a" having an "allocateBy" value at " 'M06','M81' ".

I believe you want one which have either the value "M06" or the value "M81".

So you have to do the following modifications:

1) Modify the type of allocateByList from String to List<String>

2) Format the searched value correctly: you have to split on , and then remove the ' wrapping your values.

So:

String allocateByListInitial = "'M06','M81'";

String[] allocateByListSplitted = allocateByListInitial.split(",");

// allocateByListSplitted = ["'M06'", "'M81'"] (with single quote wrapping each value)

List<String> allocateByList = Arrays.stream(allocateByListSplitted)
                                    .map(str -> str.substring(1, str.length() - 1)) // Remove first and last character of the string
                                    .collect(Collectors.toList());

// allocateByList = ["M06", "M81"] (without the single quote)

List<PointAllocation> pointAllocations = myRepo.findAllByAllocateByIn(allocateByList);


问:
jQuery bind click
I have the following situation:

In a html page i have a dynamically generated button, similar to:

```<code><div id='myButton'></div>
</code>```

This html page includes a script (e.g., A.js), that handles most of the functionality of the site, and in this script the button is being bound to an handler:

```<code>$("#myButton").bind("click", function(){
foo();
});
</code>```

So far its simple. Now, only in a particular situation, i need the same button to execute a second function. This has to be done through another script, dynamically generated and injected inside the html site. So the html will look similar to this:

```<code><script type=text/javascript src=A.js></script>
<script type=text/javascript>
//Dynamically generated script
</script>
</code>```

I do not want to override the previous function, i still need that to be executed, but also i need this function to be executed before the first one. And the way scripts are included on the site cannot be changed.

So, I have written the following (inside the second script tag):

```<code>    $("#myButton").bind("click",
     function(){
          bar(); // I still want foo() to be executed but after this is executed first.
});
</code>```

Is it possible to do something like this? Note that i do not have control on how scripts  are included on my site. Altering that order is not possible.

答:
You can still have more bindings to the same event

http://jsbin.com/iyewu5/edit

they will be fired sorted by what was the first in the code

so you can have:

```<code>$("#myButton").bind("click", function() { foo(); });
</code>```

and in other script

```<code>$("#myButton").bind("click", function() { bar(); });
</code>```

this will act as

```<code>$("#myButton").bind("click", function() { foo(); bar(); });
</code>```

as long as you place them under $(document).ready( function() {});

Title: jQuery bind click

Body:
I have the following situation:

In a html page i have a dynamically generated button, similar to:

This html page includes a script (e.g., A.js), that handles most of the functionality of the site, and in this script the button is being bound to an handler:

$("#myButton").bind("click", function(){
foo();
});

So far its simple. Now, only in a particular situation, i need the same button to execute a second function. This has to be done through another script, dynamically generated and injected inside the html site. So the html will look similar to this:

I do not want to override the previous function, i still need that to be executed, but also i need this function to be executed before the first one. And the way scripts are included on the site cannot be changed.

So, I have written the following (inside the second script tag):

    $("#myButton").bind("click",
     function(){
          bar(); // I still want foo() to be executed but after this is executed first.
});

Is it possible to do something like this? Note that i do not have control on how scripts  are included on my site. Altering that order is not possible.

Body:
You can still have more bindings to the same event

http://jsbin.com/iyewu5/edit

they will be fired sorted by what was the first in the code

so you can have:

$("#myButton").bind("click", function() { foo(); });

and in other script

$("#myButton").bind("click", function() { bar(); });

this will act as

$("#myButton").bind("click", function() { foo(); bar(); });

as long as you place them under $(document).ready( function() {});


问:
Query related to stemming in NLP
I am working on hands-on task based on stemming under NLP using python.

Below is the task which would required to be executed step wise to fetch the result.

I have completed till step 13 and got stuck at step number 14 and 15 (see below).

Please help me to know how to perform the step number 14 and 15.

TASK

Import the text corpus brown.

Extract the list of words associated with text collections belonging to the humor genre. Store the result in the variable humor_words.

Convert each word of the list humor_words into lower case, and store the result in lc_humor_words.

Find the list of unique words present in lc_humor_words. Store the result in lc_humor_uniq_words.

Import the corpus words.

Extract the list of words associated with the corpus words. Store the result in the variable wordlist_words.

Find the list of unique words present in wordlist_words. Store the result in wordlist_uniq_words.

Create an instance of PorterStemmer named, porter.

Create an instance of LancasterStemmer named, lancaster.

Stem each word present in lc_humor_uniq_words with porter instance, and store the result in the list p_stemmed

Stem each word present in lc_humor_uniq_words with lancaster instance, and store the result in the listl_stemmed`

Filter the stemmed words from p_stemmed which are also present in wordlist_uniq_words. Store the result in p_stemmed_in_wordlist.

Filter the stemmed words from l_stemmed which are also present in wordlist_uniq_words. Store the result in l_stemmed_in_wordlist.

Filter the words from lc_humor_uniq_words which have the same length as its corresponding stemmed word present in p_stemmed, and also contains at least one different character from the corresponding stemmed word. Store the result in the list p_stemmed_diff.

Filter the words from lc_humor_uniq_words which have the same length as its corresponding stemmed word, present in l_stemmed, and also contains at least one different character from the corresponding stemmed word. Store the result in list l_stemmed_diff.

Print the number of words present in p_stemmed_diff.

Print the number of words present in l_stemmed_diff.

-Below is the which I have completed till step 13.

```<code>import nltk

import nltk.corpus

from nltk.corpus import brown

humor_words = brown.words(categories = 'humor')

lc_humor_words = [w.lower() for w in humor_words]

lc_humor_uniq_words = set(lc_humor_words)

from nltk.corpus import words

wordlist_words = words.words()

wordlist_uniq_words = set(wordlist_words)

from nltk.stem import PorterStemmer

porter = PorterStemmer()

from nltk.stem import LancasterStemmer

lancaster = LancasterStemmer()

p_stemmed = []

for word in lc_humor_uniq_words:

    p_stemmed.append(porter.stem(word))

l_stemmed = []

for wordd in lc_humor_uniq_words:

    l_stemmed.append(lancaster.stem(wordd))

p_stemmed_in_wordlist = [word1 for word1 in p_stemmed if word1 in wordlist_uniq_words]

l_stemmed_in_wordlist = [word2 for word2 in l_stemmed if word2 in wordlist_uniq_words]
</code>```

答:
```<code>p_stemmed_diff=[w1 for w1,w2 in zip(lc_humor_uniq_words,p_stemmed) if len(w1) == len(w2) and w1 != w2]

l_stemmed_diff=[w1 for w1,w2 in zip(lc_humor_uniq_words,l_stemmed) if len(w1) == len(w2) and w1 != w2]
</code>```

These One-liners can help in solving Steps 14-17, check this too.

Title: Query related to stemming in NLP

Body:
I am working on hands-on task based on stemming under NLP using python.

Below is the task which would required to be executed step wise to fetch the result.

I have completed till step 13 and got stuck at step number 14 and 15 (see below).

Please help me to know how to perform the step number 14 and 15.

TASK

Import the text corpus brown.

Extract the list of words associated with text collections belonging to the humor genre. Store the result in the variable humor_words.

Convert each word of the list humor_words into lower case, and store the result in lc_humor_words.

Find the list of unique words present in lc_humor_words. Store the result in lc_humor_uniq_words.

Import the corpus words.

Extract the list of words associated with the corpus words. Store the result in the variable wordlist_words.

Find the list of unique words present in wordlist_words. Store the result in wordlist_uniq_words.

Create an instance of PorterStemmer named, porter.

Create an instance of LancasterStemmer named, lancaster.

Stem each word present in lc_humor_uniq_words with porter instance, and store the result in the list p_stemmed

Stem each word present in lc_humor_uniq_words with lancaster instance, and store the result in the listl_stemmed`

Filter the stemmed words from p_stemmed which are also present in wordlist_uniq_words. Store the result in p_stemmed_in_wordlist.

Filter the stemmed words from l_stemmed which are also present in wordlist_uniq_words. Store the result in l_stemmed_in_wordlist.

Filter the words from lc_humor_uniq_words which have the same length as its corresponding stemmed word present in p_stemmed, and also contains at least one different character from the corresponding stemmed word. Store the result in the list p_stemmed_diff.

Filter the words from lc_humor_uniq_words which have the same length as its corresponding stemmed word, present in l_stemmed, and also contains at least one different character from the corresponding stemmed word. Store the result in list l_stemmed_diff.

Print the number of words present in p_stemmed_diff.

Print the number of words present in l_stemmed_diff.

-Below is the which I have completed till step 13.

import nltk

import nltk.corpus

from nltk.corpus import brown

humor_words = brown.words(categories = 'humor')

lc_humor_words = [w.lower() for w in humor_words]

lc_humor_uniq_words = set(lc_humor_words)

from nltk.corpus import words

wordlist_words = words.words()

wordlist_uniq_words = set(wordlist_words)

from nltk.stem import PorterStemmer

porter = PorterStemmer()

from nltk.stem import LancasterStemmer

lancaster = LancasterStemmer()

p_stemmed = []

for word in lc_humor_uniq_words:

    p_stemmed.append(porter.stem(word))

l_stemmed = []

for wordd in lc_humor_uniq_words:

    l_stemmed.append(lancaster.stem(wordd))

p_stemmed_in_wordlist = [word1 for word1 in p_stemmed if word1 in wordlist_uniq_words]

l_stemmed_in_wordlist = [word2 for word2 in l_stemmed if word2 in wordlist_uniq_words]

Body:
p_stemmed_diff=[w1 for w1,w2 in zip(lc_humor_uniq_words,p_stemmed) if len(w1) == len(w2) and w1 != w2]

l_stemmed_diff=[w1 for w1,w2 in zip(lc_humor_uniq_words,l_stemmed) if len(w1) == len(w2) and w1 != w2]

These One-liners can help in solving Steps 14-17, check this too.


问:
How to bind to constant in JavaFX?
How to bind to constant in JavaFX?

I found a way like

```<code>myObject.myIntegerProperty().bind(new IntegerBinding() {
   @Override
   protected int computeValue() {
      return 2;
   }
});
</code>```

but it looks too excessive.

Is there any shorted way?

答:
Another alternative could be

```<code>Bindings.createIntegerBinding(() -> 2)
</code>```

This creates an IntegerBinding which evaluates to 2 as soon as needed.

It doesn't invalidate at all (as there are no dependencies given), so it remains at this value forever.

Title: How to bind to constant in JavaFX?

Body:
How to bind to constant in JavaFX?

I found a way like

myObject.myIntegerProperty().bind(new IntegerBinding() {
   @Override
   protected int computeValue() {
      return 2;
   }
});

but it looks too excessive.

Is there any shorted way?

Body:
Another alternative could be

Bindings.createIntegerBinding(() -> 2)

This creates an IntegerBinding which evaluates to 2 as soon as needed.

It doesn't invalidate at all (as there are no dependencies given), so it remains at this value forever.


答:
You can't.

It isn't possible (and simply doesn't make sense) to simultaneously say both:

Here is the thing you asked for

The thing you asked for is not here, you need to request this URL instead

(This sounds like an XY Problem; you might want to ask a new question about the problem you are trying to solve by asking how to do this impossible thing).

Title: res.redirect after res.json in node.js

Body:
I have the following code below
I want to redirect and return the response as well, can someone help me in this?
What is the better solution for this?

try {
  res.json(await example.preview(access_token, context, id, body))
  res.redirect(`${sso.host}/session/login?grant_type=bearer&access_token=${access_token}&remember_me=true&redirect_uri=${encodeURIComponent(
 'https://example.com'
 )}`);
} catch (e) {
  logger.info(e);
  next(e);
}


问:
Azure "Deployment successful" but app URL yields ":( Application Error" ... Docker ... container start failures
I am developing an Angular app with vscode on windows 10. It runs well locally.

I have tried to deploy it to Azure.

The vscode OUTPUT console says:

```<code>8:54:39 AM XXXXXXYY: Deployment successful.
8:54:36 AM: Deployment to "XXXXXXYY" completed.
</code>```

Browsing to the app URL yields :( Application Error

The Azure Application Logs say:

```<code>...
2020-02-17T18:02:12.322797181Z A P P   S E R V I C E   O N   L I N U X
2020-02-17T18:02:12.322800881Z
2020-02-17T18:02:12.322804281Z Documentation: http://aka.ms/webapp-linux
2020-02-17T18:02:12.322807781Z NodeJS quickstart: https://aka.ms/node-qs
2020-02-17T18:02:12.322811381Z NodeJS Version : v12.13.0

...

2020-02-17T18:03:50.224589935Z ℹ ｢wdm｣: Compiled successfully.
Docker on instance: RD0004FFE4001B experienced container start failures.

</code>```

I didn't knowingly request a Docker container.

Does anyone have any ideas?

答:
From your description, you could run an Angular app on windows 10 well locally. So, it recommended to deploy it on Azure app service on Windows instead of Linux as the logged.

You could follow this blog: How to Deploy an Angular application to Azure Web Service to create a windows OS app service. For using VScode deployment, refer to this.

Hope it could help you.

Body:
I am developing an Angular app with vscode on windows 10. It runs well locally.

I have tried to deploy it to Azure.

The vscode OUTPUT console says:

8:54:39 AM XXXXXXYY: Deployment successful.
8:54:36 AM: Deployment to "XXXXXXYY" completed.

Browsing to the app URL yields :( Application Error

The Azure Application Logs say:

...
2020-02-17T18:02:12.322797181Z A P P   S E R V I C E   O N   L I N U X
2020-02-17T18:02:12.322800881Z
2020-02-17T18:02:12.322804281Z Documentation: http://aka.ms/webapp-linux
2020-02-17T18:02:12.322807781Z NodeJS quickstart: https://aka.ms/node-qs
2020-02-17T18:02:12.322811381Z NodeJS Version : v12.13.0

...

2020-02-17T18:03:50.224589935Z ℹ ｢wdm｣: Compiled successfully.
Docker on instance: RD0004FFE4001B experienced container start failures.

I didn't knowingly request a Docker container.

Does anyone have any ideas?


问:
Construction an Arc in Eyeshot
I am trying to construct the arcs applying Eyeshot 12.
I use the constructor: Arc(Plane, 2D center point, 2D start point, 2D end point).
I have two arcs. The end point of one of them is exactly the same as the start point of the another one. In spite of that, Eyeshot constructs the arcs with significant gap between these points. Is this a bug , or I am doing somethying wrong?

The parameters of my arcs are as follows:
Arc1: 2D center point = (-0.655572, 0.160451),
      2D start point = (-0.008477,  0.049511),
      2D end point = (0.000385, 0.1271105).
Arc2: 2D center point = (-1.789206, 0.218072),
      2D start point = (0.000385, 0.1271105),
      2D end point = (0.002240, 0.177704).

答:
The radius of each arc is defined as the distance between the center and the startpoint. So if you pass an endpoint that has a different distance from the center, the arc will not pass through the endpoint.
In both of your arcs, these distances are different, and that's why you get the gap:

C1-Sta1 = 0.65653607869255759

C1-End1 = 0.65680375668022029

C2-Sta2 = 1.7919012087063424

C2-End2 = 1.7919007635301683

So if you want the first arc to end at the point in common with the second arc, you need to treat that point as a start, and then revert the arc's orientation:

```<code>            Plane pl = Plane.XY;

            Point2D c1 = new Point2D(-0.655572, 0.160451);
            Point2D c2 = new Point2D(-1.789206, 0.218072);

            Point2D s1 = new Point2D(-0.008477, 0.049511);
            Point2D s2 = new Point2D(0.000385, 0.1271105);

            Point2D e1 = new Point2D(0.000385, 0.1271105);
            Point2D e2 = new Point2D(0.002240, 0.177704);

            Plane plInv = new Plane(pl.Origin, pl.AxisY, pl.AxisX);
            Arc a1 = new Arc(plInv,plInv.Project(pl.PointAt(c1)), plInv.Project(pl.PointAt(e1)), plInv.Project(pl.PointAt(s1)));
            a1.Reverse();

            Arc a2 = new Arc(pl,c2,s2,e2);
</code>```

Title: Construction an Arc in Eyeshot

Body:
The radius of each arc is defined as the distance between the center and the startpoint. So if you pass an endpoint that has a different distance from the center, the arc will not pass through the endpoint.
In both of your arcs, these distances are different, and that's why you get the gap:

C1-Sta1 = 0.65653607869255759

C1-End1 = 0.65680375668022029

C2-Sta2 = 1.7919012087063424

C2-End2 = 1.7919007635301683

So if you want the first arc to end at the point in common with the second arc, you need to treat that point as a start, and then revert the arc's orientation:

            Plane pl = Plane.XY;

            Point2D c1 = new Point2D(-0.655572, 0.160451);
            Point2D c2 = new Point2D(-1.789206, 0.218072);

            Point2D s1 = new Point2D(-0.008477, 0.049511);
            Point2D s2 = new Point2D(0.000385, 0.1271105);

            Point2D e1 = new Point2D(0.000385, 0.1271105);
            Point2D e2 = new Point2D(0.002240, 0.177704);

            Plane plInv = new Plane(pl.Origin, pl.AxisY, pl.AxisX);
            Arc a1 = new Arc(plInv,plInv.Project(pl.PointAt(c1)), plInv.Project(pl.PointAt(e1)), plInv.Project(pl.PointAt(s1)));
            a1.Reverse();

            Arc a2 = new Arc(pl,c2,s2,e2);


问:
tapestry chenillekit chart : problem to defined trackFormatter function
I need help to display chart in tapestry pages. I'm using tapestry 5.2.4 and chenillekit 1.3.0.
My problem is that I want to defined a custom javascript function to display date in the mouse track. The option for Flotr is trackFormatter : function(obj){...}.
In my case, I send option for the graph with JSON.
When the function is called, i have error like this:

"n.mouse.trackFormatter is not a function" for firefox,

"Uncaught TypeError: Property 'trackFormatter' of object # is not a function" for chrome.

Does someone have the same problem and/or have find a solution to delcare custom javascript function like trackFormatter? thanks!

My code:

```<code>...
import org.apache.tapestry5.json.JSONLiteral;
import org.apache.tapestry5.json.JSONObject;
...

@Import(library = { "mymouseeventhandler.js" })
public class LineChart extends Chart {

private static final Logger logger = LoggerFactory.getLogger(LineChart.class);

/**
 * Map <Label , List of data> .
 */
@Parameter(required = true, defaultPrefix = BindingConstants.PROP)
private Map<String, List<XYDataItem>> counterDataWithLabel;

/**
 * Map <Label , List of data> .
 */
@Parameter(required = false, defaultPrefix = BindingConstants.PROP)
private Map<String, List<XYDataItem>> thresholdDataWithLabel;

@Parameter
private Date startTime;

@Parameter
private String graphCaption;

/**
 * Configure Flotr Graph
 *
 * <p>
 * <a href="http
 * ://www.chenillekit.org/chenillekit-tapestry/ref/org/chenillekit/tapestry/core/components
 * /Chart.html">ChenilleKit Reference </a>
 * </p>
 * <p>
 * <a href="http://solutoire.com/flotr/docs/options/">Flotr Options </a>
 * </p>
 *
 */
protected void configure(JSONObject config) {
    // TODO add attributes to LineChart, for being able to parameterize the graph.
    // counterDataWithLabel;
    StringBuilder dataString = new StringBuilder("[");
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(getStartTime());
    int startMillisecond = calendar.get(Calendar.MILLISECOND);

    int i = 0;
    for (Map.Entry<String, List<XYDataItem>> entry : counterDataWithLabel.entrySet()) {
        String label = entry.getKey();
        List<XYDataItem> dataItems = entry.getValue();
        dataString.append(String.format("{data: %s, label: '%s' , lines:{lineWidth: 1}}",
                Arrays.toString(dataItems.toArray()), label));
        dataString.append(",");
        i++;
    }
    if (!org.apache.commons.collections.MapUtils.isEmpty(thresholdDataWithLabel)) {
        int j = 0;
        for (Map.Entry<String, List<XYDataItem>> entry : thresholdDataWithLabel.entrySet()) {
            String label = entry.getKey();
            List<XYDataItem> dataItems = entry.getValue();
            dataString.append(String.format(
                    "{data: %s, label: '%s' , points: {show: false} , lines:{lineWidth: 3 }}",
                    Arrays.toString(dataItems.toArray()), label));
            if (j < thresholdDataWithLabel.size() - 1) {
                dataString.append(",");
            }
            j++;
        }
    }

    dataString.append("]");
    config.put("data", new JSONArray(dataString.toString()));

    JSONObject options = new JSONObject();

    options = flotrChart.getOptions();
    options.put("HtmlText", false);
    JSONObject mouse = new JSONObject();
    mouse.put("track", true);
    mouse.put("trackFormatter", new JSONLiteral("dateFormatter(obj)").toString());
    options.put("mouse", mouse);

    config.put("options", options);

    logger.debug("## config : " + config.toString());

}

/**
 * @return the startTime
 */
public Date getStartTime() {
    return startTime;
}

/**
 * @param startTime
 *            the startTime to set
 */
public void setStartTime(Date startTime) {
    this.startTime = startTime;
}
}
</code>```

mymouseeventhandler.js:

```<code>function dateTracker(obj){
    var dateToDisplay = new Date(parseInt(obj.x));
    var fullYear = dateToDisplay.getFullYear();
    var month = dateToDisplay.getMonth();
    var date = dateToDisplay.getDate();
    return '('+fullYear+'-'+month+'-'+date+' , '+obj.y+')';
}
</code>```

答:
The function is not well recognized because of double quote "" added when creating JSONObject. Here is a solution to avoid double quote :

```<code>...
mouse.put("trackFormatter", new JSONLiteral(
("\"function(obj){ return dateTracker(obj) }\"").replace("\"", "")));
...
</code>```

I hope it will help someone else :)

Body:
I need help to display chart in tapestry pages. I'm using tapestry 5.2.4 and chenillekit 1.3.0.
My problem is that I want to defined a custom javascript function to display date in the mouse track. The option for Flotr is trackFormatter : function(obj){...}.
In my case, I send option for the graph with JSON.
When the function is called, i have error like this:

"n.mouse.trackFormatter is not a function" for firefox,

"Uncaught TypeError: Property 'trackFormatter' of object # is not a function" for chrome.

Does someone have the same problem and/or have find a solution to delcare custom javascript function like trackFormatter? thanks!

My code:

...
import org.apache.tapestry5.json.JSONLiteral;
import org.apache.tapestry5.json.JSONObject;
...

@Import(library = { "mymouseeventhandler.js" })
public class LineChart extends Chart {

private static final Logger logger = LoggerFactory.getLogger(LineChart.class);

/**
 * Map  .
 */
@Parameter(required = true, defaultPrefix = BindingConstants.PROP)
private Map<String, List<XYDataItem>> counterDataWithLabel;

/**
 * Map  .
 */
@Parameter(required = false, defaultPrefix = BindingConstants.PROP)
private Map<String, List<XYDataItem>> thresholdDataWithLabel;

@Parameter
private Date startTime;

@Parameter
private String graphCaption;

/**
 * Configure Flotr Graph
 *
 *

 * ChenilleKit Reference
 *

 *

 * Flotr Options
 *

 *
 */
protected void configure(JSONObject config) {
    // TODO add attributes to LineChart, for being able to parameterize the graph.
    // counterDataWithLabel;
    StringBuilder dataString = new StringBuilder("[");
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(getStartTime());
    int startMillisecond = calendar.get(Calendar.MILLISECOND);

    int i = 0;
    for (Map.Entry<String, List<XYDataItem>> entry : counterDataWithLabel.entrySet()) {
        String label = entry.getKey();
        List<XYDataItem> dataItems = entry.getValue();
        dataString.append(String.format("{data: %s, label: '%s' , lines:{lineWidth: 1}}",
                Arrays.toString(dataItems.toArray()), label));
        dataString.append(",");
        i++;
    }
    if (!org.apache.commons.collections.MapUtils.isEmpty(thresholdDataWithLabel)) {
        int j = 0;
        for (Map.Entry<String, List<XYDataItem>> entry : thresholdDataWithLabel.entrySet()) {
            String label = entry.getKey();
            List<XYDataItem> dataItems = entry.getValue();
            dataString.append(String.format(
                    "{data: %s, label: '%s' , points: {show: false} , lines:{lineWidth: 3 }}",
                    Arrays.toString(dataItems.toArray()), label));
            if (j < thresholdDataWithLabel.size() - 1) {
                dataString.append(",");
            }
            j++;
        }
    }

    dataString.append("]");
    config.put("data", new JSONArray(dataString.toString()));

    JSONObject options = new JSONObject();

    options = flotrChart.getOptions();
    options.put("HtmlText", false);
    JSONObject mouse = new JSONObject();
    mouse.put("track", true);
    mouse.put("trackFormatter", new JSONLiteral("dateFormatter(obj)").toString());
    options.put("mouse", mouse);

    config.put("options", options);

    logger.debug("## config : " + config.toString());

}

/**
 * @return the startTime
 */
public Date getStartTime() {
    return startTime;
}

/**
 * @param startTime
 *            the startTime to set
 */
public void setStartTime(Date startTime) {
    this.startTime = startTime;
}
}

mymouseeventhandler.js:

function dateTracker(obj){
    var dateToDisplay = new Date(parseInt(obj.x));
    var fullYear = dateToDisplay.getFullYear();
    var month = dateToDisplay.getMonth();
    var date = dateToDisplay.getDate();
    return '('+fullYear+'-'+month+'-'+date+' , '+obj.y+')';
}

Body:
The function is not well recognized because of double quote "" added when creating JSONObject. Here is a solution to avoid double quote :

...
mouse.put("trackFormatter", new JSONLiteral(
("\"function(obj){ return dateTracker(obj) }\"").replace("\"", "")));
...

I hope it will help someone else :)


问:
Concatenate list of lists in one string - Python 3
I have a list of lists with int and string like this:

l = [[1, "two", 3],["four", 5, "six"]].

I need to generate one string, startig a new line for each list, separeted by a semicolon. Like this:

```<code>"1, two, 3;
 four, 5, six;"
</code>```

How can I do this?

答:
```<code>print ";\n".join([", ".join([str(i) for i in s]) for s in l])
</code>```

Body:
I have a list of lists with int and string like this:

l = [[1, "two", 3],["four", 5, "six"]].

I need to generate one string, startig a new line for each list, separeted by a semicolon. Like this:

"1, two, 3;
 four, 5, six;"

How can I do this?


问:
Retrieve only date from datetime
I  am using a derived column with ssis with this condition :

```<code>UpdatedDate == (DT_DATE)"9999-12-31" ? (DT_DATE)CreatedDate : (DT_DATE)UpdatedDate
</code>```

This is my actual output, I'm storing the result in BI_StartDate :

```<code>EmployeeId createdDate updatedDate BI_StartDate
54         2013-07-10  9999-12-31  2013-07-10 00:00:00.0000000
245        2016-06-29  2016-07-03  2016-07-03 00:00:00.0000000
</code>```

I want to get only the date:

```<code>EmployeeId createdDate updatedDate BI_StartDate
54         2013-07-10  9999-12-31  2013-07-10
245        2016-06-29  2016-07-03  2016-07-03
</code>```

答:
You only need to cast / convert it to date data type by using:

```<code>CAST(BI_StartDate AS DATE)
</code>```

or :

```<code>CONVERT(DATE, BI_StartDate)
</code>```

Title: Retrieve only date from datetime

Body:
I  am using a derived column with ssis with this condition :

UpdatedDate == (DT_DATE)"9999-12-31" ? (DT_DATE)CreatedDate : (DT_DATE)UpdatedDate

This is my actual output, I'm storing the result in BI_StartDate :

EmployeeId createdDate updatedDate BI_StartDate
54         2013-07-10  9999-12-31  2013-07-10 00:00:00.0000000
245        2016-06-29  2016-07-03  2016-07-03 00:00:00.0000000

I want to get only the date:

EmployeeId createdDate updatedDate BI_StartDate
54         2013-07-10  9999-12-31  2013-07-10
245        2016-06-29  2016-07-03  2016-07-03

Body:
You only need to cast / convert it to date data type by using:

CAST(BI_StartDate AS DATE)

or :

CONVERT(DATE, BI_StartDate)


问:
How to create directory and file inside the same directory in ansible using single task
Is there any way to create directory and file inside the same directory in ansible using a single task? Currently, in my task, I'm creating a directory using a file module, state= directory. How to touch a file inside that directory in the same task?</p>

答:
You could use a loop:</p>

```<code>- name: Create a directory with a file inside
  file:
    path: "{{ item.path }}"
    state: "{{ item.state }}"
  loop:
    - { path: /tmp/foo, state: directory }
    - { path: /tmp/foo/bar.txt, state: touch }
</code>```

Body:
You could use a loop:

- name: Create a directory with a file inside
  file:
    path: "{{ item.path }}"
    state: "{{ item.state }}"
  loop:
    - { path: /tmp/foo, state: directory }
    - { path: /tmp/foo/bar.txt, state: touch }


问:
Kotlin Nullable JNI Type
How to work with Kotlin nullable type like 'Long?', 'String?' etc. on JNI?
JNI type signatures represent the following information:

```<code>Signature  |Java Type
-----------|----------------
    Z      | boolean
    B      | byte
    C      | char
    S      | short
    I      | int
    J      | long
    F      | float
    D      | double
    L      | fully-qualified-class;
    [ type | type[]
    (arg-types)| ret-type method type
</code>```

But how I can use nullable 'var value:Long?' from JNI?

Kotlin Code

```<code>class KtClass
{
    var value:Long? = null
}
</code>```

JNI

```<code>jclass ktclass = env->FindClass("package/KtClass");
jmethodID ctorktID = env->GetMethodID(ktclass, "<init>", "()V");
env->NewObject(ktclass, ctorktID);

//J - mean Kotlin Long, but it not nullable 'Long?'
jfieldID valueID = env->GetFieldID(ktclass, "value", "J");
env->SetLongField(ktclass, valueID, NULL); //Error
</code>```

答:
Long? becomes java.lang.Long on JVM, so use

```<code>env->GetFieldID(ktclass, "value", "Ljava/lang/Long;")
</code>```

Title: Kotlin Nullable JNI Type

Body:
How to work with Kotlin nullable type like 'Long?', 'String?' etc. on JNI?
JNI type signatures represent the following information:

Signature  |Java Type
-----------|----------------
    Z      | boolean
    B      | byte
    C      | char
    S      | short
    I      | int
    J      | long
    F      | float
    D      | double
    L      | fully-qualified-class;
    [ type | type[]
    (arg-types)| ret-type method type

But how I can use nullable 'var value:Long?' from JNI?

Kotlin Code

class KtClass
{
    var value:Long? = null
}

JNI

jclass ktclass = env->FindClass("package/KtClass");
jmethodID ctorktID = env->GetMethodID(ktclass, "<init>", "()V");
env->NewObject(ktclass, ctorktID);

//J - mean Kotlin Long, but it not nullable 'Long?'
jfieldID valueID = env->GetFieldID(ktclass, "value", "J");
env->SetLongField(ktclass, valueID, NULL); //Error

Body:
Long? becomes java.lang.Long on JVM, so use

env->GetFieldID(ktclass, "value", "Ljava/lang/Long;")