问:
Widget Using Constraint Layout
I am Trying to use constraintLayout for my widget but it gave me an error at line #0(Doesn't xml start at line 1?).

Here is the code:

```<code><android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFF"
    android:padding="@dimen/widget_margin">

    <TextView
        android:id="@+id/appwidget_text"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_margin="8dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="#09C"
        android:text="@string/appwidget_text"
        android:textColor="#ffffff"
        android:textSize="24sp"
        android:textStyle="bold|italic"
        android:gravity="center"
        app:layout_constraintBottom_toTopOf="@+id/split2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:contentDescription="@string/appwidget_text"/>

    <Button
        android:id="@+id/flip"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="8dp"
        android:text="@string/show_answer"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/split"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/split2" />

    <Button
        android:id="@+id/next"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:text="@string/next_question"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/split"
        app:layout_constraintTop_toBottomOf="@+id/split2" />

    <android.support.constraint.Guideline
        android:id="@+id/split"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5" />

    <android.support.constraint.Guideline
        android:id="@+id/split2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.75" />

</android.support.constraint.ConstraintLayout>
</code>```

Error:

Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.constraint.ConstraintLayout

Note: I tried it using Linear layout and it worked, but I prefer to do it using constraintLayout.

答: There are only a few View classes that you can use in an app widget. ConstraintLayout is not among them.

Title: Widget Using Constraint Layout

Body:
I am Trying to use constraintLayout for my widget but it gave me an error at line #0(Doesn't xml start at line 1?).

Here is the code:

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFF"
    android:padding="@dimen/widget_margin">

    <TextView
        android:id="@+id/appwidget_text"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_margin="8dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="#09C"
        android:text="@string/appwidget_text"
        android:textColor="#ffffff"
        android:textSize="24sp"
        android:textStyle="bold|italic"
        android:gravity="center"
        app:layout_constraintBottom_toTopOf="@+id/split2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:contentDescription="@string/appwidget_text"/>

    <Button
        android:id="@+id/flip"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="8dp"
        android:text="@string/show_answer"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/split"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/split2" />

    <Button
        android:id="@+id/next"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:text="@string/next_question"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/split"
        app:layout_constraintTop_toBottomOf="@+id/split2" />

    <android.support.constraint.Guideline
        android:id="@+id/split"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5" />

    <android.support.constraint.Guideline
        android:id="@+id/split2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.75" />

</android.support.constraint.ConstraintLayout>

Error:

Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.constraint.ConstraintLayout

Note: I tried it using Linear layout and it worked, but I prefer to do it using constraintLayout.


来源: stackexchange

问:
How do I split template defintion and instantiation into hpp and ipp files
I want to split my template classes into 2 files like how normal classes function with a .hpp where the declaration is and an .ipp where the implementation lives.

I have got this working with normal methods. But with methods that are themselves templates I am facing some issues.

Using the following structure:

```<code>#ifndef MATRIX_HPP
#define MATRIX_HPP

#include <array>
#include <type_traits>

template<typename t,
         std::size_t m,
         std::size_t n>
class Matrix
{

static_assert(std::is_arithmetic<t>::value,
                  "Matrix can only be declared with a type where std::is_arithmetic is true.");
public:
    Matrix();

    template<std::size_t y, std::size_t x, std::size_t p, std::size_t q>
    Matrix<t, p, q> slice() const;

private:
    std::array<std::array<t, n>, m> data{};
};

#include "Matrix.ipp"

#endif
</code>```

Matrix.ipp:

```<code>#include "Matrix.hpp"

template<typename t, std::size_t m, std::size_t n>
Matrix<t, m, n>::Matrix()
{}

template<typename t,
         std::size_t m,
         std::size_t n,
         std::size_t y,
         std::size_t x,
         std::size_t p,
         std::size_t q>
Matrix<t, p, q> Matrix<t, m, n>::slice() const
{
    auto mat = Matrix<t, p, q>();

    for (std::size_t i = y; i < m; i++)
    {
        for (std::size_t j = x; j < n; j++)
        {
            mat[i - y][j - x] = (*this)[i][j];
        }
    }

    return mat;
}
</code>```

main.cpp

```<code>#include "Matrix.hpp"

int main() {
    auto m = Matrix<3, 3, int>();
    auto sliced = m.template slice<1, 1, 2, 2>();

    return 0;
}
</code>```

Now when I compile this it fails with the following message:

```<code>../Matrix.ipp:14:17: error: prototype for ‘Matrix<t, p, q> Matrix<t, m, n>::slice() const’ does not match any in class ‘Matrix<t, m, n>’
 Matrix<t, p, q> Matrix<t, m, n>::slice() const
                 ^~~~~~~~~~~~~~~
In file included from ../main.cpp:0:0:
../Matrix.hpp:20:18: error: candidate is: template<class t, long unsigned int m, long unsigned int n> template<long unsigned int y, long unsigned int x, long unsigned int p, long unsigned int q> Matrix<t, p, q> Matrix<t, m, n>::slice() const
  Matrix<t, p, q> slice() const;
</code>```

I am not sure how to handle this since the compiler won't recognize it. Is there a way to fix this?

I hope somebody can help me. Thanks!

答:
You need to define two sets of template parameters: one for matrix class template, and another for matrix class function, not merging them into one long list:

```<code>template<typename t, std::size_t m, std::size_t n>
template<std::size_t y, std::size_t x, std::size_t p, std::size_t q>
Matrix<t, p, q> Matrix<t, m, n>::slice() const
{
</code>```

Also note that your includes are actually messed up. Including "Matrix.hpp"
into .ipp file won't work because you are already including "Matrix.ipp" from "Matrix.hpp". Though this won't lead to an error.

ContentLicense: CC BY-SA 3.0

Body:
I want to split my template classes into 2 files like how normal classes function with a .hpp where the declaration is and an .ipp where the implementation lives.

I have got this working with normal methods. But with methods that are themselves templates I am facing some issues.

Using the following structure:

#ifndef MATRIX_HPP
#define MATRIX_HPP

#include <array>
#include <type_traits>

template<typename t,
         std::size_t m,
         std::size_t n>
class Matrix
{

static_assert(std::is_arithmetic<t>::value,
                  "Matrix can only be declared with a type where std::is_arithmetic is true.");
public:
    Matrix();

    template<std::size_t y, std::size_t x, std::size_t p, std::size_t q>
    Matrix<t, p, q> slice() const;

private:
    std::array<std::array<t, n>, m> data{};
};

#include "Matrix.ipp"

#endif

Matrix.ipp:

#include "Matrix.hpp"

template<typename t, std::size_t m, std::size_t n>
Matrix<t, m, n>::Matrix()
{}

template<typename t,
         std::size_t m,
         std::size_t n,
         std::size_t y,
         std::size_t x,
         std::size_t p,
         std::size_t q>
Matrix<t, p, q> Matrix<t, m, n>::slice() const
{
    auto mat = Matrix<t, p, q>();

    for (std::size_t i = y; i < m; i++)
    {
        for (std::size_t j = x; j < n; j++)
        {
            mat[i - y][j - x] = (*this)[i][j];
        }
    }

    return mat;
}

main.cpp

#include "Matrix.hpp"

int main() {
    auto m = Matrix<3, 3, int>();
    auto sliced = m.template slice<1, 1, 2, 2>();

    return 0;
}

Now when I compile this it fails with the following message:

../Matrix.ipp:14:17: error: prototype for ‘Matrix<t, p, q> Matrix<t, m, n>::slice() const’ does not match any in class ‘Matrix<t, m, n>’
 Matrix<t, p, q> Matrix<t, m, n>::slice() const
                 ^~~~~~~~~~~~~~~
In file included from ../main.cpp:0:0:
../Matrix.hpp:20:18: error: candidate is: template<class t, long unsigned int m, long unsigned int n> template<long unsigned int y, long unsigned int x, long unsigned int p, long unsigned int q> Matrix<t, p, q> Matrix<t, m, n>::slice() const
  Matrix<t, p, q> slice() const;

I am not sure how to handle this since the compiler won't recognize it. Is there a way to fix this?

I hope somebody can help me. Thanks!

Body:
You need to define two sets of template parameters: one for matrix class template, and another for matrix class function, not merging them into one long list:

template<typename t, std::size_t m, std::size_t n>
template<std::size_t y, std::size_t x, std::size_t p, std::size_t q>
Matrix<t, p, q> Matrix<t, m, n>::slice() const
{

Also note that your includes are actually messed up. Including "Matrix.hpp"
into .ipp file won't work because you are already including "Matrix.ipp" from "Matrix.hpp". Though this won't lead to an error.


问:
(Another) question regarding C loops and data structures
I have a program (who's code is available at the bottom) which generates a list of numbers the way that I want it to. The program works fine as is and does exactly what I want. I'm just not a fan of the way I wrote it. It returns "Segmentation fault" if I change one thing, which I'll say at the bottom as well. Here's the code:

```<code>#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main()
{
    int i,j,k;
    int **dat2, *dat;
    //double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (int*) calloc(nrow, sizeof(int));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }

    // Generates the bonds
    k=2;
    for (i=0; i<nrow; i++) {
        k--;
        for (j=0; j<2; j++) {
            dat2[i][j] = k++;
            if ( ((k%501) == 0) ) {
                k--;
                dat2[i][j] = k++;
                k++;
            }
        }
    }

    FILE *inp2;
    inp2 = fopen("bonds.out", "w");

    for (i=1; i<=nrow; i++)
        fprintf(inp2, "%d %d\n", dat2[i-1][0], dat2[i-1][1]);

    fclose(inp2);

    // Generates the bond ID in the pattern 1 2 3 3 2 1 ... (appropriate for Bond swap!)
    k=1;
    while ( k < nrow ) {
        for (j=0; j<250; j++) {
            dat[k] = (j+1);
            k++;
        }
        for (j=250; j>0; j--) {
            dat[k] = j;
            k++;
        }
    }

    // Scans bonds.out (because just reporting dat2[][] returns segmentation error, not sure why.
    // scans the bonds.out file and stores both values into dm1 and dm2, then reports into 'results.out' file
    int dm1, dm2;

    FILE *inp;
    inp = fopen("input.out", "w");
    inp2 = fopen("bonds.out", "r");

    for (i=1; i<=nrow; i++) {
        fscanf(inp2, "%d %d", &dm1, &dm2);
        fprintf(inp, "%d  %d  %d  %d\n", i, dat[i], dm1, dm2);
    }

    printf("\nDone. All data has been written to \"input.out\"\n");

    fclose(inp2);
    fclose(inp);

    return 0;
}
</code>```

Now, I don't like the fact that it's first writing dat2[][] to a file and then scanning that file for the values. Why, instead, can't I incorporate dat2[][] in the main loop that writes the "results.out" file? If I do so, I get Segmentation fault. For clarification, I mean changing these lines in the code:

```<code>for (i=1; i<=nrow; i++) {
    fscanf(inp2, "%d %d", &dm1, &dm2);
    fprintf(inp, "%d  %d  %d  %d\n", i, dat[i], dm1, dm2);
}
</code>```

To these:

```<code>for (i=1; i<=nrow; i++) {
    fprintf(inp, "%d  %d  %d  %d\n", i, dat[i], dat2[i-1][0], dat2[i-1][1]);
}
</code>```

I'd love an explanation as I'm still very new to C.

Thanks a lot!
Amit

答:
I think you forgot to subtract 1 from the array index of dat, like this:

```<code>for (i=1; i<=nrow; i++) {
  fscanf(inp2, "%d %d", &dm1, &dm2);
  fprintf(inp, "%d  %d  %d  %d\n", i, dat[i-1], dm1, dm2);
}
</code>```

The reason why this causes a segfault is because you're looping until i <= nrow, which will go out of the bounds of dat on the final loop iteration.

ContentLicense: CC BY-SA 2.5

Body:
I have a program (who's code is available at the bottom) which generates a list of numbers the way that I want it to. The program works fine as is and does exactly what I want. I'm just not a fan of the way I wrote it. It returns "Segmentation fault" if I change one thing, which I'll say at the bottom as well. Here's the code:

#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main()
{
    int i,j,k;
    int **dat2, *dat;
    //double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (int*) calloc(nrow, sizeof(int));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }

    // Generates the bonds
    k=2;
    for (i=0; i<nrow; i++) {
        k--;
        for (j=0; j<2; j++) {
            dat2[i][j] = k++;
            if ( ((k%501) == 0) ) {
                k--;
                dat2[i][j] = k++;
                k++;
            }
        }
    }

    FILE *inp2;
    inp2 = fopen("bonds.out", "w");

    for (i=1; i<=nrow; i++)
        fprintf(inp2, "%d %d\n", dat2[i-1][0], dat2[i-1][1]);

    fclose(inp2);

    // Generates the bond ID in the pattern 1 2 3 3 2 1 ... (appropriate for Bond swap!)
    k=1;
    while ( k < nrow ) {
        for (j=0; j<250; j++) {
            dat[k] = (j+1);
            k++;
        }
        for (j=250; j>0; j--) {
            dat[k] = j;
            k++;
        }
    }

    // Scans bonds.out (because just reporting dat2[][] returns segmentation error, not sure why.
    // scans the bonds.out file and stores both values into dm1 and dm2, then reports into 'results.out' file
    int dm1, dm2;

    FILE *inp;
    inp = fopen("input.out", "w");
    inp2 = fopen("bonds.out", "r");

    for (i=1; i<=nrow; i++) {
        fscanf(inp2, "%d %d", &dm1, &dm2);
        fprintf(inp, "%d  %d  %d  %d\n", i, dat[i], dm1, dm2);
    }

    printf("\nDone. All data has been written to \"input.out\"\n");

    fclose(inp2);
    fclose(inp);

    return 0;
}

Now, I don't like the fact that it's first writing dat2[][] to a file and then scanning that file for the values. Why, instead, can't I incorporate dat2[][] in the main loop that writes the "results.out" file? If I do so, I get Segmentation fault. For clarification, I mean changing these lines in the code:

for (i=1; i<=nrow; i++) {
    fscanf(inp2, "%d %d", &dm1, &dm2);
    fprintf(inp, "%d  %d  %d  %d\n", i, dat[i], dm1, dm2);
}

To these:

for (i=1; i<=nrow; i++) {
    fprintf(inp, "%d  %d  %d  %d\n", i, dat[i], dat2[i-1][0], dat2[i-1][1]);
}

I'd love an explanation as I'm still very new to C.

Thanks a lot!
Amit

Body:
I think you forgot to subtract 1 from the array index of dat, like this:

for (i=1; i<=nrow; i++) {
  fscanf(inp2, "%d %d", &dm1, &dm2);
  fprintf(inp, "%d  %d  %d  %d\n", i, dat[i-1], dm1, dm2);
}

The reason why this causes a segfault is because you're looping until i <= nrow, which will go out of the bounds of dat on the final loop iteration.


问:
Unexpected type error with multiplication of two integers in a while loop
I am supposed to implement a Method to my program that multiply all of the integers in the intervall n1,n2. This is my code:

```<code>static int productofIntervall (int n1, int n2){
    int a;
    while(n1 <= n2){
        n1*n2 = a;
        n1=n1++;
    }
    return(a);
}
        public static void main(String[] args){
        System.out.println(productofIntervall(6,11));
    }
</code>```

}

When I try to comply i recieve the error:

```<code>Main.java:6: error: unexpected type
                        (n1)*(n2)=a;
                            ^
  required: variable
  found:    value
1 error
</code>```

Can anybody tell me what`s wrong?
Thanks in advance.

答:
You need to initialize a = 0 and set a = n1*n2 not the other way around. Also n1 = n1++ can and is preferably replaced by just n1++

You are basically setting the product of two numbers to be a value (uninitialized variable) which won't work

Body:
I am supposed to implement a Method to my program that multiply all of the integers in the intervall n1,n2. This is my code:

static int productofIntervall (int n1, int n2){
    int a;
    while(n1 <= n2){
        n1*n2 = a;
        n1=n1++;
    }
    return(a);
}
        public static void main(String[] args){
        System.out.println(productofIntervall(6,11));
    }

}

When I try to comply i recieve the error:

Main.java:6: error: unexpected type
                        (n1)*(n2)=a;
                            ^
  required: variable
  found:    value
1 error

Can anybody tell me what`s wrong?
Thanks in advance.


问:
How to hide Wordpress widget ID programmatically
Based on a particular value(appID) I want to hide one of the widget ID in my wordpress blog.

my widget Id : custom_html-2  ( I got this value from enabling accessibility mode)
( from this url I got widgetID : /wp-admin/widgets.php?widgets-access=on&_wpnonce=0b123456fb2&editwidget=custom_html-2&sidebar=right-sidebar&key=0 )

Here I want to hide custom_html-2  when the value of appID is in.abcd.app .

I just echoed appID , I am getting the value in.abcd.app , but the widget is not getting hidden.

I opened the Sidebar (sidebar.php) in the word press and did modification as bellow. Didnt workout - I am new to wordpress and PHP

```<code><!-- Sidebar -->
<div class="col-lg-4 col-md-4 col-sm-4">

    <aside class="sidebar">

        <?php if ( is_active_sidebar( 'right-sidebar' ) ) : ?>
        <div class="sidebar-widget">

            <?php dynamic_sidebar( 'right-sidebar' ); ?>

            <?php
                <?php $widgets  = get_option('widget'.sidebar-widget); ?>
                $appID =  $_SERVER['HTTP_X_REQUESTED_WITH']
                if ($appID = 'in.abcd.app')
                {
                <?php unset($widgets['custom_html-2']); ?>
            ?>

        </div>
        <?php endif; ?>

    </aside>

</div>
<!-- /end sidebar -->
</code>```

答:
I suppose dynamic_sidebar( 'right-sidebar' ); renders the sidebar and the widgets, so if you unset a widget after the widget was rendered, it's not going to change anything.

Try to put the dynamic_sidebar( 'right-sidebar' ); after the unset part.

Body:
Based on a particular value(appID) I want to hide one of the widget ID in my wordpress blog.

my widget Id : custom_html-2  ( I got this value from enabling accessibility mode)
( from this url I got widgetID : /wp-admin/widgets.php?widgets-access=on&_wpnonce=0b123456fb2&editwidget=custom_html-2&sidebar=right-sidebar&key=0 )

Here I want to hide custom_html-2  when the value of appID is in.abcd.app .

I just echoed appID , I am getting the value in.abcd.app , but the widget is not getting hidden.

I opened the Sidebar (sidebar.php) in the word press and did modification as bellow. Didnt workout - I am new to wordpress and PHP

        <?php if ( is_active_sidebar( 'right-sidebar' ) ) : ?>

            <?php dynamic_sidebar( 'right-sidebar' ); ?>

            <?php
                <?php $widgets  = get_option('widget'.sidebar-widget); ?>
                $appID =  $_SERVER['HTTP_X_REQUESTED_WITH']
                if ($appID = 'in.abcd.app')
                {
                <?php unset($widgets['custom_html-2']); ?>
            ?>

        <?php endif; ?>


问:
SQL query to count all the Projects that contain 2 or more specific topics
I don't know if the title clears everything up so I'm gonna try to explain it here.
So I have a table like this

```<code>Project ID    Project topic
1              topic1
1              topic2
1              topic3
2              topic1
3              topic2
..              ...
</code>```

What I want to do is: Count the number of projects (Project IDs) which contain both topic1 and topic3 for example.
I hope I made the question clear. The solution might be very obvious but somehow I can't figure it out.
Thank You!

答:
```<code>SELECT COUNT(DISTINCT p1.project_id)
  FROM project p1 JOIN
       project p2 ON (p1.project_id = p2.project_id)
 WHERE p1.project_topic = 'topic1'
   AND p2.project_topic = 'topic2';
</code>```

If you wanted topic1 and topic3, then change topic2 to topic3.

Body:
I don't know if the title clears everything up so I'm gonna try to explain it here.
So I have a table like this

Project ID    Project topic
1              topic1
1              topic2
1              topic3
2              topic1
3              topic2
..              ...

What I want to do is: Count the number of projects (Project IDs) which contain both topic1 and topic3 for example.
I hope I made the question clear. The solution might be very obvious but somehow I can't figure it out.
Thank You!

Body:
SELECT COUNT(DISTINCT p1.project_id)
  FROM project p1 JOIN
       project p2 ON (p1.project_id = p2.project_id)
 WHERE p1.project_topic = 'topic1'
   AND p2.project_topic = 'topic2';

If you wanted topic1 and topic3, then change topic2 to topic3.


问:
Dpylr's recode function multiple-to-1 R
I would like an easier way to recode vectors. Specifically I'm wondering if there is a way to pass vectors to a function like dplyr's recode. I understand the basics of quasiquotation but don't quite get how to incorporate the =.

```<code>library(tidyverse)

vec1 <- rep(LETTERS[1:7],7)

#standard way
vec2 <- recode(vec1,
               "A" = "Value1",
               "B" = "Value2",
               "C" = "Value3",
               "D" = "Value4",
               "E" = "Value5",
               "F" = "Value6",
               "G" = "Value7"
               )

vec3 <- recode(vec1,
               "A" = "Value1",
               "B" = "Value1",
               "C" = "Value2",
               "D" = "Value2",
               .default = "Value other"
               )
</code>```

I'd like to do the following

```<code>vec3 <- some.function(vec1,
               c("A", "B") = "Value1",
               c("C", "D") = "Value2",
               .default = "Value other"
               )
</code>```

I have a solution but can't figure out how to incorporate a function with ... and =

```<code>do.call(dplyr::recode,
        c(list(vec1),
        setNames(rep("Value1",length(val1)), val1),
        setNames(rep("Value2",length(val2)), val2)))
</code>```

I also have figured out a way to pass two vectors and rename all the variables.

```<code>recode.by.vectors <- function(x, current.names, new.names){
  do.call(dplyr::recode, c(list(x), setNames(new.names, current.names)))
}
</code>```

Lastly, I'm aware of a base solution.

```<code>vec3 <- vec1
val1 <- c("A", "B")
val2 <- c("C", "D")
vec3[vec1 %in% val1] <- "Value1"
vec3[vec1 %in% val2] <- "Value2"
vec3[!vec1 %in% c(val1,val1)] <- "Value other"
</code>```

but am unaware to how in incorporate the assignment carried out here into a function.

答:
Using the forcats package (also included in the tidyverse package)

```<code>library(forcats)

vec1 <- rep(LETTERS[1:7], 7)

fct_collapse(vec1,
             Value1 = c("A", "B"),
             Value2 = c("C", "D"),
             `Value other` = c("E", "F", "G"))
</code>```

This is a little cumbersome if you have lots of categories to put into Value other, but with a secondary step, you can simplify it a little bit

```<code>fct_collapse(vec1,
             Value1 = c("A", "B"),
             Value2 = c("C", "D")) %>%
  fct_other(keep = c("Value1", "Value2"),
            other_level = "Value other")
</code>```

Title: Dpylr's recode function multiple-to-1 R

Body:
I would like an easier way to recode vectors. Specifically I'm wondering if there is a way to pass vectors to a function like dplyr's recode. I understand the basics of quasiquotation but don't quite get how to incorporate the =.

library(tidyverse)

vec1 <- rep(LETTERS[1:7],7)

#standard way
vec2 <- recode(vec1,
               "A" = "Value1",
               "B" = "Value2",
               "C" = "Value3",
               "D" = "Value4",
               "E" = "Value5",
               "F" = "Value6",
               "G" = "Value7"
               )

vec3 <- recode(vec1,
               "A" = "Value1",
               "B" = "Value1",
               "C" = "Value2",
               "D" = "Value2",
               .default = "Value other"
               )

I'd like to do the following

vec3 <- some.function(vec1,
               c("A", "B") = "Value1",
               c("C", "D") = "Value2",
               .default = "Value other"
               )

I have a solution but can't figure out how to incorporate a function with ... and =

do.call(dplyr::recode,
        c(list(vec1),
        setNames(rep("Value1",length(val1)), val1),
        setNames(rep("Value2",length(val2)), val2)))

I also have figured out a way to pass two vectors and rename all the variables.

recode.by.vectors <- function(x, current.names, new.names){
  do.call(dplyr::recode, c(list(x), setNames(new.names, current.names)))
}

Lastly, I'm aware of a base solution.

vec3 <- vec1
val1 <- c("A", "B")
val2 <- c("C", "D")
vec3[vec1 %in% val1] <- "Value1"
vec3[vec1 %in% val2] <- "Value2"
vec3[!vec1 %in% c(val1,val1)] <- "Value other"

but am unaware to how in incorporate the assignment carried out here into a function.

Body:
Using the forcats package (also included in the tidyverse package)

library(forcats)

vec1 <- rep(LETTERS[1:7], 7)

fct_collapse(vec1,
             Value1 = c("A", "B"),
             Value2 = c("C", "D"),
             `Value other` = c("E", "F", "G"))

This is a little cumbersome if you have lots of categories to put into Value other, but with a secondary step, you can simplify it a little bit

fct_collapse(vec1,
             Value1 = c("A", "B"),
             Value2 = c("C", "D")) %>%
  fct_other(keep = c("Value1", "Value2"),
            other_level = "Value other")


问:
How do I get from a type to the TryParse method?
My particular problem:

I have a string which specifies an aribitrary type in a configuration class

Config.numberType = "System.Foo";

where Foo is a type like Decimal or Double

I use Type.GetType(Config.numberType) to return the corresponding type.

How do I get from that type to being able to use, System.Foo.TryParse() ?

Some further related queries

TryParse() can be accessed from System.Foo.TryParse() as well as foo.TryParse(). Does this mean foo is some kind of class in C#? This seems weird to me that int, double etc are actually not just modifier keywords.

How can you declare variables under these circumstances? - var is not universally usable it seems i.e. only in local scope etc.

答: this may help: http://theengineroom.provoke.co.nz/archive/2007/04/27/generic-tryparse-type-conversion.aspx</p>

OwnerDisplayName: Brendan

OwnerDisplayName: Sebastian Sedlak


问:
How to set an environment variable in Vagrant that PHP can access
I want my local development environment to have an environment variable set so that my PHP app can read it.

In my Vagrantfile I have:

```<code>config.vm.provision "shell", inline: <<-SHELL

    ## Set environment variables...
    echo "export APP_ENV=development" > /home/vagrant/.profile
    echo "export APP_ENV=development" > /home/vagrant/.bashrc
    ...
</code>```

In my PHP code I added:

```<code>var_dump(shell_exec( 'whoami' ));
var_dump(shell_exec( 'echo $APP_ENV' ));
</code>```

The output is:

```<code>string(8) "vagrant "
string(1) " "
</code>```

I remembered to re-provision my box (many times). I'm mostly confused why the second var_dump isn't returning "development" but I'm especially confused why it would return a single space rather than an empty string or NULL if it's not set at all. What am I missing?

Vagrant 1.8.5

Virtualbox 5.1.30r118389

UPDATE:

When I SSH into the box as vagrant user, and run $ echo $APP_ENV, it returns "development".

I added source /home/vagrant/.profile to the provisioning script and PHP still can't see the var I'm setting.

UPDATE2:

I think Apache might be running as www-data. Here's some screenshots from my phpinfo().

答:
Got it! I was modifying /home/vagrant/.profile but Apache is running as www-data so here's what works:

```<code>config.vm.provision "shell", inline: <<-SHELL

    ## Set environment variables...
    echo "export APP_ENV=development" >> /etc/apache2/envvars
    sudo service apache2 restart
    ...
</code>```

I have to restart apache for the changes to take effect. If you restart apache elsewhere in your script you should be able to skip the second line.

Frédéric Henri's answer pointed me in the right direction to figure this out.

NOTE
One problem with the current solution is that it will add a new line to /etc/apache2/envvars every time you provision. So after a few iterations, I see

```<code>export APP_ENV=development
export APP_ENV=development
export APP_ENV=development
</code>```

This is not ideal :-/

Body:
I want my local development environment to have an environment variable set so that my PHP app can read it.

In my Vagrantfile I have:

config.vm.provision "shell", inline: <<-SHELL

    ## Set environment variables...
    echo "export APP_ENV=development" > /home/vagrant/.profile
    echo "export APP_ENV=development" > /home/vagrant/.bashrc
    ...

In my PHP code I added:

var_dump(shell_exec( 'whoami' ));
var_dump(shell_exec( 'echo $APP_ENV' ));

The output is:

string(8) "vagrant "
string(1) " "

I remembered to re-provision my box (many times). I'm mostly confused why the second var_dump isn't returning "development" but I'm especially confused why it would return a single space rather than an empty string or NULL if it's not set at all. What am I missing?

Vagrant 1.8.5

Virtualbox 5.1.30r118389

UPDATE:

When I SSH into the box as vagrant user, and run $ echo $APP_ENV, it returns "development".

I added source /home/vagrant/.profile to the provisioning script and PHP still can't see the var I'm setting.

UPDATE2:

I think Apache might be running as www-data. Here's some screenshots from my phpinfo().

Body:
Got it! I was modifying /home/vagrant/.profile but Apache is running as www-data so here's what works:

config.vm.provision "shell", inline: <<-SHELL

    ## Set environment variables...
    echo "export APP_ENV=development" >> /etc/apache2/envvars
    sudo service apache2 restart
    ...

I have to restart apache for the changes to take effect. If you restart apache elsewhere in your script you should be able to skip the second line.

Frédéric Henri's answer pointed me in the right direction to figure this out.

NOTE
One problem with the current solution is that it will add a new line to /etc/apache2/envvars every time you provision. So after a few iterations, I see

export APP_ENV=development
export APP_ENV=development
export APP_ENV=development

This is not ideal :-/

ContentLicense: CC BY-SA 4.0


问:
Installation of the F# compiler on Windows 10
I followed the directions on http://fsharp.org/use/windows/
option 2
Step 1 ok : VS Code is installed (latest ver)
Step 2 not ok  ext install Ionide-fsharp does not work so installed using extensions in VS Code , found ionide-fsharp installed it ok and followed all instructions on ionidwe-fsharp page

Created a .fs file with the following code;
printfn "Hello World to F# language "

ran code and got:

error FS0193: Could not load file or assembly 'Microsoft.Build.Utilities.Core, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

答:
If you read the option 2 carefully, you will see that it says:

```<code>You will also need to install the free F# compiler and command line tools in Step 4.
</code>```

If you scroll down to option 4, you'll see its suboption A (the simplest) recommends installing Visual Studio Build Tools and selecting F# in the list of components to install.

Since you are only beginning to learn F#, it is very likely that you will return to StackOverflow to ask more questions in the future. When you do, please make sure that your questions are phrased and formatted clearly. In particular, pay attention to punctuation and grammar. Clumsily crafted questions are very hard to understand, and a lot of people will just elect not to answer them at all. By crafting your question carefully, you will increase your chance of getting a useful answer.

For some more specific guidance, refer to How do I ask a good question.

Body:
If you read the option 2 carefully, you will see that it says:

You will also need to install the free F# compiler and command line tools in Step 4.

If you scroll down to option 4, you'll see its suboption A (the simplest) recommends installing Visual Studio Build Tools and selecting F# in the list of components to install.

Since you are only beginning to learn F#, it is very likely that you will return to StackOverflow to ask more questions in the future. When you do, please make sure that your questions are phrased and formatted clearly. In particular, pay attention to punctuation and grammar. Clumsily crafted questions are very hard to understand, and a lot of people will just elect not to answer them at all. By crafting your question carefully, you will increase your chance of getting a useful answer.

For some more specific guidance, refer to How do I ask a good question.


问:
Place IF ELSE statement inside Woocommerce product loop - Wordpress
I've got the following custom shortcode to display a range of products

```<code>add_shortcode( 'my_shortcode_name', 'on_sale_products' );

function on_sale_products() {
global $product, $woocommerce, $woocommerce_loop;

$args = apply_filters('woocommerce_related_products_args', array(
       // this is working array, just empty for this example
       )
);
$products = new WP_Query( $args );

ob_start();

woocommerce_product_loop_start();

while ( $products->have_posts() ) : $products->the_post();

wc_get_template_part( 'content', 'product' );

endwhile;

woocommerce_product_loop_end();

woocommerce_reset_loop();
wp_reset_postdata();

return '<div class="on-sale">' . ob_get_clean() . '</div>';
}
</code>```

I am trying to add a text message inside the loop that will say "No products to display" if there no products to show.

I'm struggling to correctly place the statement without getting a syntax error.

I've been fiddling around with the code like this:

```<code>add_shortcode( 'my_shortcode_name', 'on_sale_products' );

function on_sale_products() {
global $product, $woocommerce, $woocommerce_loop;

$args = apply_filters('woocommerce_related_products_args', array(
       // this is working array, just empty for this example
       )
);
$products = new WP_Query( $args );

ob_start();

woocommerce_product_loop_start();

if ( $products->have_posts() ) : $products->the_post() {

   wc_get_template_part( 'content', 'product' );

} else {

   echo '<div class="no-products">There are no products to display</div>';
}

woocommerce_product_loop_end();

woocommerce_reset_loop();
wp_reset_postdata();

return '<div class="on-sale">' . ob_get_clean() . '</div>';
}
</code>```

But that's not correct.

Could you please point me to the right direction?

答:
2 things:

1) You have removed the while loop.

2) There is an error in this line:

```<code>if ( $products->have_posts() ) : $products->the_post() {
</code>```

It should be instead (in your code):

```<code>if ( $products->have_posts() ) {
    $products->the_post();
</code>```

So the following code, should be the correct way to get this working:

```<code>add_shortcode( 'my_shortcode_name', 'on_sale_products' );
function on_sale_products() {
    global $product, $woocommerce, $woocommerce_loop;

    $products = new WP_Query( apply_filters('woocommerce_related_products_args', array(
       // this is working array, just empty for this example
    ) ) );

    ob_start();
    woocommerce_product_loop_start();

    if ( $products->have_posts() ):
        while ( $products->have_posts() ):
           $products->the_post();
           wc_get_template_part( 'content', 'product' );
        endwhile;
    else:
        echo '<div class="no-products">There are no products to display</div>';
    endif;

    woocommerce_product_loop_end();
    woocommerce_reset_loop();
    wp_reset_postdata();

    return '<div class="on-sale">' . ob_get_clean() . '</div>';
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This should work for you now…

Body:
I've got the following custom shortcode to display a range of products

add_shortcode( 'my_shortcode_name', 'on_sale_products' );

function on_sale_products() {
global $product, $woocommerce, $woocommerce_loop;

$args = apply_filters('woocommerce_related_products_args', array(
       // this is working array, just empty for this example
       )
);
$products = new WP_Query( $args );

ob_start();

woocommerce_product_loop_start();

while ( $products->have_posts() ) : $products->the_post();

wc_get_template_part( 'content', 'product' );

endwhile;

woocommerce_product_loop_end();

woocommerce_reset_loop();
wp_reset_postdata();

return '
' . ob_get_clean() . '
';
}

I am trying to add a text message inside the loop that will say "No products to display" if there no products to show.

I'm struggling to correctly place the statement without getting a syntax error.

I've been fiddling around with the code like this:

add_shortcode( 'my_shortcode_name', 'on_sale_products' );

function on_sale_products() {
global $product, $woocommerce, $woocommerce_loop;

$args = apply_filters('woocommerce_related_products_args', array(
       // this is working array, just empty for this example
       )
);
$products = new WP_Query( $args );

ob_start();

woocommerce_product_loop_start();

if ( $products->have_posts() ) : $products->the_post() {

   wc_get_template_part( 'content', 'product' );

} else {

   echo '
There are no products to display
';
}

woocommerce_product_loop_end();

woocommerce_reset_loop();
wp_reset_postdata();

return '
' . ob_get_clean() . '
';
}

But that's not correct.

Could you please point me to the right direction?

Body:
2 things:

1) You have removed the while loop.

2) There is an error in this line:

if ( $products->have_posts() ) : $products->the_post() {

It should be instead (in your code):

if ( $products->have_posts() ) {
    $products->the_post();

So the following code, should be the correct way to get this working:

add_shortcode( 'my_shortcode_name', 'on_sale_products' );
function on_sale_products() {
    global $product, $woocommerce, $woocommerce_loop;

    $products = new WP_Query( apply_filters('woocommerce_related_products_args', array(
       // this is working array, just empty for this example
    ) ) );

    ob_start();
    woocommerce_product_loop_start();

    if ( $products->have_posts() ):
        while ( $products->have_posts() ):
           $products->the_post();
           wc_get_template_part( 'content', 'product' );
        endwhile;
    else:
        echo '<div class="no-products">There are no products to display</div>';
    endif;

    woocommerce_product_loop_end();
    woocommerce_reset_loop();
    wp_reset_postdata();

    return '<div class="on-sale">' . ob_get_clean() . '</div>';
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This should work for you now…


问:
GridSearchCV gives ValueError: continuous is not supported for DecisionTreeRegressor
I'm learning ML and doing the task for Boston house price predictions. I have following code:

```<code>from sklearn.metrics import fbeta_score, make_scorer
from sklearn.model_selection import GridSearchCV

def fit_model(X, y):
    """ Tunes a decision tree regressor model using GridSearchCV on the input data X
        and target labels y and returns this optimal model. """

    # Create a decision tree regressor object
    regressor = DecisionTreeRegressor()

    # Set up the parameters we wish to tune
    parameters = {'max_depth':(1,2,3,4,5,6,7,8,9,10)}

    # Make an appropriate scoring function
    scoring_function = make_scorer(fbeta_score, beta=2)

    # Make the GridSearchCV object
    reg = GridSearchCV(regressor, param_grid=parameters, scoring=scoring_function)

    print reg
    # Fit the learner to the data to obtain the optimal model with tuned parameters
    reg.fit(X, y)

    # Return the optimal model
    return reg.best_estimator_

reg = fit_model(housing_features, housing_prices)
</code>```

This gives me ValueError: continuous is not supported for the reg.fit(X, y) line and I don't understand why. What is the reason for this, what am I missing here?

答:
That's because of the line:

```<code>scoring_function = make_scorer(fbeta_score, beta=2)
</code>```

This sets the scoring-metric to fbeta, which is for classification tasks!

Your are doing regression here as seen in:

```<code>regressor = DecisionTreeRegressor()
</code>```

From the docs

Body:
I'm learning ML and doing the task for Boston house price predictions. I have following code:

from sklearn.metrics import fbeta_score, make_scorer
from sklearn.model_selection import GridSearchCV

def fit_model(X, y):
    """ Tunes a decision tree regressor model using GridSearchCV on the input data X
        and target labels y and returns this optimal model. """

    # Create a decision tree regressor object
    regressor = DecisionTreeRegressor()

    # Set up the parameters we wish to tune
    parameters = {'max_depth':(1,2,3,4,5,6,7,8,9,10)}

    # Make an appropriate scoring function
    scoring_function = make_scorer(fbeta_score, beta=2)

    # Make the GridSearchCV object
    reg = GridSearchCV(regressor, param_grid=parameters, scoring=scoring_function)

    print reg
    # Fit the learner to the data to obtain the optimal model with tuned parameters
    reg.fit(X, y)

    # Return the optimal model
    return reg.best_estimator_

reg = fit_model(housing_features, housing_prices)

This gives me ValueError: continuous is not supported for the reg.fit(X, y) line and I don't understand why. What is the reason for this, what am I missing here?

Body:
That's because of the line:

scoring_function = make_scorer(fbeta_score, beta=2)

This sets the scoring-metric to fbeta, which is for classification tasks!

Your are doing regression here as seen in:

regressor = DecisionTreeRegressor()

From the docs


问:
I had this error in Eclipse and in Netbeans it works fine
```<code>Exception in thread "main" java.lang.NumberFormatException: For input string: "0000010000000000"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:583)
    at java.lang.Integer.parseInt(Integer.java:615)
    at cmpe363_project.Register.binaryToDecimalHelper(Register.java:163)
    at cmpe363_project.Emulator.startProgram(Emulator.java:103)
    at cmpe363_project.CMPE363_project.main(CMPE363_project.java:27)
</code>```

答:
Your number is larger than Integer.MAX_VALUE which means it simply does not fit into an int.

Use Long.parseLong instead.


答:
You are attempting to read a value that is too big to fit in an integer.

(Max Integer  = 2,147,483,647)  <  (value being read = 10,000,000,000)

Instead of reading the value into an Integer, read the value into a Long

Title: I had this error in Eclipse and in Netbeans it works fine

Body:
Exception in thread "main" java.lang.NumberFormatException: For input string: "0000010000000000"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:583)
    at java.lang.Integer.parseInt(Integer.java:615)
    at cmpe363_project.Register.binaryToDecimalHelper(Register.java:163)
    at cmpe363_project.Emulator.startProgram(Emulator.java:103)
    at cmpe363_project.CMPE363_project.main(CMPE363_project.java:27)


问:
how to find a particular entry from json store using id/name
how to find a particular entry from json store using id/name? using javascript function

for eg:

```<code>var products=[{
    "productId": 101,
    "productName": "Nilkamal Shoe Rack",
    "productPrice": 2223,
    "productOriginalPrice": 2470,
    "productDiscount": "20 %",
    "productColor": "Sandy Brown",
    "productSpecifications": [{
        "Brand": "Nilakamal",
        "Type": "Shoe Rack",
        "Material": "Polypropylene"
    }],
    "productServices": ["Installation and Demo not Required", "10 Days Replacement"]
},

{
    "productId": 102,
    "productName": "Seagate Backup Plus Slim 1TB wired external hard disk",
    "productPrice": 3899,
    "productOriginalPrice": 7450,
    "productDiscount": "47 %",
    "productColor": "White",
    "productSpecifications": [{
        "Brand": "Seagate",
        "Type": "External Hard Disk",
        "Capacity": "1 TB",
        "Connectivity": "USB 3.0",
        "Ports": "1 Port"
    }],
    "productServices": ["3 years warranty", "10 Days Replacement"]
}]
</code>```

How can I find all the details of one of the following product using id/name?

答:
you can simply use array.find like this

```<code> var myObj = products.find(obj => obj.productId == 102);
 console.log(myObj);
</code>```

if you want function then

```<code>function getObjbyId(id){
     var myObj = products.find(obj => obj.productId == id);
     return myObj;
}
</code>```

Body:
how to find a particular entry from json store using id/name? using javascript function

for eg:

var products=[{
    "productId": 101,
    "productName": "Nilkamal Shoe Rack",
    "productPrice": 2223,
    "productOriginalPrice": 2470,
    "productDiscount": "20 %",
    "productColor": "Sandy Brown",
    "productSpecifications": [{
        "Brand": "Nilakamal",
        "Type": "Shoe Rack",
        "Material": "Polypropylene"
    }],
    "productServices": ["Installation and Demo not Required", "10 Days Replacement"]
},

{
    "productId": 102,
    "productName": "Seagate Backup Plus Slim 1TB wired external hard disk",
    "productPrice": 3899,
    "productOriginalPrice": 7450,
    "productDiscount": "47 %",
    "productColor": "White",
    "productSpecifications": [{
        "Brand": "Seagate",
        "Type": "External Hard Disk",
        "Capacity": "1 TB",
        "Connectivity": "USB 3.0",
        "Ports": "1 Port"
    }],
    "productServices": ["3 years warranty", "10 Days Replacement"]
}]

How can I find all the details of one of the following product using id/name?

Body:
you can simply use array.find like this

 var myObj = products.find(obj => obj.productId == 102);
 console.log(myObj);

if you want function then

function getObjbyId(id){
     var myObj = products.find(obj => obj.productId == id);
     return myObj;
}


问:
CSS gradient border not showing correctly
I want to set half blue and orange for border-color of text input.

I tried using a gradient but it doesn't work.

what is my code problem?

.search {
  width: 550px;
  height: 50px;
  margin-left: 350px;
  border-radius: 20px;
  outline: none;
  margin-top: 70px;
  border: solid;
  border-image: linear-gradient(to right, rgb(254, 113, 53) 50%, rgb(55, 154, 214) 50%);
  font-size: 20px;
  text-align: center;
  transition: all 0.2s linear;
}

.search:hover,
.search:focus {
  border: #4cbea5 solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <form method="post">
    <input type="Search" class="search" placeholder="Search">
  </form>
</div></code>```

答:
You need to specify the slice value inside border-image like this :

.search {
  width: 550px;
  height: 50px;
  border-radius: 20px;
  outline: none;
  margin-top: 70px;
  border: solid;
  border-image: linear-gradient(to right, rgb(254, 113, 53) 50%, rgb(55, 154, 214) 50%) 2;
  font-size: 20px;
  text-align: center;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form method="post">
    <input type="Search" class="search" placeholder="Search">
  </form></code>```

You can read more about border-image

By the way, you cannot use border-radius with border-image but you can achive the same using multiple background and by adjusting background-clip. This will also allow you to have the hover behavior:

.search {
  width: 550px;
  height: 50px;
  border-radius: 20px;
  outline: none;
  margin-top: 70px;
  border: 2px solid transparent;
  background:
    linear-gradient(#fff,#fff) content-box,
    linear-gradient(to right, rgb(254, 113, 53) 50%, rgb(55, 154, 214) 50%) border-box;
  font-size: 20px;
  text-align: center;
  transition: all 0.2s linear;
}

.search:hover,
.search:focus {
  border-color:#4cbea5;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form method="post">
    <input type="Search" class="search" placeholder="Search">
  </form></code>```

Related: Border Gradient with Border Radius

Body:
I want to set half blue and orange for border-color of text input.

I tried using a gradient but it doesn't work.

what is my code problem?

.search {
  width: 550px;
  height: 50px;
  margin-left: 350px;
  border-radius: 20px;
  outline: none;
  margin-top: 70px;
  border: solid;
  border-image: linear-gradient(to right, rgb(254, 113, 53) 50%, rgb(55, 154, 214) 50%);
  font-size: 20px;
  text-align: center;
  transition: all 0.2s linear;
}

.search:hover,
.search:focus {
  border: #4cbea5 solid;
}

  <form method="post">
    <input type="Search" class="search" placeholder="Search">
  </form>

Body:
You need to specify the slice value inside border-image like this :

.search {
  width: 550px;
  height: 50px;
  border-radius: 20px;
  outline: none;
  margin-top: 70px;
  border: solid;
  border-image: linear-gradient(to right, rgb(254, 113, 53) 50%, rgb(55, 154, 214) 50%) 2;
  font-size: 20px;
  text-align: center;
 }

<form method="post">
    <input type="Search" class="search" placeholder="Search">
  </form>

You can read more about border-image

By the way, you cannot use border-radius with border-image but you can achive the same using multiple background and by adjusting background-clip. This will also allow you to have the hover behavior:

.search {
  width: 550px;
  height: 50px;
  border-radius: 20px;
  outline: none;
  margin-top: 70px;
  border: 2px solid transparent;
  background:
    linear-gradient(#fff,#fff) content-box,
    linear-gradient(to right, rgb(254, 113, 53) 50%, rgb(55, 154, 214) 50%) border-box;
  font-size: 20px;
  text-align: center;
  transition: all 0.2s linear;
}

.search:hover,
.search:focus {
  border-color:#4cbea5;
}

<form method="post">
    <input type="Search" class="search" placeholder="Search">
  </form>

Related: Border Gradient with Border Radius


问:
Parse double on string giving wrong result
In my project I am getting a string values from an api and need to pass double values to another api. When I try to parse from string values to double I am not getting the original data.

Here is the code.

```<code>String l1="11352721345377306";
String l2="11352721346734307";
String l3="11352721346734308";
String l4="11352721346734309";

DecimalFormat df = new DecimalFormat(".00");

System.out.println(df.format(Double.parseDouble(l1)));
System.out.println(df.format(Double.parseDouble(l2)));
System.out.println(df.format(Double.parseDouble(l3)));
System.out.println(df.format(Double.parseDouble(l4)));
</code>```

The output is

```<code>11352721345377306.00
11352721346734308.00
11352721346734308.00
11352721346734308.00
</code>```

What went wrong? Is there any problem with parsing? How can i get the original values back.?

Edit: Without using Decimal Format:

```<code>1.1352721345377306E16
1.1352721346734308E16
1.1352721346734308E16
1.1352721346734308E16
</code>```

答:
You can use

```<code>double d = Math.round(Double.parse(yourString) * 100.0) / 100.0;
</code>```

to get double with rounded decimals.

For printing use:

```<code>String formatted = String.format("%.2f", yourDouble);
</code>```

Body:
In my project I am getting a string values from an api and need to pass double values to another api. When I try to parse from string values to double I am not getting the original data.

Here is the code.

String l1="11352721345377306";
String l2="11352721346734307";
String l3="11352721346734308";
String l4="11352721346734309";

DecimalFormat df = new DecimalFormat(".00");

System.out.println(df.format(Double.parseDouble(l1)));
System.out.println(df.format(Double.parseDouble(l2)));
System.out.println(df.format(Double.parseDouble(l3)));
System.out.println(df.format(Double.parseDouble(l4)));

The output is

11352721345377306.00
11352721346734308.00
11352721346734308.00
11352721346734308.00

What went wrong? Is there any problem with parsing? How can i get the original values back.?

Edit: Without using Decimal Format:

1.1352721345377306E16
1.1352721346734308E16
1.1352721346734308E16
1.1352721346734308E16

Body:
You can use

double d = Math.round(Double.parse(yourString) * 100.0) / 100.0;

to get double with rounded decimals.

For printing use:

String formatted = String.format("%.2f", yourDouble);


问:
Glide Module Loading url Images In Custom Sizes with paths and any uri handling
I have followed this tutorial where it is declared a custom Glide Module to load different image sizes from server depending on the ImageView size. I have also taken a look to this Glide wiki which explains the same.

But the implementation on the tutorial and the Glide wiki only works if the String you send to the Custom Module is a http/https url. How can I modify this Custom Module or create a new one in order to handle all other types (String, Uri, int, etc as Glide.load() does) and keep the functionality presented in the tutorial?

答:
Instead of registering the new ModelLoader with append(), which handle new types of data, register it using prepend(), which handle subsets of existing data where you do want to fall back to Glide’s default behavior if your ModelLoader fails. So instead of creating the new Glide's input data (in the tutorial named as CustomImageSizeModelFutureStudio), tell Glide, in the case of a String, to check if you want to modify the String and create your url or let Glide do his work without modifying the String. Here is my implementation in Kotlin. In this case, if your input is "https://...." it will request your custom url. If your input is "content://..." your ModelLoader will fail because of the handles() method and Glide will do it's work.

The implementation of AppGlideModule:

```<code>@GlideModule
class MyGlideModule : AppGlideModule() {
    override fun registerComponents(context: Context?, glide: Glide?, registry: Registry?) {
        registry?.prepend(String::class.java, InputStream::class.java, CustomImageSizeUrlLoaderFactory())
    }
}
</code>```

The implementation of ModelLoaderFactory:

```<code>class CustomImageSizeUrlLoaderFactory : ModelLoaderFactory<String, InputStream> {
    private val modelCache = ModelCache<String, GlideUrl>(500)

    override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<String, InputStream> {
        val modelLoader = multiFactory.build(GlideUrl::class.java, InputStream::class.java)
        return CustomImageSizeUrlLoader(modelLoader, modelCache)
    }

    override fun teardown() {

    }
}
</code>```

The implementation of BaseGlideUrlLoader:

```<code>class CustomImageSizeUrlLoader(concreteLoader: ModelLoader<GlideUrl, InputStream>, modelCache: ModelCache<String, GlideUrl>?) : BaseGlideUrlLoader<String>(concreteLoader, modelCache) {
    override fun getUrl(baseImageUrl: String, width: Int, height: Int, options: Options?): String {
        return  baseImageUrl + "?w=" + width + "&h=" + height;
    }

    override fun handles(model: String): Boolean {
        return baseImageUrl.startsWith("http://")
                || baseImageUrl.startsWith("https://")
    }
}
</code>```

And call your Glide as you will normally do, not as the tutorial does.

Body:
Instead of registering the new ModelLoader with append(), which handle new types of data, register it using prepend(), which handle subsets of existing data where you do want to fall back to Glide’s default behavior if your ModelLoader fails. So instead of creating the new Glide's input data (in the tutorial named as CustomImageSizeModelFutureStudio), tell Glide, in the case of a String, to check if you want to modify the String and create your url or let Glide do his work without modifying the String. Here is my implementation in Kotlin. In this case, if your input is "https://...." it will request your custom url. If your input is "content://..." your ModelLoader will fail because of the handles() method and Glide will do it's work.

The implementation of AppGlideModule:

@GlideModule
class MyGlideModule : AppGlideModule() {
    override fun registerComponents(context: Context?, glide: Glide?, registry: Registry?) {
        registry?.prepend(String::class.java, InputStream::class.java, CustomImageSizeUrlLoaderFactory())
    }
}

The implementation of ModelLoaderFactory:

class CustomImageSizeUrlLoaderFactory : ModelLoaderFactory<String, InputStream> {
    private val modelCache = ModelCache<String, GlideUrl>(500)

    override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<String, InputStream> {
        val modelLoader = multiFactory.build(GlideUrl::class.java, InputStream::class.java)
        return CustomImageSizeUrlLoader(modelLoader, modelCache)
    }

    override fun teardown() {

    }
}

The implementation of BaseGlideUrlLoader:

class CustomImageSizeUrlLoader(concreteLoader: ModelLoader<GlideUrl, InputStream>, modelCache: ModelCache<String, GlideUrl>?) : BaseGlideUrlLoader<String>(concreteLoader, modelCache) {
    override fun getUrl(baseImageUrl: String, width: Int, height: Int, options: Options?): String {
        return  baseImageUrl + "?w=" + width + "&h=" + height;
    }

    override fun handles(model: String): Boolean {
        return baseImageUrl.startsWith("http://")
                || baseImageUrl.startsWith("https://")
    }
}

And call your Glide as you will normally do, not as the tutorial does.


问:
delete all folders and files within a linux directory except one folder and all contents inside that folder
I have a directory structure as :-

```<code>/usr/testing/member/
   ---> public--->folder1--->file1
           \----> file2
   ---> folder3:- contains files and folders
   ---> folder4:- contains files and folders
   ---> several files
</code>```

I want to keep the public folder and all its contents (further folders and files within it) but want to delete everything else under the directory /usr/testing/member/. But that also means member folder is not deleted.
Is there any shell script or command that can be used to achieve this exactly as i stated.

答:
Here's one way to do it:

```<code>(cd /usr/testing/member; find . -maxdepth 1 \( ! -name . -a ! -name public \) -exec echo rm -fr {} +)
</code>```

That is: cd into /usr/testing/member, find all files and directories there, without going further below, and exclude the current directory (".") and any file or directory named "public", and execute a command for the found files.

This will print what would be deleted.
Verify it looks good, and then drop the echo.

Body:
I have a directory structure as :-

/usr/testing/member/
   ---> public--->folder1--->file1
           \----> file2
   ---> folder3:- contains files and folders
   ---> folder4:- contains files and folders
   ---> several files

I want to keep the public folder and all its contents (further folders and files within it) but want to delete everything else under the directory /usr/testing/member/. But that also means member folder is not deleted.
Is there any shell script or command that can be used to achieve this exactly as i stated.

Body:
Here's one way to do it:

(cd /usr/testing/member; find . -maxdepth 1 \( ! -name . -a ! -name public \) -exec echo rm -fr {} +)

That is: cd into /usr/testing/member, find all files and directories there, without going further below, and exclude the current directory (".") and any file or directory named "public", and execute a command for the found files.

This will print what would be deleted.
Verify it looks good, and then drop the echo.


问:
Where to find the list of Check IDs for SuppressMessage?
Where can I find the list of Check IDs for SuppressMessage?

The code below is an excerpt from Microsoft online document about SuppressMessageAttribute.CheckId. I want to know the list of valid values for SuppressMessage such as the pair of "Microsoft.Performance" and "CA1804:RemoveUnusedLocals".

```<code>[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "isChecked")]
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "fileIdentifier")]
static void FileNode(string name, bool isChecked)
{
    string fileIdentifier = name;
    string fileName = name;
    string version = String.Empty;
}
</code>```

I want to suppress the warning "Use expression body for methods", but I have no idea as to what values should be given to SuppressMessage.

Code example:

```<code>namespace MyNameSpace
{
    public class MyClass
    {
        // This code raises a warning "Use expression body for methods".
        public string MyMethod()
        {
            return MyPrivateMethod();
        }

        // This code raises a warning "Use expression body for methods".
        string MyPrivateMethod()
        {
            return "Hello";
        }

        // This code raises a warning "Use block body for methods".
        public string MyMethod2() => MyPrivateMethod2();

        // This code raises a warning "Use block body for methods".
        string MyPrivateMethod2() => "Hello";
    }
}
</code>```

Moving the cursor on a method name will display a warning. The behavior prevents the document comment of the method (if any) from being displayed.

Visual Studio Developer Community: IDE0022 missmatch to IDE description

答:
So I am assuming you are talking about the tooltips that VS for Mac shows when you hover over some text and not build warnings.

You can see the list of code rule warnings in the preferences dialog in the Text Editor - Source Analysis - C# section.

If you uncheck a code rule here it should prevent VS for Mac showing a tooltip in the text editor.

Body:
Where can I find the list of Check IDs for SuppressMessage?

The code below is an excerpt from Microsoft online document about SuppressMessageAttribute.CheckId. I want to know the list of valid values for SuppressMessage such as the pair of "Microsoft.Performance" and "CA1804:RemoveUnusedLocals".

[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "isChecked")]
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "fileIdentifier")]
static void FileNode(string name, bool isChecked)
{
    string fileIdentifier = name;
    string fileName = name;
    string version = String.Empty;
}

I want to suppress the warning "Use expression body for methods", but I have no idea as to what values should be given to SuppressMessage.

Code example:

namespace MyNameSpace
{
    public class MyClass
    {
        // This code raises a warning "Use expression body for methods".
        public string MyMethod()
        {
            return MyPrivateMethod();
        }

        // This code raises a warning "Use expression body for methods".
        string MyPrivateMethod()
        {
            return "Hello";
        }

        // This code raises a warning "Use block body for methods".
        public string MyMethod2() => MyPrivateMethod2();

        // This code raises a warning "Use block body for methods".
        string MyPrivateMethod2() => "Hello";
    }
}

Moving the cursor on a method name will display a warning. The behavior prevents the document comment of the method (if any) from being displayed.

Visual Studio Developer Community: IDE0022 missmatch to IDE description


问:
Android Studio emulator missing hardware buttons
I just installed Android Studio 1.0.2 and created a virtual device. When I run an app on the emulator, everything works fine except for the missing hardware buttons (home, menu, and back buttons). I tried to change the Android version of the AVD and the Skin but nothing seems to work.

Does anyone knows how to fix this problem please?

答:
Other answers are kind of deprecated now, because the Android emulator interface changed a little bit.

If you need to display hardware buttons on your Android emulator you have to followe these steps:

Open Android emulator devices

Click "Edit this AVD"

Select the first "Change" button beside the "hardware profile of the AVD"

Click "Edit device..." button

Uncheck this toggle.

Restart your emulator and you should see the hardware buttons now.


问:
crystal reports: set up a dummy parameter as null
I am a novice in Crystal Reports and I need help. I need to set up a parameter as a selection for null value. I, for example, created a dummy parameter called, "No name" and am trying to set it up as a null value in the dataset.

Any suggestions, please?

答:
Once check the link.It shows how to create parameters and add default values like Null
https://kb.blackbaud.com/articles/Article/60683</p>


问:
Swift: Split comma-separated strings, but not if comma enclosed in single quotes
My XML file encodes strings in between single-quotes. Array elements are comma-separated.

'Hello', 'World'

Normally, extracting comma-separated values is easy:

```<code>let result = myString.split{ $0 == "," }.map(String.init)
</code>```

The problem is that I can't recklessly split on the comma: if the comma is enclosed in single quotes it is text, otherwise it is an array element separator:

'Hello', 'World', 'Hello, World'

Should produce:

```<code>["Hello", "World", "Hello, World"]
</code>```

Note two things:

An empty single quotes is an empty string that can't be discarded (it's an element in an array)

I can't guarantee whitespace between the elements; a user may have tampered with a file.

'Hello', 'World'     , 'Hello, World', ''

should produce:

```<code>["Hello", "World", "Hello, World", ""]
</code>```

I need some way to differentiate between a comma-separated value which lies outside of the single quotes: ', ' A better approach would probably be to retain anything in between single-quotes, but I don't know how to do this.

答:
What about separating the string by single quotes and removing elements containing a single comma and a space afterwards?

Note that you should remove the first/last element of the result, since the input starts and ends with a single quote and that produces an empty element after separating.

```<code>var result = myString.components(separatedBy: "'").filter {
    $0.trimmingCharacters(in: .whitespaces) != ","
}

result.removeLast()
result.removeFirst()
</code>```

Body:
My XML file encodes strings in between single-quotes. Array elements are comma-separated.

'Hello', 'World'

Normally, extracting comma-separated values is easy:

let result = myString.split{ $0 == "," }.map(String.init)

The problem is that I can't recklessly split on the comma: if the comma is enclosed in single quotes it is text, otherwise it is an array element separator:

'Hello', 'World', 'Hello, World'

Should produce:

["Hello", "World", "Hello, World"]

Note two things:

An empty single quotes is an empty string that can't be discarded (it's an element in an array)

I can't guarantee whitespace between the elements; a user may have tampered with a file.

'Hello', 'World'     , 'Hello, World', ''

should produce:

["Hello", "World", "Hello, World", ""]

I need some way to differentiate between a comma-separated value which lies outside of the single quotes: ', ' A better approach would probably be to retain anything in between single-quotes, but I don't know how to do this.

Body:
What about separating the string by single quotes and removing elements containing a single comma and a space afterwards?

Note that you should remove the first/last element of the result, since the input starts and ends with a single quote and that produces an empty element after separating.

var result = myString.components(separatedBy: "'").filter {
    $0.trimmingCharacters(in: .whitespaces) != ","
}

result.removeLast()
result.removeFirst()


问:
SOAP Web Service in GlassFish Java EE Application
I have built a SOAP web service using JAX-WS annotations per Java EE guidance.

```<code>@WebService( name = "PersonDataExposureService" )
public class PersonDataExposureWebServiceBean {
...
@WebMethod
public PersonList retrieveAllPeople() { ...
    // get the data and return it ...
}
... more methods ...
}
</code>```

The web service is deployed to GlassFish in a Java EE Application built in NetBeans using the NetBeans wizard.  The application deploys and the UI is rendered and is functional, in the same WAR as the web service.

I am trying to verify the availability of the SOAP web service based upon some examples in the Java EE documentation using...

```<code>http://localhost:8080/DemoApplication-war/PersonDataExposureService?wsdl
</code>```

or

```<code>http://localhost:8080/DemoApplication-war/PersonDataExposureService?retrieveAllPeople
</code>```

where DemoApplication-war is the WAR produced by the NetBeans Java EE wizard.

I am getting an error:

```<code>HTTP Status 404 - Not Found

type Status report

message Not Found

description The requested resource is not available.
</code>```

How can I get the WSDL and web service method to render directly in the browser by accessing the web service directly through the URL?

What am I doing wrong?

答:
Invoking the "Test Web Service" for the PersonDataExposureService node of the "Web Services" section of the navigation tree for the WAR in the NetBeans IDE produces:

```<code>http://localhost:8080/DemoApplication-war/PersonDataExposureWebServiceBeanService?Tester
</code>```

This allows direct testing of the web service interface from the browser.

The WSDL can subsequently be accessed by using:

```<code>http://localhost:8080/DemoApplication-war/PersonDataExposureWebServiceBeanService?wsdl
</code>```

The redirected naming is a little confusing, but it works.  It is not really clear why an additional "Service" is appended to the web service name.  If somebody could provide additional clarification on the generated names, this would be helpful.

Body:
I have built a SOAP web service using JAX-WS annotations per Java EE guidance.

@WebService( name = "PersonDataExposureService" )
public class PersonDataExposureWebServiceBean {
...
@WebMethod
public PersonList retrieveAllPeople() { ...
    // get the data and return it ...
}
... more methods ...
}

The web service is deployed to GlassFish in a Java EE Application built in NetBeans using the NetBeans wizard.  The application deploys and the UI is rendered and is functional, in the same WAR as the web service.

I am trying to verify the availability of the SOAP web service based upon some examples in the Java EE documentation using...

http://localhost:8080/DemoApplication-war/PersonDataExposureService?wsdl

or

http://localhost:8080/DemoApplication-war/PersonDataExposureService?retrieveAllPeople

where DemoApplication-war is the WAR produced by the NetBeans Java EE wizard.

I am getting an error:

HTTP Status 404 - Not Found

type Status report

message Not Found

description The requested resource is not available.

How can I get the WSDL and web service method to render directly in the browser by accessing the web service directly through the URL?

What am I doing wrong?

Body:
Invoking the "Test Web Service" for the PersonDataExposureService node of the "Web Services" section of the navigation tree for the WAR in the NetBeans IDE produces:

http://localhost:8080/DemoApplication-war/PersonDataExposureWebServiceBeanService?Tester

This allows direct testing of the web service interface from the browser.

The WSDL can subsequently be accessed by using:

http://localhost:8080/DemoApplication-war/PersonDataExposureWebServiceBeanService?wsdl

The redirected naming is a little confusing, but it works.  It is not really clear why an additional "Service" is appended to the web service name.  If somebody could provide additional clarification on the generated names, this would be helpful.


问:
Write files to S3 through Java
I have a program which takes input from S3, generates a text file, and then sends it to the mapper class. I am unable to write the file to S3, from where the mapper can read it later. Now, I realize that we cannot write files to S3 directly, so I am trying to upload the text file created to S3 using copyFromLocalFile(). However, I get a null pointer exception in the following line:

fs.copyFromLocalFile(true, new Path(tgiPath), mapIP);

I am creating the text file in main function, so I am not sure where exactly it's being created. The only reason behind the null pointer exception, that I can think of is that the text file is not being written on the local disk. So my question is: How do I write files on the local disk? If I just specify the name of the file while creating it, where is it created and how do I access it?

答:
Have a look at Jets3t

This seems to be exactly what you need.

Title: Write files to S3 through Java


问:
Securing Parquet Files Column-wise
I have been looking for a way to secure Parquet files, column-wise, for Spark access. Ideally, that would work the same way Apache Ranger works for Hive, i.e., a Sysadmin defines the access policies for different groups and columns.

I have been trying Ranger through Hortoworks HDP, however, it seems that plug-ins for Spark and Parquet are not there yet.

I have also been able to devise a solution using Apache Drill and views, however, it is not acceptable right now mainly because of the still scarce community support for Drill.

Has anyone faced the same requirement and/or have some directions for a solution?

答:
After a great deal of research, I've come to a conclusion that this is not possible.

The way Ranger works with other tools (HDFS, Hive, HBase, etc) is by using plug-ins that implements hooks provided by those tools. For instance, to create a custom plug-in to secure Hive, one needs to create a HiveAuthorizer through the HiveAuthorizerFactory. But there's no such a hook for Parquet as it is nothing more than a file format.

A possible solution that would allow to secure Parquet files at a column-wise level from Ranger is to create an extension for Ranger's HDFS plugin. This extension would implement the access rules for Parquet files defined through Ranger. That way, we could seamlessly secure Parquet files the same way we do for Hive or HBase as long as the files are stored in HDFS.

Title: Securing Parquet Files Column-wise


问:
Unable to iterate through String created with Gson
I am trying to iterate through this String that I created using Gson.

```<code>"`{\"public_id\":\"xxxxxx\",\"timestamp\":xxxxx,\"signature\":\"xxxxx\",\"api_key\":\"xxxxxx\"}"`
</code>```

I have tried making this string into a JSONArray and iterating it with Iterator but got of type java.lang.String cannot be converted to JSONArray

This is how I am constructing my String

```<code>Gson gson = new GsonBuilder().create();
String parameter = gson.toJson(newImages.get(i).post_data);
</code>```

What I am trying to achieve is to iterate through the string to eventually add these properties into an okhttp request.

答:
I really can't tell what you are doing, but using gson.toJson() isn't helping. I don't know what post_data is, but it looks like a String, and toJson() seems to be wrapping it in quotes and escaping the quotes inside.

I think what you want to do is to parse post_data. Possibly, post_data is JSON. If so, use gson.fromJson() to parse it into an object. Note that you will have to define the target object with fields that match the JSON structure.

Body:
I am trying to iterate through this String that I created using Gson.

"`{\"public_id\":\"xxxxxx\",\"timestamp\":xxxxx,\"signature\":\"xxxxx\",\"api_key\":\"xxxxxx\"}"`

I have tried making this string into a JSONArray and iterating it with Iterator but got of type java.lang.String cannot be converted to JSONArray

This is how I am constructing my String

Gson gson = new GsonBuilder().create();
String parameter = gson.toJson(newImages.get(i).post_data);

What I am trying to achieve is to iterate through the string to eventually add these properties into an okhttp request.


问:
Make the banner image scale proportionately with the available space in the viewport
I have a banner 900px width and 150px height, if I make the screen smaller then 900px using google chrome, I want it to adjust automatically, like scaling proportionately.
This is the code I am using:

```<code><meta name="viewport" content="width=device-width, initial-scale=1"> .........some other code......

.banner {
  background: silver;
  padding: 20px 0;
  max-width: 100%;
  overflow: auto;
}
</code>```

What would be the suggestions to achieve what I am seeking?

答:
My problem was I was referring only to .banner, it was unclear in instructions.
When I wrote
.banner img {max-width: 100%} it worked. and deleted overflow with maxwidth in .banner.

Body:
I have a banner 900px width and 150px height, if I make the screen smaller then 900px using google chrome, I want it to adjust automatically, like scaling proportionately.
This is the code I am using:

<meta name="viewport" content="width=device-width, initial-scale=1"> .........some other code......

.banner {
  background: silver;
  padding: 20px 0;
  max-width: 100%;
  overflow: auto;
}

What would be the suggestions to achieve what I am seeking?


问:
Applet fails to draw compoents properly after refreshing page in browser
When I wait until java tray icon is gone, everything loads properly!

Java Version: SE 6 Update 22

```<code>public void init()
{

    try
    {
        java.awt.EventQueue.invokeAndWait(new Runnable()
        {

            public void run()
            {
                initComponents();
                invalidate();
                doLayout();

            }
        });
    } catch (Exception ex)
    {
        ex.printStackTrace();
    }
}
</code>```

答:
If your having problems with Chrome, it is better to file a bug:

http://crbug.com/new

Loading / refreshing applets work fine in Chrome 10+

Body:
When I wait until java tray icon is gone, everything loads properly!

Java Version: SE 6 Update 22

public void init()
{

    try
    {
        java.awt.EventQueue.invokeAndWait(new Runnable()
        {

            public void run()
            {
                initComponents();
                invalidate();
                doLayout();

            }
        });
    } catch (Exception ex)
    {
        ex.printStackTrace();
    }
}


问:
I want to reorder an array of strings
I have an array of String ["a", "b", "c", "d"]. My task is to add them to a listView in order like this:

row ==> d

row ==> c d

row ==> b c d

row ==> a b c d

For now I have created an empty String and through a for loop I added an array of items to it by + but problem is if I use this method, the ListView will look like:

row ==> d

row ==> d c

row ==> d c b

row ==> d c b a

This is what I have done:
...

```<code>String arrNaslovi[] = reverse.split(" ");
String deli = "";

for(int i=arrNaslovi.length-1; i>=0; i--) {
    deli += arrNaslovi[i] + " ";
    arrayNaslovi.add(deli);
}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, arrayNaslovi);
    ListView listView = findViewById(R.id.listView);
    listView.setAdapter(adapter);
</code>```

答:
Use a simple approach like this.</p>

```<code>public List<String> myList() {
    String[] a = {"a", "b", "c", "d"};
    //reverse the array
    String[] b = reverse(a).split("");
    String out = "";
    List<String> list1 = new ArrayList<>();
    for (String aB : b) {
        out += aB;
        //reverse it back
        list1.add(reverse(out.split("")));
    }
    return list1;
}

String reverse(String[] string) {
    String out = "";
    for (int i = string.length - 1; i >= 0; i--) {
        if (!string[i].isEmpty())
            out += string[i];
    }
    return out;
}
</code>```

Title: I want to reorder an array of strings

Body:
I have an array of String ["a", "b", "c", "d"]. My task is to add them to a listView in order like this:

row ==> d

row ==> c d

row ==> b c d

row ==> a b c d

For now I have created an empty String and through a for loop I added an array of items to it by + but problem is if I use this method, the ListView will look like:

row ==> d

row ==> d c

row ==> d c b

row ==> d c b a

This is what I have done:
...

String arrNaslovi[] = reverse.split(" ");
String deli = "";

for(int i=arrNaslovi.length-1; i>=0; i--) {
    deli += arrNaslovi[i] + " ";
    arrayNaslovi.add(deli);
}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, arrayNaslovi);
    ListView listView = findViewById(R.id.listView);
    listView.setAdapter(adapter);

Body:
Use a simple approach like this.

public List<String> myList() {
    String[] a = {"a", "b", "c", "d"};
    //reverse the array
    String[] b = reverse(a).split("");
    String out = "";
    List<String> list1 = new ArrayList<>();
    for (String aB : b) {
        out += aB;
        //reverse it back
        list1.add(reverse(out.split("")));
    }
    return list1;
}

String reverse(String[] string) {
    String out = "";
    for (int i = string.length - 1; i >= 0; i--) {
        if (!string[i].isEmpty())
            out += string[i];
    }
    return out;
}


问:
How To Save an Item List in rows in session and display it on the Template in django
Kindly assist with my plight as am still new to django python.

Am developing a shopping cart application, where ajax receives the cart items and send it via POST to View in django

in Django View

```<code> def add_product (request):
     if is_ajax or request.POST:
         productname = request.POST.get('productname','')
         price = request.POST.get('price')
         quantity = request.POST.get('quantity', '')
         cartsession = request.session.get('cartitems', {})
         cartsession[productname] = productname
         cartsession[price] = price
         cartsession[total] = total
         cartsession[quantity] = quantity

         request.session.get('cartitem') = cartsession
         return render(request, 'cartset.html',{'cartsession':cartsession})
</code>```

on Template

```<code>{% for cart in cartsession %}

  { cart.productname}

{% endfor %}
</code>```

After the code above nothing is displaying on the Template page...

Someone pls help

答:
There are multiple issues with your code,

views.py

```<code>cartsession['productname'] = productname
cartsession['price'] = price
</code>```

To display dictionary value by key in template,

```<code>{{ cartsession.price }}
{{ cartsession.productname }}
</code>```

if you want to iterate through dictionary items, use the below code.

```<code>{% for key,value in cartsession.items %}
    {{ key }} : {{ value }}
{% endfor %}
</code>```

Body:
Kindly assist with my plight as am still new to django python.

Am developing a shopping cart application, where ajax receives the cart items and send it via POST to View in django

in Django View

 def add_product (request):
     if is_ajax or request.POST:
         productname = request.POST.get('productname','')
         price = request.POST.get('price')
         quantity = request.POST.get('quantity', '')
         cartsession = request.session.get('cartitems', {})
         cartsession[productname] = productname
         cartsession[price] = price
         cartsession[total] = total
         cartsession[quantity] = quantity

         request.session.get('cartitem') = cartsession
         return render(request, 'cartset.html',{'cartsession':cartsession})

on Template

{% for cart in cartsession %}

  { cart.productname}

{% endfor %}

After the code above nothing is displaying on the Template page...

Someone pls help

Body:
There are multiple issues with your code,

views.py

cartsession['productname'] = productname
cartsession['price'] = price

To display dictionary value by key in template,

{{ cartsession.price }}
{{ cartsession.productname }}

if you want to iterate through dictionary items, use the below code.

{% for key,value in cartsession.items %}
    {{ key }} : {{ value }}
{% endfor %}


问:
SignalR Core can't connect from JS client

I'm following this guide from MS. I created an MVC Core 2.0 app and added the package reference

```<code><PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.0.0-alpha1-final" />
</code>```

I configured the Startup.cs

```<code>    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddSignalR();
    }
</code>```

and

```<code> public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        ...
        app.UseSignalR(routes =>
        {
            routes.MapHub<Statistics>("statistics");
        });

       ...
    }
</code>```

Here is my StatisticsHub:

```<code>public class Statistics : Hub
{
    public Task Send(string message)
    {
        return Clients.All.InvokeAsync("Send", message);
    }
}
</code>```

From my HomeController I have an Index action which returns this view:

```<code><script src="js/signalr-client-1.0.0-alpha2-final.js"></script>

<script>
    let connection = new signalR.HubConnection('/statistics');

    connection.on('send', data => {
        console.log(data);
    });

    connection.start()
        .then(() => connection.invoke('send', 'Hello'));
</script>
</code>```

I also tried to include the
 client but there's no difference.

I start the app, firefox boots up and this is what happens in the console:
Errors

I followed the guide step by step and I don't know why it doesn't connect.

答:
Try the following

```<code>[HubName("Statistics")]
public class Statistics : Hub
{
    public Task Send(string message)
    {
        return Clients.All.InvokeAsync("Send", message);
    }
}
</code>```

Script

```<code><script>
        $.connection.hub.url = "http://localhost:xxxx/signalr";
        var statisticsHub = $.connection.Statistics;
    </script>
</code>```

Or

```<code><script>
    let connection = new signalR.HubConnection('http://localhost:xxxx');

    connection.on('send', data => {
        console.log(data);
    });

    connection.start()
        .then(() => connection.invoke('send', 'Hello'));
</script>
</code>```

Where "xxxx: is the port number

Body:
I'm following this guide from MS. I created an MVC Core 2.0 app and added the package reference

<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.0.0-alpha1-final" />

I configured the Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddSignalR();
    }

and

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        ...
        app.UseSignalR(routes =>
        {
            routes.MapHub<Statistics>("statistics");
        });

       ...
    }

Here is my StatisticsHub:

public class Statistics : Hub
{
    public Task Send(string message)
    {
        return Clients.All.InvokeAsync("Send", message);
    }
}

From my HomeController I have an Index action which returns this view:

I also tried to include the
 client but there's no difference.

I start the app, firefox boots up and this is what happens in the console:
Errors

I followed the guide step by step and I don't know why it doesn't connect.

Body:
Try the following

[HubName("Statistics")]
public class Statistics : Hub
{
    public Task Send(string message)
    {
        return Clients.All.InvokeAsync("Send", message);
    }
}

Script

<script>
        $.connection.hub.url = "http://localhost:xxxx/signalr";
        var statisticsHub = $.connection.Statistics;
    </script>

Or

<script>
    let connection = new signalR.HubConnection('http://localhost:xxxx');

    connection.on('send', data => {
        console.log(data);
    });

    connection.start()
        .then(() => connection.invoke('send', 'Hello'));
</script>

Where "xxxx: is the port number


问:
Create a nnModule that's just the identity

I'm trying to debug a pretty complex interaction between different nnModules. It would be very helpful for me to be able to replace one of them with just an identity network for debugging purposes. For example:

net_a = NetworkA()
net_b = NetworkB()
net_c = NetworkC()

input = Autograd.Variable(torch.rand(10,2))

out = net_a(input)
out = net_b(out)
out = net_c(out)
```

<p>I would like to be able to just change the second line to <code>net_b = IdentityNet()</code>, instead of having to go through and reconnect all my As to Cs. But, when I make a completely empty nnModule, the optimizer throws <code>ValueError: optimizer got an empty parameter list</code>.</p>

<p>Is there any workaround this? </p>

<p>A minimum non-working example:</p>

<pre class="lang-py prettyprint-override"><code>import torch.optim as optim

class IdentityModule(nnModule):
    def forward(self, inputs):
        return inputs

identity = IdentityModule()
opt = optim.Adam(identity, lr=0.001)
out = identity(any_tensor)
error = torch.mean(out)
error.backward()
opt.step()
</code>```

答:
The problem you encounter here is a logical one. Look at what it means when you do:

error.backward()
opt.step()
```

<p><code>.backward()</code> will recursively compute the gradients from your output to any input you pass into the network. In terms of the computation graph, there are two noteworthy kinds of inputs: the input you pass in, and the <code>nn.Parameter</code>s that model the network's behavior. When you then do <code>opt.step()</code>, PyTorch will look for any input that it can update to change the output of the network, namely the <code>nn.Parameters()</code>.</p>

<p>However, your Pseudo-code <em>does not have a single <code>nn.Parameter</code>!</em>, since the identity module does not contain one. So when you call these functions, the <code>opt.step()</code> has no targets, explaining the error message.</p>

<p>This does not extend to the case you describe earlier. If you chain a module with no parameters into a larger chain with some that do have parameters, there are parameters to train in the computation graph. </p>

<p>You need to make sure, though, that the optimizer indeed gets all of these parameters passed upon initialization. A simple trick is to print these:</p>

<pre class="lang-py prettyprint-override"><code>net_a = SomeNetwork()
net_b = IdentityNetwork()  # has no parameters
net_c = SomeNetwork()

print(list(net_a.parameters()))  # will contain whatever parameters in net_a
print(list(net_b.parameters()))  # will be []
print(list(net_c.parameters()))  # will contain whatever parameters in net_c
# to train all of them, you can do one of two things:
# 1. create new module. This works, since `.parameters()` collects params recursively from all submodules.
class NewNet(nn.Module):
    def __init__(self):
        nn.Module.__init__(self)
        self.net_a = net_a
        self.net_b = identity
        self.net_c = net_c

    def forward(self, input):
        return self.net_c(self.net_b(self.net_a(input)))
all_parameters = list(NewNet().parameters())
print(all_parameters)  # will contain a list of all parameters of net_a and net_c

# 2. simply merge the lists
all_parameters = list(net_a.parameters()) + list(net_b.parameters()) + list(net_c.parameters())
print(all_parameters)  # will contain a list of all parameters of net_a and net_c

opt = optim.SGD(all_parameters)
</code>```

Body:
I'm trying to debug a pretty complex interaction between different nnModules. It would be very helpful for me to be able to replace one of them with just an identity network for debugging purposes. For example:

net_a = NetworkA()
net_b = NetworkB()
net_c = NetworkC()

input = Autograd.Variable(torch.rand(10,2))

out = net_a(input)
out = net_b(out)
out = net_c(out)

I would like to be able to just change the second line to net_b = IdentityNet(), instead of having to go through and reconnect all my As to Cs. But, when I make a completely empty nnModule, the optimizer throws ValueError: optimizer got an empty parameter list.

Is there any workaround this?

A minimum non-working example:

import torch.optim as optim

class IdentityModule(nnModule):
    def forward(self, inputs):
        return inputs

identity = IdentityModule()
opt = optim.Adam(identity, lr=0.001)
out = identity(any_tensor)
error = torch.mean(out)
error.backward()
opt.step()

Body:
The problem you encounter here is a logical one. Look at what it means when you do:

error.backward()
opt.step()

.backward() will recursively compute the gradients from your output to any input you pass into the network. In terms of the computation graph, there are two noteworthy kinds of inputs: the input you pass in, and the nn.Parameters that model the network's behavior. When you then do opt.step(), PyTorch will look for any input that it can update to change the output of the network, namely the nn.Parameters().

However, your Pseudo-code does not have a single nn.Parameter!, since the identity module does not contain one. So when you call these functions, the opt.step() has no targets, explaining the error message.

This does not extend to the case you describe earlier. If you chain a module with no parameters into a larger chain with some that do have parameters, there are parameters to train in the computation graph.

You need to make sure, though, that the optimizer indeed gets all of these parameters passed upon initialization. A simple trick is to print these:

net_a = SomeNetwork()
net_b = IdentityNetwork()  # has no parameters
net_c = SomeNetwork()

print(list(net_a.parameters()))  # will contain whatever parameters in net_a
print(list(net_b.parameters()))  # will be []
print(list(net_c.parameters()))  # will contain whatever parameters in net_c
# to train all of them, you can do one of two things:
# 1. create new module. This works, since `.parameters()` collects params recursively from all submodules.
class NewNet(nn.Module):
    def __init__(self):
        nn.Module.__init__(self)
        self.net_a = net_a
        self.net_b = identity
        self.net_c = net_c

    def forward(self, input):
        return self.net_c(self.net_b(self.net_a(input)))
all_parameters = list(NewNet().parameters())
print(all_parameters)  # will contain a list of all parameters of net_a and net_c

# 2. simply merge the lists
all_parameters = list(net_a.parameters()) + list(net_b.parameters()) + list(net_c.parameters())
print(all_parameters)  # will contain a list of all parameters of net_a and net_c

opt = optim.SGD(all_parameters)


问:
How do I formally document a C# Attribute in UML?
What is the proper way to document a C# Attribute on a class in a UML class diagram?</p>

答:
I haven't decided if this is my answer, but I figured I'd throw it out there for sake of discussion.  Does this look acceptable?

Its an instance of the attribute type with the metadata values put into tagged values below.  I just figured out how to add custom stereo types. The arrow is just a dependency arrow that is labeled as "applies".