问:
Gradle doesn't run tests
In my Gradle project I have a very simple JUnit test:

```<code>import org.junit.jupiter.api.Test
import static org.junit.jupiter.api.Assertions.fail

class ApiCallerTest {

    @Test
    void testSetApiKey() {
        fail();
    }
}
</code>```

When I run the test in IntelliJ, I get a list of tasks with the message that the build was successful. Eg.:

```<code>Testing started at 19:52 ...
> Task :cleanTest UP-TO-DATE
> Task :compileJava UP-TO-DATE
> Task :compileGroovy NO-SOURCE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :compileTestJava NO-SOURCE
> Task :compileTestGroovy NO-SOURCE
> Task :processTestResources NO-SOURCE
> Task :testClasses UP-TO-DATE
> Task :test NO-SOURCE
BUILD SUCCESSFUL in 0s
</code>```

This should not happen since I am expecting the test to fail. I also get a message "Test events were not received".

This is my gradle.build file:

```<code>plugins {
    id 'groovy'
    id 'java'
}

group 'com.ipdive'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.3.11'
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.0')
}
</code>```

According to suggestions on the internet I tried adding this code to the gradle.build file.

```<code>test {
    useJUnitPlatform()
}
</code>```

But that didn't help.

I also tried changing the Gradle setting to "Run tests using" -> "IntelliJ IDEA". When I run the test after this change, I get an error message:

```<code>Internal Error occurred.
org.junit.platform.commons.JUnitException: TestEngine with ID 'junit-jupiter' failed to discover tests
    at org.junit.platform.launcher.core.DefaultLauncher.discoverEngineRoot(DefaultLauncher.java:189)
    at org.junit.platform.launcher.core.DefaultLauncher.discoverRoot(DefaultLauncher.java:168)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: org.junit.platform.commons.JUnitException: MethodSelector [className = 'ApiCallerTest', methodName = 'testSetApiKey', methodParameterTypes = ''] resolution failed
    at org.junit.platform.launcher.listeners.discovery.AbortOnFailureLauncherDiscoveryListener.selectorProcessed(AbortOnFailureLauncherDiscoveryListener.java:39)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolveCompletely(EngineDiscoveryRequestResolution.java:102)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.run(EngineDiscoveryRequestResolution.java:82)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolver.resolve(EngineDiscoveryRequestResolver.java:113)
    at org.junit.jupiter.engine.discovery.DiscoverySelectorResolver.resolveSelectors(DiscoverySelectorResolver.java:45)
    at org.junit.jupiter.engine.JupiterTestEngine.discover(JupiterTestEngine.java:69)
    at org.junit.platform.launcher.core.DefaultLauncher.discoverEngineRoot(DefaultLauncher.java:181)
    ... 6 more
Caused by: org.junit.platform.commons.PreconditionViolationException: Could not load class with name: ApiCallerTest
...
...
</code>```

Can you please tell me what to do so I can run my unit-tests with Gradle?

EDIT: Added screenshot of the project structure.

答:
The test file was (mistakenly) created as a Groovy file. You can tell by the missing semicolons at the end of the import statements or by the almost square file icon in the IntelliJ.

Therefore it should be in the /test/groovy folder. That's why it wasn't picking up the test file in the /test/java folder because there was no java file. Once moved to the correct folder, Gradle picked it up.

Later there was also a problem with the Groovy version. These two statements were clashing with each other:

```<code>compile 'org.codehaus.groovy:groovy-all:2.3.11'
implementation(localGroovy())
</code>```

Only one of them should be used.

Title: Gradle doesn't run tests

Body:
In my Gradle project I have a very simple JUnit test:

import org.junit.jupiter.api.Test
import static org.junit.jupiter.api.Assertions.fail

class ApiCallerTest {

    @Test
    void testSetApiKey() {
        fail();
    }
}

When I run the test in IntelliJ, I get a list of tasks with the message that the build was successful. Eg.:

Testing started at 19:52 ...
> Task :cleanTest UP-TO-DATE
> Task :compileJava UP-TO-DATE
> Task :compileGroovy NO-SOURCE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :compileTestJava NO-SOURCE
> Task :compileTestGroovy NO-SOURCE
> Task :processTestResources NO-SOURCE
> Task :testClasses UP-TO-DATE
> Task :test NO-SOURCE
BUILD SUCCESSFUL in 0s

This should not happen since I am expecting the test to fail. I also get a message "Test events were not received".

This is my gradle.build file:

plugins {
    id 'groovy'
    id 'java'
}

group 'com.ipdive'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.3.11'
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.0')
}

According to suggestions on the internet I tried adding this code to the gradle.build file.

test {
    useJUnitPlatform()
}

But that didn't help.

I also tried changing the Gradle setting to "Run tests using" -> "IntelliJ IDEA". When I run the test after this change, I get an error message:

Internal Error occurred.
org.junit.platform.commons.JUnitException: TestEngine with ID 'junit-jupiter' failed to discover tests
    at org.junit.platform.launcher.core.DefaultLauncher.discoverEngineRoot(DefaultLauncher.java:189)
    at org.junit.platform.launcher.core.DefaultLauncher.discoverRoot(DefaultLauncher.java:168)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: org.junit.platform.commons.JUnitException: MethodSelector [className = 'ApiCallerTest', methodName = 'testSetApiKey', methodParameterTypes = ''] resolution failed
    at org.junit.platform.launcher.listeners.discovery.AbortOnFailureLauncherDiscoveryListener.selectorProcessed(AbortOnFailureLauncherDiscoveryListener.java:39)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolveCompletely(EngineDiscoveryRequestResolution.java:102)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.run(EngineDiscoveryRequestResolution.java:82)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolver.resolve(EngineDiscoveryRequestResolver.java:113)
    at org.junit.jupiter.engine.discovery.DiscoverySelectorResolver.resolveSelectors(DiscoverySelectorResolver.java:45)
    at org.junit.jupiter.engine.JupiterTestEngine.discover(JupiterTestEngine.java:69)
    at org.junit.platform.launcher.core.DefaultLauncher.discoverEngineRoot(DefaultLauncher.java:181)
    ... 6 more
Caused by: org.junit.platform.commons.PreconditionViolationException: Could not load class with name: ApiCallerTest
...
...

Can you please tell me what to do so I can run my unit-tests with Gradle?

EDIT: Added screenshot of the project structure.

Body:
The test file was (mistakenly) created as a Groovy file. You can tell by the missing semicolons at the end of the import statements or by the almost square file icon in the IntelliJ.

Therefore it should be in the /test/groovy folder. That's why it wasn't picking up the test file in the /test/java folder because there was no java file. Once moved to the correct folder, Gradle picked it up.

Later there was also a problem with the Groovy version. These two statements were clashing with each other:

compile 'org.codehaus.groovy:groovy-all:2.3.11'
implementation(localGroovy())

Only one of them should be used.


来源: stackexchange

问:
How to execute a loop with sequential summation?
I have an array with this loop:

var arr = [5, 4, 9, 6, 4];

var sum = 0;

arr.forEach(function(item) {
  sum += parseInt(item);
  console.log(sum)
});```
</div>
</div>
</p>

<p>At the moment, I get this result:</p>

```5
9
18
24
28
```

<p>But how to make sure that the result always starts with 0 and ends with the penultimate digit, i.e. it should look like this:</p>

```0
5
9
18
24
```

答:
You could add the value to a sum and make the sum usable in the next loop.

This solution uses a take first approach and changes a value later in the run.

```<code>[value, changePart][index]
</code>```

var array = [5, 4, 9, 6, 4],
    result = array.map((s => v => [s, s += v][0])(0));

console.log(...result);```

ContentLicense: CC BY-SA 4.0

Body:
I have an array with this loop:

var arr = [5, 4, 9, 6, 4];

var sum = 0;

arr.forEach(function(item) {
  sum += parseInt(item);
  console.log(sum)
});

At the moment, I get this result:

5
9
18
24
28

But how to make sure that the result always starts with 0 and ends with the penultimate digit, i.e. it should look like this:

0
5
9
18
24

Body:
You could add the value to a sum and make the sum usable in the next loop.

This solution uses a take first approach and changes a value later in the run.

[value, changePart][index]

var array = [5, 4, 9, 6, 4],
    result = array.map((s => v => [s, s += v][0])(0));

console.log(...result);


问:
Split one Row to Multiple Row Based on New line Character with Presto
I have a table in Presto:

I want:

I have used UNNEST function with split function but I am not able to split each line using '\n' or char(10)

```<code>SELECT Col1,split_Col2
FROM tbl
CROSS JOIN UNNEST(SPLIT(Col2,'\n')) AS t (split_Col2)
</code>```

does not work.

Even this:

```<code>SELECT Col1,split_Col2
FROM tbl
CROSS JOIN UNNEST(SPLIT(Col2,char(10))) AS t (split_Col2)
</code>```

does not work.

I am very new to Presto and it would be great if someone could help!

答:
you have to give the actual newline (enter button) instead of a escape sequence  '\n' or char(10)

use:

```<code>SELECT Col1,split_Col2  FROM tbl CROSS JOIN UNNEST(SPLIT(Col2,'
')) AS t (split_Col2)
</code>```

This works

Body:
I have a table in Presto:

I want:

I have used UNNEST function with split function but I am not able to split each line using '\n' or char(10)

SELECT Col1,split_Col2
FROM tbl
CROSS JOIN UNNEST(SPLIT(Col2,'\n')) AS t (split_Col2)

does not work.

Even this:

SELECT Col1,split_Col2
FROM tbl
CROSS JOIN UNNEST(SPLIT(Col2,char(10))) AS t (split_Col2)

does not work.

I am very new to Presto and it would be great if someone could help!

Body:
you have to give the actual newline (enter button) instead of a escape sequence  '\n' or char(10)

use:

SELECT Col1,split_Col2  FROM tbl CROSS JOIN UNNEST(SPLIT(Col2,'
')) AS t (split_Col2)

This works


问:
PL/SQL regex validation how to escape from '
I'm working on a fullName validation function, examples that can go are :

John Deep

JohnDeep

John-Deep

I want to use this regex:

```<code>^\p{L}+[\p{L}\p{Pd}\p{Zs}']*\p{L}+$|^\p{L}+$
</code>```

My validation function is :

```<code> create or replace FUNCTION is_valid_fullName (str IN VARCHAR2) RETURN VARCHAR2 AS
        bln BOOLEAN;
    begin
     if regexp_like(str, '^\p{L}+[\p{L}\p{Pd}\p{Zs}']*\p{L}+$|^\p{L}+$') then

            return 1;
      else
        return 0;
     end if;
     end;
</code>```

However I have a problem with syntax.

PLS-00103: Encountered the symbol "]" when ...

How can I solve this?

答:
To input a single quote in a string double it.

Your pattern is a bit redundant, you may get rid of the alternation using an optional group:

```<code>^\p{L}+([\p{L}\p{Pd}\p{Zs}']*\p{L}+)?$
       ^                           ^^
</code>```

However, you can't use Unicode property classes in an Oracle regex. What you may do is use POSIX [:alpha:] character class instead of the \p{L} to match any Unicode letter and spell out the \p{Pd} ([\u002D\u058A\u05BE\u1400\u1806\u2010\u2011\u2012\u2013\u2014\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]) and \p{Zs} ([\u0020\u3000\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2008\u2009\u200A\u205F\u00A0\u2007\u202F]) Unicode property classes. You may also consider using the POSIX [:space:] / [:blank:] character classes instead of \p{Zs} because \p{Zs} matches all horizontal whitespace BUT a tab char.

A converted pattern will look like

```<code>'^[[:alpha:]]+([-[:alpha:]' || unistr('\058A') || unistr('\05BE') || unistr('\1400') || unistr('\1806') || unistr('\2010') || unistr('\2011') || unistr('\2012') || unistr('\2013') || unistr('\2014') || unistr('\2015') || unistr('\2E17') || unistr('\2E1A') || unistr('\2E3A') || unistr('\2E3B') || unistr('\2E40') || unistr('\301C') || unistr('\3030') || unistr('\30A0') || unistr('\FE31') || unistr('\FE32') || unistr('\FE58') || unistr('\FE63') || unistr('\FF0D') || unistr('\0009') || unistr('\3000') || unistr('\1680') || unistr('\2000') || unistr('\2001') || unistr('\2002') || unistr('\2003') || unistr('\2004') || unistr('\2005') || unistr('\2006') || unistr('\2008') || unistr('\2009') || unistr('\200A') || unistr('\205F') || unistr('\00A0') || unistr('\2007') || unistr('\202F') || ' '']*[[:alpha:]]+)?$'
</code>```

Or, if you use [:blank:]:

```<code>'^[[:alpha:]]+([-[:alpha:][:blank:]' || unistr('\058A') || unistr('\05BE') || unistr('\1400') || unistr('\1806') || unistr('\2010') || unistr('\2011') || unistr('\2012') || unistr('\2013') || unistr('\2014') || unistr('\2015') || unistr('\2E17') || unistr('\2E1A') || unistr('\2E3A') || unistr('\2E3B') || unistr('\2E40') || unistr('\301C') || unistr('\3030') || unistr('\30A0') || unistr('\FE31') || unistr('\FE32') || unistr('\FE58') || unistr('\FE63') || unistr('\FF0D') || ' '']*[[:alpha:]]+)?$'
</code>```

See the regex demo (1 means there was a match).

Body:
I'm working on a fullName validation function, examples that can go are :

John Deep

JohnDeep

John-Deep

I want to use this regex:

^\p{L}+[\p{L}\p{Pd}\p{Zs}']*\p{L}+$|^\p{L}+$

My validation function is :

 create or replace FUNCTION is_valid_fullName (str IN VARCHAR2) RETURN VARCHAR2 AS
        bln BOOLEAN;
    begin
     if regexp_like(str, '^\p{L}+[\p{L}\p{Pd}\p{Zs}']*\p{L}+$|^\p{L}+$') then

            return 1;
      else
        return 0;
     end if;
     end;

However I have a problem with syntax.

PLS-00103: Encountered the symbol "]" when ...

How can I solve this?

Body:
To input a single quote in a string double it.

Your pattern is a bit redundant, you may get rid of the alternation using an optional group:

^\p{L}+([\p{L}\p{Pd}\p{Zs}']*\p{L}+)?$
       ^                           ^^

However, you can't use Unicode property classes in an Oracle regex. What you may do is use POSIX [:alpha:] character class instead of the \p{L} to match any Unicode letter and spell out the \p{Pd} ([\u002D\u058A\u05BE\u1400\u1806\u2010\u2011\u2012\u2013\u2014\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]) and \p{Zs} ([\u0020\u3000\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2008\u2009\u200A\u205F\u00A0\u2007\u202F]) Unicode property classes. You may also consider using the POSIX [:space:] / [:blank:] character classes instead of \p{Zs} because \p{Zs} matches all horizontal whitespace BUT a tab char.

A converted pattern will look like

'^[[:alpha:]]+([-[:alpha:]' || unistr('\058A') || unistr('\05BE') || unistr('\1400') || unistr('\1806') || unistr('\2010') || unistr('\2011') || unistr('\2012') || unistr('\2013') || unistr('\2014') || unistr('\2015') || unistr('\2E17') || unistr('\2E1A') || unistr('\2E3A') || unistr('\2E3B') || unistr('\2E40') || unistr('\301C') || unistr('\3030') || unistr('\30A0') || unistr('\FE31') || unistr('\FE32') || unistr('\FE58') || unistr('\FE63') || unistr('\FF0D') || unistr('\0009') || unistr('\3000') || unistr('\1680') || unistr('\2000') || unistr('\2001') || unistr('\2002') || unistr('\2003') || unistr('\2004') || unistr('\2005') || unistr('\2006') || unistr('\2008') || unistr('\2009') || unistr('\200A') || unistr('\205F') || unistr('\00A0') || unistr('\2007') || unistr('\202F') || ' '']*[[:alpha:]]+)?$'

Or, if you use [:blank:]:

'^[[:alpha:]]+([-[:alpha:][:blank:]' || unistr('\058A') || unistr('\05BE') || unistr('\1400') || unistr('\1806') || unistr('\2010') || unistr('\2011') || unistr('\2012') || unistr('\2013') || unistr('\2014') || unistr('\2015') || unistr('\2E17') || unistr('\2E1A') || unistr('\2E3A') || unistr('\2E3B') || unistr('\2E40') || unistr('\301C') || unistr('\3030') || unistr('\30A0') || unistr('\FE31') || unistr('\FE32') || unistr('\FE58') || unistr('\FE63') || unistr('\FF0D') || ' '']*[[:alpha:]]+)?$'

See the regex demo (1 means there was a match).


问:
android:textSize change in MotionLayout
I am going to animate text size change using MotionLayout.

I do the following for start state

```<code><CustomAttribute
    motion:attributeName="textSize"
    motion:customDimension="16sp" />
</code>```

And the following for end state

```<code><CustomAttribute
    motion:attributeName="textSize"
    motion:customDimension="14sp" />
</code>```

As a result, it looks like size is actually changing, but it's much larger than 14sp-16sp

So, how to change text size properly?

答:
Use "motion:customDimension" for change textSize. Below file is scene.xml

```<code>  <?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:motion="http://schemas.android.com/apk/res-auto">

    <Transition
        motion:constraintSetEnd="@+id/end"
        motion:constraintSetStart="@+id/start"
        motion:duration="2000">
        <OnSwipe
            motion:dragDirection="dragDown"
            motion:moveWhenScrollAtTop="true"
            motion:touchAnchorSide="bottom"
            motion:touchRegionId="@+id/ivExpand" />
    </Transition>

    <ConstraintSet android:id="@+id/start">

    <Constraint
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <CustomAttribute
                motion:attributeName="textSize"
                motion:customDimension="10sp" />

        </Constraint>

 </ConstraintSet>

    <ConstraintSet android:id="@+id/end">
 <Constraint
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <CustomAttribute
                motion:attributeName="textSize"
                motion:customDimension="5sp" />

        </Constraint>
    </ConstraintSet>
</code>```

Add scene.xml (scene description file) in mainActivity.xml

```<code><androidx.constraintlayout.motion.widget.MotionLayout xmlns:android="http://schemas.android.com/apk/res/android"
            <?xml version="1.0" encoding="utf-8"?>
    <MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:motion="http://schemas.android.com/apk/res-auto">

 <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/tvName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/black"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>
</<androidx.constraintlayout.motion.widget.MotionLayout>
</code>```

Title: android:textSize change in MotionLayout

Body:
I am going to animate text size change using MotionLayout.

I do the following for start state

<CustomAttribute
    motion:attributeName="textSize"
    motion:customDimension="16sp" />

And the following for end state

<CustomAttribute
    motion:attributeName="textSize"
    motion:customDimension="14sp" />

As a result, it looks like size is actually changing, but it's much larger than 14sp-16sp

So, how to change text size properly?

Body:
Use "motion:customDimension" for change textSize. Below file is scene.xml

  <?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:motion="http://schemas.android.com/apk/res-auto">

    <Transition
        motion:constraintSetEnd="@+id/end"
        motion:constraintSetStart="@+id/start"
        motion:duration="2000">
        <OnSwipe
            motion:dragDirection="dragDown"
            motion:moveWhenScrollAtTop="true"
            motion:touchAnchorSide="bottom"
            motion:touchRegionId="@+id/ivExpand" />
    </Transition>

    <ConstraintSet android:id="@+id/start">

    <Constraint
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <CustomAttribute
                motion:attributeName="textSize"
                motion:customDimension="10sp" />

        </Constraint>

 </ConstraintSet>

    <ConstraintSet android:id="@+id/end">
 <Constraint
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <CustomAttribute
                motion:attributeName="textSize"
                motion:customDimension="5sp" />

        </Constraint>
    </ConstraintSet>

Add scene.xml (scene description file) in mainActivity.xml

<androidx.constraintlayout.motion.widget.MotionLayout xmlns:android="http://schemas.android.com/apk/res/android"
            <?xml version="1.0" encoding="utf-8"?>
    <MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:motion="http://schemas.android.com/apk/res-auto">

 <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/tvName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/black"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>
</<androidx.constraintlayout.motion.widget.MotionLayout>


问:
jsGrid: How to pass additional variables from javascript to php using ajax
I'm using jsGrid for my project. View here for original source code

I want to pass an additional variable call $user_session to use for mysql select query in fetch.php but failed. Below is what i have been trying.

```<code><script>

var user_session = "<?php echo $user_session; ?>"; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

//......

 controller: {
  loadData: function(){
   return $.ajax({
    type: "GET",
    url: "fetch_data.php",
    data: {user_session:user_session} //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   });
  },

 //......
</code>```

Here's the fetch.php file

```<code><?php

if($method == 'GET')
{
 $user_session = $_GET['user_session']; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

 $query = "SELECT * FROM sample_data WHERE first_name=? ORDER BY id DESC";
 $statement = $connect->prepare($query);
 $statement->execute($user_session); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output[] = array(
   'id'    => $row['id'],
   'first_name'  => $row['first_name'],
   'last_name'   => $row['last_name'],
   'age'    => $row['age'],
   'gender'   => $row['gender']
  );
 }
 header("Content-Type: application/json");
 echo json_encode($output);
}
//......
?>
</code>```

What is the proper way to do this?

答:
First of all, anyone could open up a dev console inside a browser and start fuzzing your session id. While you are correctly preparing your query, defusing sql injection, it does does not protect you from an IDOR, or, i could  enumerate your users by just querying your application repeatedly.

If you really want to pass your session id client-side, maybe you could consider using a cookie, as it is less easily editable by a normal user.


问:
Laravel storage disk put gives internal server error 500 on live server | no logs are created
I am saving image files to disk. After that I create a ZIP and download it. Everything works fine on localhost.

On the live server I get:

```<code>Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at webmaster@example.com to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.
</code>```

The error occurs if I want to save an image to the storage:

```<code>$user = DB::connection('mysql_live')->table('users')->where('id', $userid)->first();
Storage::disk('gdpr')->put($user->picture, file_get_contents(env('AVATAR_PHOTO_SRC') . $user->picture));
</code>```

env('AVATAR_PHOTO_SRC') is the absoulte path to the image, example: https://example.com/uploads/thumb/

There is no log file created. And the size of the zip is less then 1MB, images are even smaller.

What is happening here?

EDIT

$user->picture is the name of the file. example: example.jpg.

The file does exist and can be opened for example in the browser. Remember everything works fine on localhost.

EDIT

I found a log in try, catch:

```<code>file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0
</code>```

EDIT

PHP ini cant be modified on a shared server. I will need an alternative way to store the image.

答:
Here is the curl solution, which worked for me:

```<code>$c = curl_init();
curl_setopt($c, CURLOPT_URL, env('AVATAR_PHOTO_SRC') . $user->picture);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_HEADER, 0);

curl_setopt($c, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($c, CURLOPT_CAINFO, Storage::disk('other')->path("cacert-2020-01-01.pem"));
$img = curl_exec($c);

$httpCode_post = curl_getinfo($c, CURLINFO_HTTP_CODE);
$cerror_post = curl_error($c);

curl_close($c);

Storage::disk('gdpr')->put($user->picture, $img);
</code>```

You can set CURLOPT_SSL_VERIFYPEER to false then you dont need the step with the certificate.

But I advise you to add the certificate. Its super easy. Just download it here and save it somewhere in your storage.

Body:
I am saving image files to disk. After that I create a ZIP and download it. Everything works fine on localhost.

On the live server I get:

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at webmaster@example.com to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.

The error occurs if I want to save an image to the storage:

$user = DB::connection('mysql_live')->table('users')->where('id', $userid)->first();
Storage::disk('gdpr')->put($user->picture, file_get_contents(env('AVATAR_PHOTO_SRC') . $user->picture));

env('AVATAR_PHOTO_SRC') is the absoulte path to the image, example: https://example.com/uploads/thumb/

There is no log file created. And the size of the zip is less then 1MB, images are even smaller.

What is happening here?

EDIT

$user->picture is the name of the file. example: example.jpg.

The file does exist and can be opened for example in the browser. Remember everything works fine on localhost.

EDIT

I found a log in try, catch:

file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0

EDIT

PHP ini cant be modified on a shared server. I will need an alternative way to store the image.

Body:
Here is the curl solution, which worked for me:

$c = curl_init();
curl_setopt($c, CURLOPT_URL, env('AVATAR_PHOTO_SRC') . $user->picture);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_HEADER, 0);

curl_setopt($c, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($c, CURLOPT_CAINFO, Storage::disk('other')->path("cacert-2020-01-01.pem"));
$img = curl_exec($c);

$httpCode_post = curl_getinfo($c, CURLINFO_HTTP_CODE);
$cerror_post = curl_error($c);

curl_close($c);

Storage::disk('gdpr')->put($user->picture, $img);

You can set CURLOPT_SSL_VERIFYPEER to false then you dont need the step with the certificate.

But I advise you to add the certificate. Its super easy. Just download it here and save it somewhere in your storage.


问:
Windows 10 GitKraken And Github - failed to get server certificate: The handle is in the wrong state for the requested operation
I noticed the fix on the below thread for windows 7 but I am seeing it on windows 10, multiple boxes at my work and others reporting on gitkraken slack channel.

Anyone fixed this on windows 10?

Windows 7 thread link:
GitKraken And Github - failed to get server certificate: The handle is in the wrong state for the requested operation

答:
UPDATE: This is not recommended as all traffic will be send over HTTP instead of HTTPS.

This means everything will be visible (not encrypted) to anyone watching network activity. Please see the comment from cboittin below

Credit to Kef in the comments.

Changing the remote origin from https to http fixed it for me. (Again, not recommended)

Disclaimer: <s>I do not know if this has any side effects. If it does, please let me know in the comments.</s>

How to change the remote origin address in gitkraken:

You can change it from https by checking the left navigation bar and clicking the 3 dots button next to the remote origin. (Image)

After that click edit origin.

Here you can see the pull and push addresses. Changing those from https to http fixed it for me.

ContentLicense: CC BY-SA 3.0


问:
nullpointerexception on Button ClickListener android
hi all m having a strange problem.

i have a button and when i set onClick Listener of it.

it gives me null Pointer Exception and application forcefully closes.

my code is

```<code>more = (Button) findViewById(R.id.moreButton);
System.out.println("BEFORE more listener CALL");
more.setOnClickListener(this);
</code>```

Its so strange for me please can any one help?

stackTrace is Below:

```<code>05-17 13:28:54.141: ERROR/AndroidRuntime(1509): FATAL EXCEPTION: main
05-17 13:28:54.141: ERROR/AndroidRuntime(1509): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.sigmatec.finditnear/org.sigmatec.finditnear.customListView}: java.lang.NullPointerException
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at  android.os.Looper.loop(Looper.java:123)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.main(ActivityThread.java:4627)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at java.lang.reflect.Method.invokeNative(Native Method)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at java.lang.reflect.Method.invoke(Method.java:521)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at dalvik.system.NativeStart.main(Native Method)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509): Caused by: java.lang.NullPointerException
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at org.sigmatec.finditnear.customListView.onCreate(customListView.java:114)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     ... 11 more
</code>```

UPDATED:

one more thing the Button that i am using has been taken from the answer from the link

How to add a footer in ListView?

i have used button instead of TextView Take a look at answer#2 at the end.

m using the Button from some other layout not from the one which has been set on setContentView. because i am using List and i want a button at the end of the list so i made a seperate .xml and used the following code to join it with the List Footer.

COde:

```<code>super.onCreate(savedInstanceState);
setContentView(R.layout.listview);

 ListView l1 = (ListView) findViewById(R.id.ListView01);
    View footerView =
        ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.layout_footer, null, false);

    l1.addFooterView(footerView);
    l1.setAdapter(adapter);
</code>```

答:
if you add a onclicklistener with "this" the activity had to extends OnClickListener, otherwhise the code should be like:</p>

```<code>more.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View arg0) {
    // TODO Auto-generated method stub
   }
});
</code>```

Body:
hi all m having a strange problem.

i have a button and when i set onClick Listener of it.

it gives me null Pointer Exception and application forcefully closes.

my code is

more = (Button) findViewById(R.id.moreButton);
System.out.println("BEFORE more listener CALL");
more.setOnClickListener(this);

Its so strange for me please can any one help?

stackTrace is Below:

05-17 13:28:54.141: ERROR/AndroidRuntime(1509): FATAL EXCEPTION: main
05-17 13:28:54.141: ERROR/AndroidRuntime(1509): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.sigmatec.finditnear/org.sigmatec.finditnear.customListView}: java.lang.NullPointerException
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at  android.os.Looper.loop(Looper.java:123)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.main(ActivityThread.java:4627)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at java.lang.reflect.Method.invokeNative(Native Method)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at java.lang.reflect.Method.invoke(Method.java:521)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at dalvik.system.NativeStart.main(Native Method)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509): Caused by: java.lang.NullPointerException
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at org.sigmatec.finditnear.customListView.onCreate(customListView.java:114)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     ... 11 more

UPDATED:

one more thing the Button that i am using has been taken from the answer from the link

How to add a footer in ListView?

i have used button instead of TextView Take a look at answer#2 at the end.

m using the Button from some other layout not from the one which has been set on setContentView. because i am using List and i want a button at the end of the list so i made a seperate .xml and used the following code to join it with the List Footer.

COde:

super.onCreate(savedInstanceState);
setContentView(R.layout.listview);

 ListView l1 = (ListView) findViewById(R.id.ListView01);
    View footerView =
        ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.layout_footer, null, false);

    l1.addFooterView(footerView);
    l1.setAdapter(adapter);

Body:
if you add a onclicklistener with "this" the activity had to extends OnClickListener, otherwhise the code should be like:

more.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View arg0) {
    // TODO Auto-generated method stub
   }
});


问:
How to deploy code from bit bucket to heroku?
while am doing auto deploying code from bit bucket to heroku, I got some configuration issue in bitbucket-pipelines.yml.

```<code> HEROKU_API_KEY: 'XXXXXX'
 HEROKU_APP_NAME: 'XXXX'
 ZIP_FILE: 'your-app-sources.tar.gz'
 WAIT: 'true'
</code>```

Above is the configuration for Heroku.

But while deploying it gives me an error near "ZIP_FILE":'..'

like that mentioned file/folder not found.

My question is which value i have to place for "ZIP_FILE":'XXXX'.

Please help me to go forward.

Note: am doing auto deployment from bitbucket to heroku for any push done on
  master branch.
  Thanks,SrinivasaRao.CH

答:
You can do this in a previous step in the deploy process.

```<code>- step:
   name: Create ZIP_FILE
   script:
     - tar czfv my_app.tgz /path/to/src
   artifacts:
     - my_app.tgz
</code>```

Such that, you can access the tar.gz app in your next step (the one you have above).

Everything should look like this:

```<code>pipelines:
  default:
    - step:
        name: Create ZIP_FILE
        script:
          - tar czfv my_app.tgz /path/to/src
        artifacts:
          - my_app.tgz
    - step:
        name: Deploy to Heroku
        deployment: test   # set to test, staging or production
        script:
          - pipe: atlassian/heroku-deploy:1.1.1
            variables:
              HEROKU_API_KEY: $HEROKU_API_KEY
              HEROKU_APP_NAME: $HEROKU_APP_NAME
              ZIP_FILE: "my_app.tgz"
</code>```

Body:
while am doing auto deploying code from bit bucket to heroku, I got some configuration issue in bitbucket-pipelines.yml.

 HEROKU_API_KEY: 'XXXXXX'
 HEROKU_APP_NAME: 'XXXX'
 ZIP_FILE: 'your-app-sources.tar.gz'
 WAIT: 'true'

Above is the configuration for Heroku.

But while deploying it gives me an error near "ZIP_FILE":'..'

like that mentioned file/folder not found.

My question is which value i have to place for "ZIP_FILE":'XXXX'.

Please help me to go forward.

Note: am doing auto deployment from bitbucket to heroku for any push done on
  master branch.
  Thanks,SrinivasaRao.CH

Body:
You can do this in a previous step in the deploy process.

- step:
   name: Create ZIP_FILE
   script:
     - tar czfv my_app.tgz /path/to/src
   artifacts:
     - my_app.tgz

Such that, you can access the tar.gz app in your next step (the one you have above).

Everything should look like this:

pipelines:
  default:
    - step:
        name: Create ZIP_FILE
        script:
          - tar czfv my_app.tgz /path/to/src
        artifacts:
          - my_app.tgz
    - step:
        name: Deploy to Heroku
        deployment: test   # set to test, staging or production
        script:
          - pipe: atlassian/heroku-deploy:1.1.1
            variables:
              HEROKU_API_KEY: $HEROKU_API_KEY
              HEROKU_APP_NAME: $HEROKU_APP_NAME
              ZIP_FILE: "my_app.tgz"


问:
File menus are not selectable for unity3d on kubuntu
hey I am new to linux ( kubuntu 19.10 ). I installed kubuntu and did some UI tweaking, after that I installed unity3d 2019.3 game engine from unity hub. When I opened it, sub menus of file menu are not selectable. Other apps are working fine

I have no idea whats going on ... plz help.
I will be happy to provide any info you want

答:
I found a workaround and that is to remove global menu...
Though I still dont know why there is a problem with unity3d and kde global menu</p>


问:
How do you introduce unit testing into a large, legacy (C/C++) codebase?
We have a large, multi-platform application written in C. (with a small but growing amount of C++) It has evolved over the years with many features you would expect in a large C/C++ application:

#ifdef hell

Large files that make it hard to isolate testable code

Functions that are too complex to be easily testable

Since this code is targeted for embedded devices, it's a lot of overhead to run it on the actual target. So we would like to do more of our development and testing in quick cycles, on a local system. But we would like to avoid the classic strategy of "copy/paste into a .c file on your system, fix bugs, copy/paste back". If developers are going to to go the trouble to do that, we'd like to be able to recreate the same tests later, and run in an automated fashion.

Here's our problem: in order to refactor the code to be more modular, we need it to be more testable. But in order to introduce automated unit tests, we need it to be more modular.

One problem is that since our files are so large, we might have a function inside a file that calls a function in the same file that we need to stub out to make a good unit test. It seems like this would be less of a problem as our code gets more modular, but that is a long way off.

One thing we thought about doing was tagging "known to be testable" source code with comments. Then we could write a script scan source files for testable code, compile it in a separate file, and link it with the unit tests. We could slowly introduce the unit tests as we fix defects and add more functionality.

However, there is concern that maintaining this scheme (along with all the required stub functions) will become too much of a hassle, and developers will stop maintaining the unit tests. So another approach is to use a tool that automatically generates stubs for all the code, and link the file with that. (the only tool we have found that will do this is an expensive commercial product) But this approach seems to require that all our code be more modular before we can even begin, since only the external calls can be stubbed out.

Personally, I would rather have developers think about their external dependencies and intelligently write their own stubs. But this could be overwhelming to stub out all the dependencies for a horribly overgrown, 10,000 line file. It might be difficult to convince developers that they need to maintain stubs for all their external dependencies, but is that the right way to do it? (One other argument I've heard is that the maintainer of a subsystem should maintain the stubs for their subsystem. But I wonder if "forcing" developers to write their own stubs would lead to better unit testing?)

The #ifdefs, of course, add another whole dimension to the problem.

We have looked at several C/C++ based unit test frameworks, and there are a lot of options that look fine. But we have not found anything to ease the transition from "hairball of code with no unit tests" to "unit-testable code".

So here are my questions to anyone else who has been through this:

What is a good starting point? Are we going in the right direction, or are we missing something obvious?

What tools might be useful to help with the transition? (preferably free/open source, since our budget right now is roughly "zero")

Note, our build environment is Linux/UNIX based, so we can't use any Windows-only tools.

答:
Not sure is it actual or not, but I have small advice here. As I understand, you ask methodological question about incremental non-invasive integration of unit testing into huge legacy code with a lot of stakeholders protecting their swamp.

Usually, first step is to build your testing code independently from all other code. Even this step in long-live legacy code is very complex. I propose to build your testing code as a dynamic shared library with run-time linking. That will allow you to refactor only small piece of code which is undertesting and not whole 20K file. So, you can start covering function by function without touching/fixing all linking issues


问:
adding JWT token in request in reactive way in webflux
I am using WebClient to call Rest API Which are secured by JWT token.
//To get Token

```<code>JwtToken token = client.post()
                .uri("")
                .body(BodyInserters.fromFormData("username", "XXX")
                        .with("password", "XXXXX"))
                .retrieve()
                .bodyToFlux(JwtToken.class)
                .onErrorMap(e -> new Exception("Error While getting Token", e))
                .blockLast();
</code>```

//Call secure API

```<code> WebClient client = consorsWebClientBuilder
                .defaultHeaders(token.bearer())
                .build();

              client
                .get()
                .uri(someURI)
                .retrieve()
                .bodyToMono(String.class)
</code>```

i am calling  Block in reactive chain, so web flux is not happy and saying

block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-client-epoll-12

How can i add token in reactive way ?
Note, I Can create Filter but still in filter also i need to call Block

答:
```<code>I used map for this, not the best solution but does the work

Mono<JwtToken>  token = client.post()
                .uri("")
                .body(BodyInserters.fromFormData("username", "XXX")
                        .with("password", "XXXXX"))
                .retrieve()
                .bodyToMon(JwtToken.class)
                .onErrorMap(e -> new Exception("Error While getting Token", e))

return token
     .flatMap(token -> callApi(request, token));
</code>```

Body:
I am using WebClient to call Rest API Which are secured by JWT token.
//To get Token

JwtToken token = client.post()
                .uri("")
                .body(BodyInserters.fromFormData("username", "XXX")
                        .with("password", "XXXXX"))
                .retrieve()
                .bodyToFlux(JwtToken.class)
                .onErrorMap(e -> new Exception("Error While getting Token", e))
                .blockLast();

//Call secure API

 WebClient client = consorsWebClientBuilder
                .defaultHeaders(token.bearer())
                .build();

              client
                .get()
                .uri(someURI)
                .retrieve()
                .bodyToMono(String.class)

i am calling  Block in reactive chain, so web flux is not happy and saying

block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-client-epoll-12

How can i add token in reactive way ?
Note, I Can create Filter but still in filter also i need to call Block


答:
If you want to group by year, month, day and hour:

```<code>const result = data.reduce((a, { name, date }) => {
    let currentDate = new Date(date);
    let dateHour = currentDate.getFullYear() + '/' + currentDate.getMonth()
        + '/' +  currentDate.getDate()  + '/' +  currentDate.getHours();
    a[dateHour] = a[dateHour] || {name, date};
    return a;
}, {})
</code>```

An example:

let data = [
  {
      'name' : 'sample',
      'date' : '2020-02-18 13:50:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 13:20:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 13:12:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 13:13:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 12:50:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 11:50:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 07:50:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 01:50:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 01:30:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 01:20:01'
  },
]

const result = data.reduce((a, { name, date }) => {
  let currentDate = new Date(date);
  let dateHour = currentDate.getFullYear() + '/' + currentDate.getMonth()  + '/' +  currentDate.getDate()  + '/' +  currentDate.getHours();
  a[dateHour] = a[dateHour] || {name, date};
  return a;
}, {})

console.log(Object.values(result));```

Title: how to display the data per hour ago in angular

Body:
here's the code:

data = [
    {
        'name' : 'sample'
        'date' : '2020-02-18 13:50:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 13:20:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 13:12:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 13:13:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 12:50:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 11:50:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 07:50:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 01:50:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 01:30:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 01:20:01'
    },
]

expected output:

 data = [
        {
            'name' : 'sample'
            'date' : '2020-02-18 13:50:01'
        },
        {
            'name' : 'sample'
            'date' : '2020-02-18 12:50:01'
        },
        {
            'name' : 'sample'
            'date' : '2020-02-18 11:50:01'
        },
        {
            'name' : 'sample'
            'date' : '2020-02-18 07:50:01'
        },
    ]

what I want to do here is to display the data per hour.
the data will filter like this.

data = [
            {
                'name' : 'sample'
                'date' : '2020-02-18 13:50:01'
            },
            {
                'name' : 'sample'
                'date' : '2020-02-18 12:50:01'
            },
            {
                'name' : 'sample'
                'date' : '2020-02-18 11:50:01'
            },
            {
                'name' : 'sample'
                'date' : '2020-02-18 07:50:01'
            },
        ]

it will not get the other data not hour ago. if the data is last 30minutes it will not get/display. the data should be last hour ago, data should be per hour ago. it should be dynamic. because if there's a new data which is
date: 2020-02-18 14:00:01, then per hour ago:

2020-02-18 14:00:01,

2020-02-18 13:00:01,

2020-02-18 12:00:01, etc...

here's the code: https://stackblitz.com/edit/angular-dnbses?file=src/app/app.component.ts

Body:
If you want to group by year, month, day and hour:

const result = data.reduce((a, { name, date }) => {
    let currentDate = new Date(date);
    let dateHour = currentDate.getFullYear() + '/' + currentDate.getMonth()
        + '/' +  currentDate.getDate()  + '/' +  currentDate.getHours();
    a[dateHour] = a[dateHour] || {name, date};
    return a;
}, {})

An example:

let data = [
  {
      'name' : 'sample',
      'date' : '2020-02-18 13:50:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 13:20:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 13:12:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 13:13:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 12:50:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 11:50:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 07:50:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 01:50:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 01:30:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 01:20:01'
  },
]

const result = data.reduce((a, { name, date }) => {
  let currentDate = new Date(date);
  let dateHour = currentDate.getFullYear() + '/' + currentDate.getMonth()  + '/' +  currentDate.getDate()  + '/' +  currentDate.getHours();
  a[dateHour] = a[dateHour] || {name, date};
  return a;
}, {})

console.log(Object.values(result));


问:
Powershell call works on server but returns error through jenkins
We recently got some new Windows Server 2019 machines and I want to add them to our Jenkins setup. The problem is:
executing any external program causes an error. docker login, git status, java -version all give an error like this

```<code>[TestPowershell] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\XXX~1\AppData\Local\Temp\3\jenkins1416755497082623783.ps1'"
java : java version "1.8.0_101"
At C:\Users\XXX-sa\AppData\Local\Temp\3\jenkins1416755497082623783.ps1:1 char:1
+ java -version
+ ~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (java version "1.8.0_101":String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Java(TM) SE Runtime Environment (build 1.8.0_101-b13
)
Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)
Notifying upstream projects of job completion
Finished: SUCCESS
</code>```

Tried it on the server itself, works fine. All the setup is the same as our 2016 servers, which dont present this issue

EDIT: I setup a vanilla master on VM 2019 and it works without this error, still presents the error with a 2016 master.

答: For some reason, it seems that this is related to dotnet 4.8. Windows 2019 1809 ships with 4.7 which presents this strange error, not only does it happen on java -version, but git clone , npm install and ng build to name a few also cause the same error. Installing dotnet framework 4.8 fixes it.. in case anyone is having the same issue we were..</p>

Body:
We recently got some new Windows Server 2019 machines and I want to add them to our Jenkins setup. The problem is:
executing any external program causes an error. docker login, git status, java -version all give an error like this

[TestPowershell] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\XXX~1\AppData\Local\Temp\3\jenkins1416755497082623783.ps1'"
java : java version "1.8.0_101"
At C:\Users\XXX-sa\AppData\Local\Temp\3\jenkins1416755497082623783.ps1:1 char:1
+ java -version
+ ~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (java version "1.8.0_101":String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Java(TM) SE Runtime Environment (build 1.8.0_101-b13
)
Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)
Notifying upstream projects of job completion
Finished: SUCCESS

Tried it on the server itself, works fine. All the setup is the same as our 2016 servers, which dont present this issue

EDIT: I setup a vanilla master on VM 2019 and it works without this error, still presents the error with a 2016 master.


答:
if you add button in footerview so try this..</p>

```<code>more = (Button)footerview.findViewById(R.id.moreButton);
System.out.println("BEFORE more listener CALL");
more.setOnClickListener(this);
</code>```

Title: nullpointerexception on Button ClickListener android

Body:
if you add button in footerview so try this..

more = (Button)footerview.findViewById(R.id.moreButton);
System.out.println("BEFORE more listener CALL");
more.setOnClickListener(this);


问:
Change column type in pandas
I created a DataFrame from a list of lists:

table = [
    ['a',  '1.2',  '4.2' ],
    ['b',  '70',   '0.03'],
    ['x',  '5',    '0'   ],
]

df = pd.DataFrame(table)
```

How do I convert the columns to specific types? In this case, I want to convert columns 2 and 3 into floats.

Is there a way to specify the types while converting the list to DataFrame? Or is it better to create the DataFrame first and then loop through the columns to change the dtype for each column? Ideally I would like to do this in a dynamic way because there can be hundreds of columns, and I don't want to specify exactly which columns are of which type. All I can guarantee is that each column contains values of the same type.

答:
pandas >= 1.0

Here's a chart that summarises some of the most important conversions in pandas.

Conversions to string are trivial .astype(str) and are not shown in the figure.

"Hard" versus "Soft" conversions

Note that "conversions" in this context could either refer to converting text data into their actual data type (hard conversion), or inferring more appropriate data types for data in object columns (soft conversion). To illustrate the difference, take a look at

df = pd.DataFrame({'a': ['1', '2', '3'], 'b': [4, 5, 6]}, dtype=object)
df.dtypes

a    object
b    object
dtype: object

# Actually converts string to numeric - hard conversion
df.apply(pd.to_numeric).dtypes

a    int64
b    int64
dtype: object

# Infers better data types for object data - soft conversion
df.infer_objects().dtypes

a    object  # no change
b     int64
dtype: object

# Same as infer_objects, but converts to equivalent ExtensionType
    df.convert_dtypes().dtypes
```

Title: Change column type in pandas

Body:
I created a DataFrame from a list of lists:

table = [
    ['a',  '1.2',  '4.2' ],
    ['b',  '70',   '0.03'],
    ['x',  '5',    '0'   ],
]

df = pd.DataFrame(table)

How do I convert the columns to specific types? In this case, I want to convert columns 2 and 3 into floats.

Is there a way to specify the types while converting the list to DataFrame? Or is it better to create the DataFrame first and then loop through the columns to change the dtype for each column? Ideally I would like to do this in a dynamic way because there can be hundreds of columns, and I don't want to specify exactly which columns are of which type. All I can guarantee is that each column contains values of the same type.


问:
Gradle Jar Creating Task getting stucked
I am new to gradle. When running the gradle build task in intelliJ, my task keep running infinitely and never completed. The task is written as follows:

```<code>task webjar(type: Jar) {
    from(fileTree("build")) {
        into "META-INF/resources"
    }
}
jar.finalizedBy('webjar')
</code>```

Can anybody help me in pointing out if I am doing anything wrong here?

update: When i am writing the task as follows it finishes successfully:

```<code>task webjar(type: Jar) {
    destinationDir file("${projectDir}/build")
    from(fileTree("build")) {
        into "META-INF/resources"
    }
}
</code>```

Thanks,

答:
The issue is that you are attempting to pack the whole build folder into that jar, which includes all the project output.

So that is most likely the issue there. build should not be what you package in META-INF/resources.

Instead you will need to identify which task produces the content to be included in META-INF/resources and use its output as the from argument.

Body:
I am new to gradle. When running the gradle build task in intelliJ, my task keep running infinitely and never completed. The task is written as follows:

task webjar(type: Jar) {
    from(fileTree("build")) {
        into "META-INF/resources"
    }
}
jar.finalizedBy('webjar')

Can anybody help me in pointing out if I am doing anything wrong here?

update: When i am writing the task as follows it finishes successfully:

task webjar(type: Jar) {
    destinationDir file("${projectDir}/build")
    from(fileTree("build")) {
        into "META-INF/resources"
    }
}

Thanks,


问:
Collection View horizontal direction with dynamic height
I have a collection view with direction set to horizontal and paging enable. The things is, the height of my collection cell each page sometimes is higher than the phone screen size. What I want to achieve is user can scroll down the cell and swipe right to the next page.

Currently, I only able to display the collection cell one full page, without manage to scroll downward based on content height. Here some code:

```<code>extension EventListDetailsVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cat = dataArray[indexPath.row]

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "celldetails", for: indexPath) as? EventListDetailsCVC
        cell?.imageEvent.image = UIImage(named: cat.imageEvent)
        cell?.eventTitleLabel.text = cat.titleEvent
        cell?.eventDescriptionLabel.text = cat.content

        return cell!
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        return CGSize(width: self.collectionView.frame.size.width, height: self.collectionView.frame.size.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.zero
     }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
}
</code>```

this how it should be

I tried to embed my collectionView into tableView, but it seems does not work because I have dynamic height in a cell.

Is it another way to achive this?

p/s I just started learning swift, thanks.

答:
I think you should try UIPageViewController with the scroll transition style. It has native pagination between pages.

Every page should have UIScrollView.

Body:
I have a collection view with direction set to horizontal and paging enable. The things is, the height of my collection cell each page sometimes is higher than the phone screen size. What I want to achieve is user can scroll down the cell and swipe right to the next page.

Currently, I only able to display the collection cell one full page, without manage to scroll downward based on content height. Here some code:

extension EventListDetailsVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cat = dataArray[indexPath.row]

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "celldetails", for: indexPath) as? EventListDetailsCVC
        cell?.imageEvent.image = UIImage(named: cat.imageEvent)
        cell?.eventTitleLabel.text = cat.titleEvent
        cell?.eventDescriptionLabel.text = cat.content

        return cell!
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        return CGSize(width: self.collectionView.frame.size.width, height: self.collectionView.frame.size.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.zero
     }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
}

this how it should be

I tried to embed my collectionView into tableView, but it seems does not work because I have dynamic height in a cell.

Is it another way to achive this?

p/s I just started learning swift, thanks.


问:
How to clean text from .pdf artifacts?
I am replacing placeholders in .pdf file like mentioned in itext7 doc

```<code> PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
    PdfPage page = pdfDoc.getFirstPage();
    PdfDictionary dict = page.getPdfObject();

    PdfObject object = dict.get(PdfName.Contents);
    if (object instanceof PdfStream) {
        PdfStream stream = (PdfStream) object;
        byte[] data = stream.getBytes();
        String replacedData = new String(data).replace("{#Address_line1}", "Saint-Petersburg");
        stream.setData(replacedData.getBytes(StandardCharsets.UTF_8));
    }

    pdfDoc.close()
</code>```

My .pdf file is a little bit more complicated, so my {#Address_line1} placeholder looks like ({#)4(Add)-4(ress)-17(_)6(L)-6(i)3(n)-8(e1)4(})

Are there any tools to clean up my placeholder, so that ({#)4(Add)-4(ress)-17(_)6(L)-6(i)3(n)-8(e1)4(}) will turn into {#Address_line1} ? I can write it myself, but maybe there are some ready solutions

答: No way, need to implement my own solution.</p>

Title: How to clean text from .pdf artifacts?

Body:
I am replacing placeholders in .pdf file like mentioned in itext7 doc

 PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
    PdfPage page = pdfDoc.getFirstPage();
    PdfDictionary dict = page.getPdfObject();

    PdfObject object = dict.get(PdfName.Contents);
    if (object instanceof PdfStream) {
        PdfStream stream = (PdfStream) object;
        byte[] data = stream.getBytes();
        String replacedData = new String(data).replace("{#Address_line1}", "Saint-Petersburg");
        stream.setData(replacedData.getBytes(StandardCharsets.UTF_8));
    }

    pdfDoc.close()

My .pdf file is a little bit more complicated, so my {#Address_line1} placeholder looks like ({#)4(Add)-4(ress)-17(_)6(L)-6(i)3(n)-8(e1)4(})

Are there any tools to clean up my placeholder, so that ({#)4(Add)-4(ress)-17(_)6(L)-6(i)3(n)-8(e1)4(}) will turn into {#Address_line1} ? I can write it myself, but maybe there are some ready solutions


问:
Azure Kusto Data Explorer - convert duration to days
Is there a way to find number of days from timespan?

For example,
time(00:00:00.2000000), time(00:30:30), time(01:00:00), time(413.00:00:00)
should return 0, 0, 0, 413

答:
You could use format_timespan():</p>

```<code>let getDays = (t:timespan)
{
    toint(format_timespan(t, 'd'))
};
print result = getDays(time(00:00:00.2000000)), //0
               getDays(time(00:30:30)), //0
               getDays(time(01:00:00)), //0
               getDays(time(413.00:00:00)) //413
</code>```

Body:
You could use format_timespan():

let getDays = (t:timespan)
{
    toint(format_timespan(t, 'd'))
};
print result = getDays(time(00:00:00.2000000)), //0
               getDays(time(00:30:30)), //0
               getDays(time(01:00:00)), //0
               getDays(time(413.00:00:00)) //413


问:
How to Multiply two numbers in php
1)I am retrieving the deduction data from db as 1000.00 and its type is in double(10,2)

2) And i have calculated monthly salary based on working days as shown below,
i am getting out put of $emppp as 2898.00;

3) Now i am trying to subtract deduction(1000.00 which is from db)from salary then its showing the error like this

A non-numeric value encountered

```<code><th class='text-right'>".$emppp-$total_did;echo"Rs</th>

$amounts=round($employee_salary/$days);
$amountss=$amounts;
$emp_salary=number_format($totaldays*$amountss,2);
$emppp=str_replace(',','',$emp_salary);
</code>```

答:
What you need is like this:

1.get $emp_salary by doing $totaldays*$amounts. (don't use number_format() there)

2.Now subtract deduction amount from $emp_salary and then use number_format()

Sample code:

```<code><?php

$employee_salary = 45000.00; //assumed

$days = 29; //feb month total days

$totaldays = 20; //days user is present in office

$deduction = 10000.00; // you gave it in your question

$amounts = round($employee_salary/$days);//get per day salary

$emp_salary= $totaldays*$amounts; // get total salary based on days user is present in office

echo $emppp= number_format($emp_salary-$deduction ,2); // now remove deduction amount and use number_format()
</code>```

Output: https://3v4l.org/O8PO1

More reduced code: https://3v4l.org/oftfC

Title: How to Multiply two numbers in php

Body:
1)I am retrieving the deduction data from db as 1000.00 and its type is in double(10,2)

2) And i have calculated monthly salary based on working days as shown below,
i am getting out put of $emppp as 2898.00;

3) Now i am trying to subtract deduction(1000.00 which is from db)from salary then its showing the error like this

A non-numeric value encountered

".$emppp-$total_did;echo"Rs

$amounts=round($employee_salary/$days);
$amountss=$amounts;
$emp_salary=number_format($totaldays*$amountss,2);
$emppp=str_replace(',','',$emp_salary);

Body:
What you need is like this:

1.get $emp_salary by doing $totaldays*$amounts. (don't use number_format() there)

2.Now subtract deduction amount from $emp_salary and then use number_format()

Sample code:

<?php

$employee_salary = 45000.00; //assumed

$days = 29; //feb month total days

$totaldays = 20; //days user is present in office

$deduction = 10000.00; // you gave it in your question

$amounts = round($employee_salary/$days);//get per day salary

$emp_salary= $totaldays*$amounts; // get total salary based on days user is present in office

echo $emppp= number_format($emp_salary-$deduction ,2); // now remove deduction amount and use number_format()

Output: https://3v4l.org/O8PO1

More reduced code: https://3v4l.org/oftfC


问:
NullPointerException when adding ClickListener
I try to find a view by its ID but I get the NullPointerException. Have you any idea where am I doing wrong?

This is the exception I'm getting

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.voicemail, PID: 24209
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.voicemail/com.example.voicemail.ComposeMail}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3162)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3305)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1993)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7285)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.example.voicemail.ComposeMail.onCreate(ComposeMail.java:34)
        at android.app.Activity.performCreate(Activity.java:7353)
        at android.app.Activity.performCreate(Activity.java:7344)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1275)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3142)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3305)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1993)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7285)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
</code>```

The code:

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Initializing the views
    editTextEmail = (EditText) findViewById(R.id.editTextEmail);

    editTextSubject = (EditText) findViewById(R.id.editTextSubject);

    editTextMessage = (EditText) findViewById(R.id.editTextMessage);

    buttonSend = (Button) findViewById(R.id.buttonSend);

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

private void sendEmail() {
   //doSomething
}
</code>```

Here's my XML code

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/bg2"
    android:padding="20dp"
    android:gravity="center_horizontal"
    tools:context=".ComposeMail">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginTop="40dp"
        android:textColorHint="@android:color/white"
        android:textColor="@android:color/white"
        android:hint="@string/to"

        android:id="@+id/editTextEmail" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginTop="40dp"
        android:textColorHint="@android:color/white"
        android:textColor="@android:color/white"
        android:hint="@string/subject"
        android:id="@+id/editTextSubject" />

    <EditText
        android:lines="15"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:textColorHint="@android:color/white"
        android:textColor="@android:color/white"
        android:hint="@string/message"
        android:gravity="top"
        android:id="@+id/editTextMessage" />

    <Button
        android:id="@+id/buttonSend"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_marginTop="20dp"
        android:background="@drawable/round_corner"
        android:text="@string/send"
        android:textColor="#ffffff"/>

</LinearLayout>
</code>```

I'm getting a NullPointerException on setOnClickListener. Basically I'm sending data from one activity to another using an intent. I have tried almost everything to solve this but it keeps on showing me the same exception. Please help me.

答:
Try this, I think it will work.</p>

```<code>super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

EditText editTextEmail, editTextSubject, editTextMessage;
Button buttonSend;

//Initializing the views
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextSubject = (EditText) findViewById(R.id.editTextSubject);
editTextMessage = (EditText) findViewById(R.id.editTextMessage);

buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        sendEmail();
    }
});

private void sendEmail() {

    //Getting content for email
    String email = editTextEmail.getText().toString().trim();
    String subject = editTextSubject.getText().toString().trim();
    String message = editTextMessage.getText().toString().trim();
    String e=intent.getStringExtra("Username");
    String p=intent.getStringExtra("Password");

    //Creating SendMail object
    SendMail sm = new SendMail(this, email, subject, message, e, p);
}
</code>```

Body:
I try to find a view by its ID but I get the NullPointerException. Have you any idea where am I doing wrong?

This is the exception I'm getting

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.voicemail, PID: 24209
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.voicemail/com.example.voicemail.ComposeMail}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3162)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3305)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1993)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7285)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.example.voicemail.ComposeMail.onCreate(ComposeMail.java:34)
        at android.app.Activity.performCreate(Activity.java:7353)
        at android.app.Activity.performCreate(Activity.java:7344)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1275)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3142)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3305)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1993)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7285)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)

The code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Initializing the views
    editTextEmail = (EditText) findViewById(R.id.editTextEmail);

    editTextSubject = (EditText) findViewById(R.id.editTextSubject);

    editTextMessage = (EditText) findViewById(R.id.editTextMessage);

    buttonSend = (Button) findViewById(R.id.buttonSend);

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

private void sendEmail() {
   //doSomething
}

Here's my XML code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/bg2"
    android:padding="20dp"
    android:gravity="center_horizontal"
    tools:context=".ComposeMail">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginTop="40dp"
        android:textColorHint="@android:color/white"
        android:textColor="@android:color/white"
        android:hint="@string/to"

        android:id="@+id/editTextEmail" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginTop="40dp"
        android:textColorHint="@android:color/white"
        android:textColor="@android:color/white"
        android:hint="@string/subject"
        android:id="@+id/editTextSubject" />

    <EditText
        android:lines="15"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:textColorHint="@android:color/white"
        android:textColor="@android:color/white"
        android:hint="@string/message"
        android:gravity="top"
        android:id="@+id/editTextMessage" />

    <Button
        android:id="@+id/buttonSend"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_marginTop="20dp"
        android:background="@drawable/round_corner"
        android:text="@string/send"
        android:textColor="#ffffff"/>

</LinearLayout>

I'm getting a NullPointerException on setOnClickListener. Basically I'm sending data from one activity to another using an intent. I have tried almost everything to solve this but it keeps on showing me the same exception. Please help me.

Body:
Try this, I think it will work.

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

EditText editTextEmail, editTextSubject, editTextMessage;
Button buttonSend;

//Initializing the views
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextSubject = (EditText) findViewById(R.id.editTextSubject);
editTextMessage = (EditText) findViewById(R.id.editTextMessage);

buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        sendEmail();
    }
});

private void sendEmail() {

    //Getting content for email
    String email = editTextEmail.getText().toString().trim();
    String subject = editTextSubject.getText().toString().trim();
    String message = editTextMessage.getText().toString().trim();
    String e=intent.getStringExtra("Username");
    String p=intent.getStringExtra("Password");

    //Creating SendMail object
    SendMail sm = new SendMail(this, email, subject, message, e, p);
}


问:
R row-wise sampling with upside down normal distribution
I have a data frame DF that looks like this:

```<code>Min Max
10  80
20  90
40  120
</code>```

I want to append a new Random column with a randomly generated number between the min and max values per row. The sampling of the number shall be derived from an upside down normal distribution and exclude the middle values like illustrated below

The below prototype code with single variables seem to work but I'm stuck with how to apply this row-wise.

```<code>min <- 1
max <- 20
q <- min + (max-min)*rbeta(10000, 0.5, 0.5)
q <- q[!(q > 5 & q < 15)][1:10000]
hist(q)
</code>```

答:
Something like this?
This calculates the 25% and the 75% cutoffs where the values may not lie between and samples so long until it may return a value. Also it is executed in a row-wise manner.</p>

```<code>library(dplyr)
fun <- function(min, max){
  repeat {
  x <- min + (max-min)*rbeta(1,0.5,0.5)
  q1 <- min + (max-min)*pbeta(0.25,0.5,0.5)
  q2 <- min + (max-min)*pbeta(0.75,0.5,0.5)
  if(x<=q1 | x>=q2) break
  }
  return(x)
}

df <- data.frame(min=1:20, max=21:40)
df %>% rowwise() %>%
  mutate(value=fun(min, max))

> Source: local data frame [20 x 3]
> Groups: <by row>

> # A tibble: 20 x 3
>      min   max value
>    <int> <int> <dbl>
>  1     1    21  3.38
>  2     2    22  7.48
>  3     3    23  3.02
>  4     4    24  4.47
</code>```

Body:
I have a data frame DF that looks like this:

Min Max
10  80
20  90
40  120

I want to append a new Random column with a randomly generated number between the min and max values per row. The sampling of the number shall be derived from an upside down normal distribution and exclude the middle values like illustrated below

The below prototype code with single variables seem to work but I'm stuck with how to apply this row-wise.

min <- 1
max <- 20
q <- min + (max-min)*rbeta(10000, 0.5, 0.5)
q <- q[!(q > 5 & q < 15)][1:10000]
hist(q)

Body:
Something like this?
This calculates the 25% and the 75% cutoffs where the values may not lie between and samples so long until it may return a value. Also it is executed in a row-wise manner.

library(dplyr)
fun <- function(min, max){
  repeat {
  x <- min + (max-min)*rbeta(1,0.5,0.5)
  q1 <- min + (max-min)*pbeta(0.25,0.5,0.5)
  q2 <- min + (max-min)*pbeta(0.75,0.5,0.5)
  if(x<=q1 | x>=q2) break
  }
  return(x)
}

df <- data.frame(min=1:20, max=21:40)
df %>% rowwise() %>%
  mutate(value=fun(min, max))

> Source: local data frame [20 x 3]
> Groups: <by row>

> # A tibble: 20 x 3
>      min   max value
>    <int> <int> <dbl>
>  1     1    21  3.38
>  2     2    22  7.48
>  3     3    23  3.02
>  4     4    24  4.47


问:
RSS feed excerpt doesn't display the excerpt
I am trying to display the excerpt in a custom feed page, using the_excerpt_rss() function, I already set the summary show mode in Settings->Reading but it returns me the first paragraph of content, is there any another function to call just the excerpt, I already try with the_excerpt() and get_the_excerpt()?

Here is my code:

<description><![CDATA[<?php html_entity_decode(preg_replace( "/\r|\n/", "",the_excerpt_rss())); ?>]]></description>

答:
I had found a solution. So I customized the function add_feed_content($content):

```<code>function add_feed_content($content) {
    global $post;
    $excerpt = $post->post_excerpt;

    if(is_feed()) {
        if (strlen($excerpt) > 0){
            $content = '';
            $content .= $excerpt;
            return $content;
        } else {
            return $content;
        }
    }
}
add_filter('the_excerpt_rss', 'add_feed_content');
</code>```

Body:
I had found a solution. So I customized the function add_feed_content($content):

function add_feed_content($content) {
    global $post;
    $excerpt = $post->post_excerpt;

    if(is_feed()) {
        if (strlen($excerpt) > 0){
            $content = '';
            $content .= $excerpt;
            return $content;
        } else {
            return $content;
        }
    }
}
add_filter('the_excerpt_rss', 'add_feed_content');


问:
How to apply Application.ShortcutMenus so the Macro still appears when right-clicking a table?
There seems to be very little online around this, so some input here would be very useful.

I have used the below code to add an option to a right-click menu:

```<code>Private Sub Workbook_Open()
    Dim MyMenu As Object

Set MyMenu = Application.ShortcutMenus(xlWorksheetCell) _
    .MenuItems.AddMenu("Opportunities", 1)

With MyMenu.MenuItems
    .Add "Open", "openOpportunity", , 1, , ""
    .Add "Edit", "editOpportunity", , 2, , ""
End With

Set MyMenu = Nothing

End Sub
</code>```

This adds an option to the right-click menu when I right-click in a cell, but when I right-click a cell in an Excel table, it doesn't appear.

Any ideas where I go next?

答:
You also must add your options to 'List Range Popup'. I am not familiar with the way you do that and I don't know how to obtain the necessary Command bar index, so I will show you my way to do exactly what you need, in the next code:

```<code>Sub AddButContextMenu()
  Dim CMenu_Cell As CommandBar, MySubMCell As CommandBarControl
  Dim CMenu_Table As CommandBar, MySubMTable As CommandBarControl
    'Delete the controls first, in order to avoid duplicates
    Call DeleteFromCellMenu
    'Set ContextMenu to the Cell menu and List Range Popup
    Set CMenu_Cell = Application.CommandBars(35)  'Cell menu
    Set CMenu_Table = Application.CommandBars(71) 'List Range Popup
     Set MySubMCell = CMenu_Cell.Controls.Add(Type:=msoControlPopup, Before:=3)
     Set MySubMTable = CMenu_Table.Controls.Add(Type:=msoControlPopup, Before:=3)

    With MySubMCell
        .Caption = "Opportunities"
        .Tag = "My_Tag"
        With .Controls.Add(Type:=msoControlButton)
            .OnAction = "'" & ThisWorkbook.Name & "'!" & "openOpportunity"
            .Caption = "Open"
        End With
        With .Controls.Add(Type:=msoControlButton)
            .OnAction = "'" & ThisWorkbook.Name & "'!" & "editOpportunity"
            .Caption = "Edit"
        End With
    End With
    With MySubMTable
        .Caption = "Opportunities"
        .Tag = "My_Tag"
        With .Controls.Add(Type:=msoControlButton)
            .OnAction = "'" & ThisWorkbook.Name & "'!" & "openOpportunity"
            .Caption = "Open"
        End With
        With .Controls.Add(Type:=msoControlButton)
            .OnAction = "'" & ThisWorkbook.Name & "'!" & "editOpportunity"
            .Caption = "Edit"
        End With
    End With

    CMenu_Cell.Controls(4).BeginGroup = True 'add separator
    CMenu_Table.Controls(4).BeginGroup = True 'add separator
End Sub
Sub DeleteFromCellMenu()
    Dim ContextMCell As CommandBar, ContextMTable As CommandBar
    Dim ctrl As CommandBarControl

    Set ContextMCell = Application.CommandBars(35)  'Cell
    Set ContextMTable = Application.CommandBars(71) 'List Range Popup

    For Each ctrl In ContextMCell.Controls
        If ctrl.Tag = "My_Tag" Then
            ctrl.Delete
        End If
    Next ctrl
    For Each ctrl In ContextMTable.Controls
        If ctrl.Tag = "My_Tag" Then
            ctrl.Delete
        End If
    Next ctrl
End Sub
</code>```

If interested, I can show you a method to identify all shortcut menus...

Body:
There seems to be very little online around this, so some input here would be very useful.

I have used the below code to add an option to a right-click menu:

Private Sub Workbook_Open()
    Dim MyMenu As Object

Set MyMenu = Application.ShortcutMenus(xlWorksheetCell) _
    .MenuItems.AddMenu("Opportunities", 1)

With MyMenu.MenuItems
    .Add "Open", "openOpportunity", , 1, , ""
    .Add "Edit", "editOpportunity", , 2, , ""
End With

Set MyMenu = Nothing

End Sub

This adds an option to the right-click menu when I right-click in a cell, but when I right-click a cell in an Excel table, it doesn't appear.

Any ideas where I go next?

Body:
You also must add your options to 'List Range Popup'. I am not familiar with the way you do that and I don't know how to obtain the necessary Command bar index, so I will show you my way to do exactly what you need, in the next code:

Sub AddButContextMenu()
  Dim CMenu_Cell As CommandBar, MySubMCell As CommandBarControl
  Dim CMenu_Table As CommandBar, MySubMTable As CommandBarControl
    'Delete the controls first, in order to avoid duplicates
    Call DeleteFromCellMenu
    'Set ContextMenu to the Cell menu and List Range Popup
    Set CMenu_Cell = Application.CommandBars(35)  'Cell menu
    Set CMenu_Table = Application.CommandBars(71) 'List Range Popup
     Set MySubMCell = CMenu_Cell.Controls.Add(Type:=msoControlPopup, Before:=3)
     Set MySubMTable = CMenu_Table.Controls.Add(Type:=msoControlPopup, Before:=3)

    With MySubMCell
        .Caption = "Opportunities"
        .Tag = "My_Tag"
        With .Controls.Add(Type:=msoControlButton)
            .OnAction = "'" & ThisWorkbook.Name & "'!" & "openOpportunity"
            .Caption = "Open"
        End With
        With .Controls.Add(Type:=msoControlButton)
            .OnAction = "'" & ThisWorkbook.Name & "'!" & "editOpportunity"
            .Caption = "Edit"
        End With
    End With
    With MySubMTable
        .Caption = "Opportunities"
        .Tag = "My_Tag"
        With .Controls.Add(Type:=msoControlButton)
            .OnAction = "'" & ThisWorkbook.Name & "'!" & "openOpportunity"
            .Caption = "Open"
        End With
        With .Controls.Add(Type:=msoControlButton)
            .OnAction = "'" & ThisWorkbook.Name & "'!" & "editOpportunity"
            .Caption = "Edit"
        End With
    End With

    CMenu_Cell.Controls(4).BeginGroup = True 'add separator
    CMenu_Table.Controls(4).BeginGroup = True 'add separator
End Sub
Sub DeleteFromCellMenu()
    Dim ContextMCell As CommandBar, ContextMTable As CommandBar
    Dim ctrl As CommandBarControl

    Set ContextMCell = Application.CommandBars(35)  'Cell
    Set ContextMTable = Application.CommandBars(71) 'List Range Popup

    For Each ctrl In ContextMCell.Controls
        If ctrl.Tag = "My_Tag" Then
            ctrl.Delete
        End If
    Next ctrl
    For Each ctrl In ContextMTable.Controls
        If ctrl.Tag = "My_Tag" Then
            ctrl.Delete
        End If
    Next ctrl
End Sub

If interested, I can show you a method to identify all shortcut menus...


问:
RabbitMQ File Size-based Log Rotation Default Size
I'm new to RabbitMQ and I have an application that uses RabbitMQ as the message broker. Up until this day, I've been using the default settings - no log rotation. I wanted to use the log rotation feature so I set it using:

```<code>{log, [
        {file, [{file, "MyAppLogs.log"},
                {level, info},
                {date, "$D0"},
                {size, 1073741824},
                {count, 30}
                ]}
    ]}
</code>```

Of course testing would take a while if I am to test 1GB file size, so for testing purposes I changed it to 1024 instead. I expected the log will rotate when it reaches 1KB but it did not. I've noticed that the log files would only rotate once the file size reaches 5KB.
So my question is - is the minimum log file size for RabbitMQ file-based log rotation 5KB?
I've looked around the web - especially in the rabbitmq documentation site: https://www.rabbitmq.com/logging.html - however there's no mention of any minimimum size.
Here is the sample output of my the settings that I've used:
Test Settings:

```<code>[{file, [{file, "rabbit.log"},
              {level, info},
              {date, "$D0"},
              {size, 1024},
              {count, 3}
             ]}
     ]}
</code>```

答:
This requires rabbitmq version > 3.7. Put the log rotate logics inside your rabbitmq.conf file like below:

{log, [
        {file, [{file, "/var/log/rabbitmq/rabbitmq.log"}, %% log.file
                {level, info},        %% log.file.info
                {date, "$D0"},           %% log.file.rotation.date
                {size, 1024},            %% log.file.rotation.size
                {count, 15}            %% log.file.rotation.count
                ]}
    ]},
```

Body:
I'm new to RabbitMQ and I have an application that uses RabbitMQ as the message broker. Up until this day, I've been using the default settings - no log rotation. I wanted to use the log rotation feature so I set it using:

{log, [
        {file, [{file, "MyAppLogs.log"},
                {level, info},
                {date, "$D0"},
                {size, 1073741824},
                {count, 30}
                ]}
    ]}

Of course testing would take a while if I am to test 1GB file size, so for testing purposes I changed it to 1024 instead. I expected the log will rotate when it reaches 1KB but it did not. I've noticed that the log files would only rotate once the file size reaches 5KB.
So my question is - is the minimum log file size for RabbitMQ file-based log rotation 5KB?
I've looked around the web - especially in the rabbitmq documentation site: https://www.rabbitmq.com/logging.html - however there's no mention of any minimimum size.
Here is the sample output of my the settings that I've used:
Test Settings:

[{file, [{file, "rabbit.log"},
              {level, info},
              {date, "$D0"},
              {size, 1024},
              {count, 3}
             ]}
     ]}