问:
Assign a div name to a variable in jQuery
Does anyone know why $bz_div.length < 1 or $bz_div.remove() don't work while $('#bz-ph').length < 1 or $('#bz-ph').remove() do?

Can't I assign a div name like $('#bz-ph') to a variable?

```<code>var show = function (options) {
    var $gallery    = $('#gallery');
    var $img        = $('.bz-img');
    var $bz_div     = $('#bz-ph');

    $img.click(function () {
        var $img_path   = $(this).data('image');
        print($bz_div.length);
        /* Prevents: double click = double gallery layer */
        if ($bz_div.length < 1) {
            $gallery.append(output(options, $img_path));
        } else {
            $bz_div.remove();
        }
    });
};
</code>```

答:
When you do this $('#bz-ph'), you're getting the object in dom by jquery. It's a shortcut to document.getElementById("bz-ph").

To assign a div to a variable, you can do something like this.

```<code>var obj = $('#bz-ph');
$(obj).fadeOut();
</code>```

Body:
Does anyone know why $bz_div.length < 1 or $bz_div.remove() don't work while $('#bz-ph').length < 1 or $('#bz-ph').remove() do?

Can't I assign a div name like $('#bz-ph') to a variable?

var show = function (options) {
    var $gallery    = $('#gallery');
    var $img        = $('.bz-img');
    var $bz_div     = $('#bz-ph');

    $img.click(function () {
        var $img_path   = $(this).data('image');
        print($bz_div.length);
        /* Prevents: double click = double gallery layer */
        if ($bz_div.length < 1) {
            $gallery.append(output(options, $img_path));
        } else {
            $bz_div.remove();
        }
    });
};

Body:
When you do this $('#bz-ph'), you're getting the object in dom by jquery. It's a shortcut to document.getElementById("bz-ph").

To assign a div to a variable, you can do something like this.

var obj = $('#bz-ph');
$(obj).fadeOut();


来源: stackexchange

问:
HttpResponse does not contain a definition for AddHeader for Dot Net Core
When moving a project into .Net Core, AddHeader throws an error:

Error CS1061  'HttpResponse' does not contain a definition for
  'AddHeader' and no extension method 'AddHeader' accepting a first
  argument of type 'HttpResponse' could be found (are you missing a
  using directive or an assembly reference?)    .NETCoreApp,Version=v1.0

答:
Checkout

Examples:

```<code>string combineValue = httpContext.Request.Headers["header1];
if (string.IsNullOrEmpty(combineValue)) // ...
var values = httpContext.Request.Headers["header1"];
if (StringValues.IsNullOrEmpty(values)) // ...
httpContext.Response.Headers["CustomHeader1"] = "singleValue";
httpContext.Response.Headers["CustomHeader2"] =  new[] { "firstValue", "secondValue" };
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Checkout

Examples:

string combineValue = httpContext.Request.Headers["header1];
if (string.IsNullOrEmpty(combineValue)) // ...
var values = httpContext.Request.Headers["header1"];
if (StringValues.IsNullOrEmpty(values)) // ...
httpContext.Response.Headers["CustomHeader1"] = "singleValue";
httpContext.Response.Headers["CustomHeader2"] =  new[] { "firstValue", "secondValue" };


问:
Why Maven dependency exclusion would not cause compile error?
Newly exposed to Maven, I can understand the use case of the <exclusion> tag, but not sure why it wouldn't cause compile error:

```<code><dependencies>
<dependency>
  <groupId>org.apache.maven</groupId>
  <artifactId>maven-embedder</artifactId>
  <version>2.0</version>
  <exclusions>
    <exclusion>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-core</artifactId>
    </exclusion>
  </exclusions>
</dependency>
...
</code>```

Is this only possible only when you have another direct dependency on maven-core? otherwise, compile error should happen. (assuming maven-core is used somewhere in maven-embedder)

答:
There are different possibilities:

As Carl said: Check your dependency:tree if the dependency is not pulled in from somewhere else.

It is possible that maven-core is not used at all, even if maven-embedder indeed uses it: Assume e.g. that maven-embedder has two classes A and B. You only use A, but maven-core is only used by B. Then (if A and B do not use each other), your project might be entirely independent of maven-core. (A side remark: some jars should logically be two separate jars, but where merged together by whatever reason - in our example, one should think about putting A and B in separate artifacts).

It is possible that transitive dependencies are not necessary at compile time, but are used at runtime.

Body:
Newly exposed to Maven, I can understand the use case of the <exclusion> tag, but not sure why it wouldn't cause compile error:

<dependencies>
<dependency>
  <groupId>org.apache.maven</groupId>
  <artifactId>maven-embedder</artifactId>
  <version>2.0</version>
  <exclusions>
    <exclusion>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-core</artifactId>
    </exclusion>
  </exclusions>
</dependency>
...

Is this only possible only when you have another direct dependency on maven-core? otherwise, compile error should happen. (assuming maven-core is used somewhere in maven-embedder)


问:
Android Mocking a Dagger2 injected dependency for a Espresso test
I have a heavily dependency injected (dagger2) application. I would like to run an espresso test without having the test navigate through the whole application, and log into the application.

I would like to start on my teleActivity, and mock the login manager. However in any @test function, we have already hit the null pointer as we have called onCreate. If I override it before we launch the activity (show below) the activity is null.

To my understanding, the ability to switch our underlining dependencies is a large reason why we use Dagger2, else it would be just a very over engineered singleton. How do I override, mock, or switch the injection to a testing dagger module -- so I can create this simple espresso test.

Note I also wrote all this in the MVP design pattern if that makes a difference.

TeleActivity

```<code>@Inject
TelePresenter mTelePresenter;
@Inject
public LoginStateManager mLoginStateManager;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
    DaggerInjectorTele.get().inject(this);
    mTelePresenter.setTeleDependencies(this);
    Intent intent = getIntent();

    String searchId = null;

    if (intent != null) {
        searchId = intent.getStringExtra(Constants.SEARCH_ID);
       }

    mTelePresenter.onCreateEvent(searchId,
            Helper.makeAuthorizationHeader(
            // CRASH Null pointer
            mLoginStateManager.getBaseLoginResponse().getAccessToken()));

}
</code>```

Espresso

```<code>@LargeTest
@RunWith(AndroidJUnit4.class)
public class TeleTest {
    @Rule
    public ActivityTestRule<TeleActivity> mActivityTestRule = new ActivityTestRule(
            TeleActivity.class) {
        @Override
        protected void beforeActivityLaunched() {
            super.beforeActivityLaunched();
            TeleActivity teleActivity = (TeleActivity)getActivity();
             //teleActivity NULL!
            teleActivity.mLoginStateManager = mock(LoginStateManager.class);
            LoginResponse loginResponse = mock(LoginResponse.class);
            when(loginResponse.getAccessToken()).thenReturn("1234");
            // Nope here still null

when(teleActivity.mLoginStateManager.getBaseLoginResponse()).thenReturn(loginResponse);

        }
    };
</code>```

Dagger Injector

```<code>  public class DaggerInjectorTele {
    private static TelePresenterComponent telePresenterComponent =
            DaggerTelePresenterComponent.builder().build();

    public static TelePresenterComponent get() {
        return telePresenterComponent;
    }
}
</code>```

TelePresenterComponent

```<code>@Singleton
@Component(modules = {TelePresenterModule.class,
        LoginStateManagerModule.class})
public interface TelePresenterComponent {
    void inject(TeleActivity activity);
}
</code>```

TelePresenterModule

```<code>@Module
public class TelePresenterModule {

    @Provides
    @Singleton
    public TelePresenter getTelePresenter() {
        return new TelePresenter();
    }
}
</code>```

LoginStateManagerModule

```<code>@Module
public class LoginStateManagerModule {

    @Provides
    @Singleton
    public LoginStateManager getLoginStateManager(){
        return new LoginStateManager();
    }
}
</code>```

答:
there is no value set in

LoginStateManager

so when you build the component you get both   TelePresenter Dependency and LoginStateManager dependency
but no values set in member variables of the both .So i think you need to set the values of member variables before accessing them.

```<code>getBaseLoginResponse().getAccessToken())
</code>```

the above line of code is giving you null because you haven't set the value .So before accessing it you need to set the values first

Body:
I have a heavily dependency injected (dagger2) application. I would like to run an espresso test without having the test navigate through the whole application, and log into the application.

I would like to start on my teleActivity, and mock the login manager. However in any @test function, we have already hit the null pointer as we have called onCreate. If I override it before we launch the activity (show below) the activity is null.

To my understanding, the ability to switch our underlining dependencies is a large reason why we use Dagger2, else it would be just a very over engineered singleton. How do I override, mock, or switch the injection to a testing dagger module -- so I can create this simple espresso test.

Note I also wrote all this in the MVP design pattern if that makes a difference.

TeleActivity

@Inject
TelePresenter mTelePresenter;
@Inject
public LoginStateManager mLoginStateManager;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
    DaggerInjectorTele.get().inject(this);
    mTelePresenter.setTeleDependencies(this);
    Intent intent = getIntent();

    String searchId = null;

    if (intent != null) {
        searchId = intent.getStringExtra(Constants.SEARCH_ID);
       }

    mTelePresenter.onCreateEvent(searchId,
            Helper.makeAuthorizationHeader(
            // CRASH Null pointer
            mLoginStateManager.getBaseLoginResponse().getAccessToken()));

}

Espresso

@LargeTest
@RunWith(AndroidJUnit4.class)
public class TeleTest {
    @Rule
    public ActivityTestRule<TeleActivity> mActivityTestRule = new ActivityTestRule(
            TeleActivity.class) {
        @Override
        protected void beforeActivityLaunched() {
            super.beforeActivityLaunched();
            TeleActivity teleActivity = (TeleActivity)getActivity();
             //teleActivity NULL!
            teleActivity.mLoginStateManager = mock(LoginStateManager.class);
            LoginResponse loginResponse = mock(LoginResponse.class);
            when(loginResponse.getAccessToken()).thenReturn("1234");
            // Nope here still null

when(teleActivity.mLoginStateManager.getBaseLoginResponse()).thenReturn(loginResponse);

        }
    };

Dagger Injector

  public class DaggerInjectorTele {
    private static TelePresenterComponent telePresenterComponent =
            DaggerTelePresenterComponent.builder().build();

    public static TelePresenterComponent get() {
        return telePresenterComponent;
    }
}

TelePresenterComponent

@Singleton
@Component(modules = {TelePresenterModule.class,
        LoginStateManagerModule.class})
public interface TelePresenterComponent {
    void inject(TeleActivity activity);
}

TelePresenterModule

@Module
public class TelePresenterModule {

    @Provides
    @Singleton
    public TelePresenter getTelePresenter() {
        return new TelePresenter();
    }
}

LoginStateManagerModule

@Module
public class LoginStateManagerModule {

    @Provides
    @Singleton
    public LoginStateManager getLoginStateManager(){
        return new LoginStateManager();
    }
}

Body:
there is no value set in

LoginStateManager

so when you build the component you get both   TelePresenter Dependency and LoginStateManager dependency
but no values set in member variables of the both .So i think you need to set the values of member variables before accessing them.

getBaseLoginResponse().getAccessToken())

the above line of code is giving you null because you haven't set the value .So before accessing it you need to set the values first


问:
Why is C array so much faster than std::array?
We are currently writing some performance critical code in C++ that operates on many large matrices and vectors. Regarding to our research, there should be no major performance difference between std::array and standard C arrays
(See This question or this).
However, while testing we experienced a huge performance improvement by using C arrays over std::array.
This is our demo code:

```<code>#include <iostream>
#include <array>
#include <sys/time.h>

#define ROWS 784
#define COLS 100
#define RUNS 50

using std::array;

void DotPComplex(array<double, ROWS> &result, array<double, ROWS> &vec1, array<double, ROWS> &vec2){
  for(int i = 0; i < ROWS; i++){
    result[i] = vec1[i] * vec2[i];
  }
}

void DotPSimple(double result[ROWS], double vec1[ROWS], double vec2[ROWS]){
  for(int i = 0; i < ROWS; i++){
    result[i] = vec1[i] * vec2[i];
  }
}

void MatMultComplex(array<double, ROWS> &result, array<array<double, COLS>, ROWS> &mat, array<double, ROWS> &vec){
  for (int i = 0; i < COLS; ++i) {
      for (int j = 0; j < ROWS; ++j) {
        result[i] += mat[i][j] * vec[j];
      }
  }
}

void MatMultSimple(double result[ROWS], double mat[ROWS][COLS], double vec[ROWS]){
  for (int i = 0; i < COLS; ++i) {
      for (int j = 0; j < ROWS; ++j) {
        result[i] += mat[i][j] * vec[j];
      }
  }
}

double getTime(){
    struct timeval currentTime;
    gettimeofday(&currentTime, NULL);
    double tmp = (double)currentTime.tv_sec * 1000.0 + (double)currentTime.tv_usec/1000.0;
    return tmp;
}

array<double, ROWS> inputVectorComplex = {{ 0 }};
array<double, ROWS> resultVectorComplex = {{ 0 }};
double inputVectorSimple[ROWS] = { 0 };
double resultVectorSimple[ROWS] = { 0 };

array<array<double, COLS>, ROWS> inputMatrixComplex = {{0}};
double inputMatrixSimple[ROWS][COLS] = { 0 };

int main(){
  double start;
  std::cout << "DotP test with C array: " << std::endl;
  start = getTime();
  for(int i = 0; i < RUNS; i++){
    DotPSimple(resultVectorSimple, inputVectorSimple, inputVectorSimple);
  }
  std::cout << "Duration: " << getTime() - start << std::endl;

  std::cout << "DotP test with C++ array: " << std::endl;
  start = getTime();
  for(int i = 0; i < RUNS; i++){
    DotPComplex(resultVectorComplex, inputVectorComplex, inputVectorComplex);
  }
  std::cout << "Duration: " << getTime() - start << std::endl;

  std::cout << "MatMult test with C array : " << std::endl;
  start = getTime();
  for(int i = 0; i < RUNS; i++){
    MatMultSimple(resultVectorSimple, inputMatrixSimple, inputVectorSimple);
  }
  std::cout << "Duration: " << getTime() - start << std::endl;

  std::cout << "MatMult test with C++ array: " << std::endl;
  start = getTime();
  for(int i = 0; i < RUNS; i++){
    MatMultComplex(resultVectorComplex, inputMatrixComplex, inputVectorComplex);
  }
  std::cout << "Duration: " << getTime() - start << std::endl;
}
</code>```

Compiled with: icpc demo.cpp -std=c++11 -O0
This is the result:

```<code>DotP test with C array:
Duration: 0.289795 ms
DotP test with C++ array:
Duration: 1.98413 ms
MatMult test with C array :
Duration: 28.3459 ms
MatMult test with C++ array:
Duration: 175.15 ms
</code>```

With -O3 flag:

```<code>DotP test with C array:
Duration: 0.0280762 ms
DotP test with C++ array:
Duration: 0.0288086 ms
MatMult test with C array :
Duration: 1.78296 ms
MatMult test with C++ array:
Duration: 4.90991 ms
</code>```

The C array implementation is much faster without compiler optimization. Why?
Using compiler optimizations the dot products are equally fast. But for the matrix multiplication there is still a significant speedup when using C arrays.
Is there a way to achieve equal performance when using std::array?

Update:

The compiler used: icpc 17.0.0

With gcc 4.8.5 our code runs much slower than with the intel compiler using any optimization level. Therefore we are mainly interested in the behaviour of the intel compiler.

As suggested by Jonas we adjusted RUNS 50.000 with the following results (intel compiler):

With -O0 flag:

```<code>DotP test with C array:
Duration: 201.764 ms
DotP test with C++ array:
Duration: 1020.67 ms
MatMult test with C array :
Duration: 15069.2 ms
MatMult test with C++ array:
Duration: 123826 ms
</code>```

With -O3 flag:

```<code>DotP test with C array:
Duration: 16.583 ms
DotP test with C++ array:
Duration: 15.635 ms
MatMult test with C array :
Duration: 980.582 ms
MatMult test with C++ array:
Duration: 2344.46 ms
</code>```

答:
why ... is much faster without compiler optimization. Why?

For whatever reason the compiler chooses. If you don't let the compiler optimize, then you cannot expect two different pieces of code to have similar performance, even if they have identical behaviour. When optimization is enabled, the compiler may be able to transform the abstracted code into the efficient one, and the performance should be comparable.

The use of std::array involves function calls where the use of a pointer does not. For example, std::array::operator[] is a function, while the subscript operator of a pointer is not. Making a function call is potentially slower than not making a function call. All those function calls can be optimized away (expanded inline), but if you choose to not enable optimization, then the function calls remain.

But for the matrix multiplication there is still a significant speedup when using C arrays.

Probably a quirk in your benchmark, or the compiler. Here both functions have identical assembly, and so have identical performance

EDIT: I concur with Jonas' answer. The benchmark has way too few iterations. Also, it is not possible to say whether the difference between two measurements is significant without repeating the benchmark, and analysing the deviation.

The conclusios are:

The C array is not faster than std::array when optimization is enabled. At least not when compiling with clang 3.9.1 as demonstrated by the link. Perhaps your compiler produces different assembly, but I see no reason why it should.

The zero cost abstractions of C++ are zero cost only after optimization.

Writing meaningful micro benchmarks is not trivial.

Body:
We are currently writing some performance critical code in C++ that operates on many large matrices and vectors. Regarding to our research, there should be no major performance difference between std::array and standard C arrays
(See This question or this).
However, while testing we experienced a huge performance improvement by using C arrays over std::array.
This is our demo code:

#include <iostream>
#include <array>
#include <sys/time.h>

#define ROWS 784
#define COLS 100
#define RUNS 50

using std::array;

void DotPComplex(array<double, ROWS> &result, array<double, ROWS> &vec1, array<double, ROWS> &vec2){
  for(int i = 0; i < ROWS; i++){
    result[i] = vec1[i] * vec2[i];
  }
}

void DotPSimple(double result[ROWS], double vec1[ROWS], double vec2[ROWS]){
  for(int i = 0; i < ROWS; i++){
    result[i] = vec1[i] * vec2[i];
  }
}

void MatMultComplex(array<double, ROWS> &result, array<array<double, COLS>, ROWS> &mat, array<double, ROWS> &vec){
  for (int i = 0; i < COLS; ++i) {
      for (int j = 0; j < ROWS; ++j) {
        result[i] += mat[i][j] * vec[j];
      }
  }
}

void MatMultSimple(double result[ROWS], double mat[ROWS][COLS], double vec[ROWS]){
  for (int i = 0; i < COLS; ++i) {
      for (int j = 0; j < ROWS; ++j) {
        result[i] += mat[i][j] * vec[j];
      }
  }
}

double getTime(){
    struct timeval currentTime;
    gettimeofday(&currentTime, NULL);
    double tmp = (double)currentTime.tv_sec * 1000.0 + (double)currentTime.tv_usec/1000.0;
    return tmp;
}

array<double, ROWS> inputVectorComplex = {{ 0 }};
array<double, ROWS> resultVectorComplex = {{ 0 }};
double inputVectorSimple[ROWS] = { 0 };
double resultVectorSimple[ROWS] = { 0 };

array<array<double, COLS>, ROWS> inputMatrixComplex = {{0}};
double inputMatrixSimple[ROWS][COLS] = { 0 };

int main(){
  double start;
  std::cout << "DotP test with C array: " << std::endl;
  start = getTime();
  for(int i = 0; i < RUNS; i++){
    DotPSimple(resultVectorSimple, inputVectorSimple, inputVectorSimple);
  }
  std::cout << "Duration: " << getTime() - start << std::endl;

  std::cout << "DotP test with C++ array: " << std::endl;
  start = getTime();
  for(int i = 0; i < RUNS; i++){
    DotPComplex(resultVectorComplex, inputVectorComplex, inputVectorComplex);
  }
  std::cout << "Duration: " << getTime() - start << std::endl;

  std::cout << "MatMult test with C array : " << std::endl;
  start = getTime();
  for(int i = 0; i < RUNS; i++){
    MatMultSimple(resultVectorSimple, inputMatrixSimple, inputVectorSimple);
  }
  std::cout << "Duration: " << getTime() - start << std::endl;

  std::cout << "MatMult test with C++ array: " << std::endl;
  start = getTime();
  for(int i = 0; i < RUNS; i++){
    MatMultComplex(resultVectorComplex, inputMatrixComplex, inputVectorComplex);
  }
  std::cout << "Duration: " << getTime() - start << std::endl;
}

Compiled with: icpc demo.cpp -std=c++11 -O0
This is the result:

DotP test with C array:
Duration: 0.289795 ms
DotP test with C++ array:
Duration: 1.98413 ms
MatMult test with C array :
Duration: 28.3459 ms
MatMult test with C++ array:
Duration: 175.15 ms

With -O3 flag:

DotP test with C array:
Duration: 0.0280762 ms
DotP test with C++ array:
Duration: 0.0288086 ms
MatMult test with C array :
Duration: 1.78296 ms
MatMult test with C++ array:
Duration: 4.90991 ms

The C array implementation is much faster without compiler optimization. Why?
Using compiler optimizations the dot products are equally fast. But for the matrix multiplication there is still a significant speedup when using C arrays.
Is there a way to achieve equal performance when using std::array?

Update:

The compiler used: icpc 17.0.0

With gcc 4.8.5 our code runs much slower than with the intel compiler using any optimization level. Therefore we are mainly interested in the behaviour of the intel compiler.

As suggested by Jonas we adjusted RUNS 50.000 with the following results (intel compiler):

With -O0 flag:

DotP test with C array:
Duration: 201.764 ms
DotP test with C++ array:
Duration: 1020.67 ms
MatMult test with C array :
Duration: 15069.2 ms
MatMult test with C++ array:
Duration: 123826 ms

With -O3 flag:

DotP test with C array:
Duration: 16.583 ms
DotP test with C++ array:
Duration: 15.635 ms
MatMult test with C array :
Duration: 980.582 ms
MatMult test with C++ array:
Duration: 2344.46 ms


问:
BigDecimal divide with scale
I have

```<code>private static final BigDecimal ONE_HUNDRED = new BigDecimal(100);
    private static final BigDecimal TEN = new BigDecimal(10);
</code>```

BigDecimal decimal = new BigDecimal(1050);
I need to get 10% I write
BigDecimal decimalResult = decimal.divide(ONE_HUNDRED).multiply(TEN)//100, 10

But Intellij IDE says:

'BigDecimal.divide()' called without a rounding mode argument more...

I added BigDecimal.ROUND_HALF_UP and all others but I get wrong result. I need 1050/100 = 10.5  but if I add BigDecimal.ROUND_HALF_UP result = 11.

How can I correctly divide with scale parameters?

答:
This example returns 105.0000

```<code>public class TestBigDecimal {
  static BigDecimal decimal = new BigDecimal(1050).setScale(4, BigDecimal.ROUND_HALF_UP);
  static BigDecimal ONE_HUNDRED = new BigDecimal(100);
  static BigDecimal TEN = new BigDecimal(10);

  public static void main(String[] args)
  {
    BigDecimal decimalResult = decimal.divide(ONE_HUNDRED).multiply(TEN) ;
    System.out.println(decimalResult);
  }
}
</code>```

You should adjust the scale during the creation of decimal variable.

Title: BigDecimal divide with scale

Body:
I have

private static final BigDecimal ONE_HUNDRED = new BigDecimal(100);
    private static final BigDecimal TEN = new BigDecimal(10);

BigDecimal decimal = new BigDecimal(1050);
I need to get 10% I write
BigDecimal decimalResult = decimal.divide(ONE_HUNDRED).multiply(TEN)//100, 10

But Intellij IDE says:

'BigDecimal.divide()' called without a rounding mode argument more...

I added BigDecimal.ROUND_HALF_UP and all others but I get wrong result. I need 1050/100 = 10.5  but if I add BigDecimal.ROUND_HALF_UP result = 11.

How can I correctly divide with scale parameters?

Body:
This example returns 105.0000

public class TestBigDecimal {
  static BigDecimal decimal = new BigDecimal(1050).setScale(4, BigDecimal.ROUND_HALF_UP);
  static BigDecimal ONE_HUNDRED = new BigDecimal(100);
  static BigDecimal TEN = new BigDecimal(10);

  public static void main(String[] args)
  {
    BigDecimal decimalResult = decimal.divide(ONE_HUNDRED).multiply(TEN) ;
    System.out.println(decimalResult);
  }
}

You should adjust the scale during the creation of decimal variable.


问:
Two implementations for List Monad bind in the literature: why are they equivalent?
Reading the Monad chapter in "Programming in Haskell" 2nd ed. from Graham Hutton, I found this example on page 167 to illustrate the behaviour of the List Monad:

```<code>> pairs [1,2] [3,4]
[(1,3),(1,4),(2,3),(2,4)]
</code>```

With pairs defined like this:

```<code>pairs :: [a] -> [b] -> [(a,b)]
pairs xs ys = do x <- xs
                 y <- ys
                 return (x,y)
</code>```

And this implementation of bind:

```<code>instance Monad [] where
   -- (>>=) :: [a] -> (a -> [b]) -> [b]
   xs >>= f = [y | x <- xs, y <- f x]
</code>```

I tried to understand with pencil and paper how the example worked out, but didn't get it.

Then I found, that in other books the bind operation is defined differently:

```<code>...
   xs >>= f = concat (fmap f xs)
</code>```

With this definition I understand why the example works.
But the first definition is the one I found on hackage in the prelude, so I trust its correct.

My question:

Can anybody explain why the first definition is equivalent to the second?          (Where does the concat-stuff happen in the first one?)

答:
[y | x <- xs, y <- f x] takes all the xs in xs one-by-one and

apply f to them, which is a monadic action a -> [a], thus the result  is a list of values ([a])

the comprehension proceeds to address each y in f x one-by-one

each y is sent to the output list

this is equivalent to first mapping f over each of the elements of the input list, resulting in a list of nested lists, that are then concatenated. Notice that fmap is map for lists, and you could use concatMap f xs as the definition of xs >>= f.

Body:
Reading the Monad chapter in "Programming in Haskell" 2nd ed. from Graham Hutton, I found this example on page 167 to illustrate the behaviour of the List Monad:

> pairs [1,2] [3,4]
[(1,3),(1,4),(2,3),(2,4)]

With pairs defined like this:

pairs :: [a] -> [b] -> [(a,b)]
pairs xs ys = do x <- xs
                 y <- ys
                 return (x,y)

And this implementation of bind:

instance Monad [] where
   -- (>>=) :: [a] -> (a -> [b]) -> [b]
   xs >>= f = [y | x <- xs, y <- f x]

I tried to understand with pencil and paper how the example worked out, but didn't get it.

Then I found, that in other books the bind operation is defined differently:

...
   xs >>= f = concat (fmap f xs)

With this definition I understand why the example works.
But the first definition is the one I found on hackage in the prelude, so I trust its correct.

My question:

Can anybody explain why the first definition is equivalent to the second?          (Where does the concat-stuff happen in the first one?)


问:
JMeter-JDBC Connection error
While running an SQl query in JMeter using JDBC request, I'm getting:

SQL ConnectionException:Cannot create Poolable Connectionfactory

(IO error:Network Adapter could not establish the connection).

Installed Oracle11g in virtual machine.

Please give me solution.

Thanks in Advance.

答:
Make sure you have Oracle JDBC driver somewhere in JMeter Classpath

Make sure you have configured network adapter in the virtual machine in Bridge mode (not "host-only", not "NAT") so the virtual machine would have its own IP address.

Make sure port 1521 (or whatever is used by Oracle) is not blocked by OS firewall. Check if you are able to connect to the port using i.e. telnet client

Add JDBC Connection Configuration test element and provide JDBC url of your Oracle instance along with credentials there.

See The Real Secret to Building a Database Test Plan With JMeter guide to learn more about setting up JMeter for databases load testing

Title: JMeter-JDBC Connection error


问:
Ionic Storage, how to stay simple in the Promise scope
I am using Ionic Storage, and it returns a Promise...which is really impractical.

I need to get a value from Storage and depending on its boolean value, do something.

That was the code I had in Angular 1:

```<code>$scope.isUser = UserService.getUser() ? true : false;
$scope.isUserTemp = storageService.get("userTemp") ? true : false;
$scope.data.showLoginClose = ($scope.isUser || $scope.isUserTemp || !$rootScope.isMobile );
</code>```

Here's the new code in typescript:

```<code>    let isUser: boolean;
    let isUserTemp: boolean;
    this.storage.ready().then(() => {
        this.storage.get('userTemp').then((val) => {
            isUserTemp = true ;
            isUser = UserService.getUser() ? true : false;
            this.data.showLoginClose = (isUser || userTemp || !this.isCordova.f() );
        })
        .catch( (e) => {
            isUserTemp = false ;
            isUser = UserService.getUser() ? true : false;
            this.data.showLoginClose = (isUser || userTemp || !this.isCordova.f() );
        })
    });
</code>```

3 lines vs 14 lines, that's not an improvement.

Can you help me write something clean in the Promise scope for Angular2 / typescript, for all the cases (isUser true, userTemp : true   ; isUser false, userTemp : true  ; etc...) ?

答:
After removing useless variables isUserTemp (which is just set to true or false, meaning that you don't need to involve it in a condition, as you already know its value...) and isUser (which only depends on UserService.getUser()), here's what you get:

```<code>this.storage.ready().then(() => {
    return this.storage.get('userTemp');
}).then((val) => {
    this.data.showLoginClose = (UserService.getUser() || !this.isCordova.f() );
}).catch( (e) => {
    this.data.showLoginClose = (UserService.getUser() || !this.isCordova.f() );
});
</code>```

I feel like something is wrong in the logic.
After a minor refactoring, you may have something like:

```<code>function updateLoginClose(isUserTemp: boolean) {
    this.data.showLoginClose = isUserTemp || UserService.getUser() || !this.isCordova.f();
}

this.storage.ready().then(() => {
    return this.storage.get('userTemp');
})
.then(val => updateLoginClose(!!val))
.catch(() => updateLoginClose(false));
</code>```

Please mind that you should do something with variables valand e,  otherwise, don't declare them.

EDIT - Take val into account.

Body:
I am using Ionic Storage, and it returns a Promise...which is really impractical.

I need to get a value from Storage and depending on its boolean value, do something.

That was the code I had in Angular 1:

$scope.isUser = UserService.getUser() ? true : false;
$scope.isUserTemp = storageService.get("userTemp") ? true : false;
$scope.data.showLoginClose = ($scope.isUser || $scope.isUserTemp || !$rootScope.isMobile );

Here's the new code in typescript:

    let isUser: boolean;
    let isUserTemp: boolean;
    this.storage.ready().then(() => {
        this.storage.get('userTemp').then((val) => {
            isUserTemp = true ;
            isUser = UserService.getUser() ? true : false;
            this.data.showLoginClose = (isUser || userTemp || !this.isCordova.f() );
        })
        .catch( (e) => {
            isUserTemp = false ;
            isUser = UserService.getUser() ? true : false;
            this.data.showLoginClose = (isUser || userTemp || !this.isCordova.f() );
        })
    });

3 lines vs 14 lines, that's not an improvement.

Can you help me write something clean in the Promise scope for Angular2 / typescript, for all the cases (isUser true, userTemp : true   ; isUser false, userTemp : true  ; etc...) ?

Body:
After removing useless variables isUserTemp (which is just set to true or false, meaning that you don't need to involve it in a condition, as you already know its value...) and isUser (which only depends on UserService.getUser()), here's what you get:

this.storage.ready().then(() => {
    return this.storage.get('userTemp');
}).then((val) => {
    this.data.showLoginClose = (UserService.getUser() || !this.isCordova.f() );
}).catch( (e) => {
    this.data.showLoginClose = (UserService.getUser() || !this.isCordova.f() );
});

I feel like something is wrong in the logic.
After a minor refactoring, you may have something like:

function updateLoginClose(isUserTemp: boolean) {
    this.data.showLoginClose = isUserTemp || UserService.getUser() || !this.isCordova.f();
}

this.storage.ready().then(() => {
    return this.storage.get('userTemp');
})
.then(val => updateLoginClose(!!val))
.catch(() => updateLoginClose(false));

Please mind that you should do something with variables valand e,  otherwise, don't declare them.

EDIT - Take val into account.


问:
JSP pages in Eclipse do not indent?
I've read this article describing how to format jsp's in eclipse.  I have WTP installed and the jsp tags are colored.  However, there is no indenation on the html (i.e.  and  etc. are all at the same level).  I've tried Source -> Format with no success.  Is this a bug?

答:
Same problem here
Toy around with the formatter settings for html as this is used for jsp.

window > preferences > left tree pick web > editor.
Then change the line width to maybe 180
Click "Split multiple attributes each on a new line" seems to do the trick

ContentLicense: CC BY-SA 2.5

Title: JSP pages in Eclipse do not indent?


问:
JavaFX TableView how to get file size to PropertyValueFactory?
I have some TableView with two columns - name and size;
This Table works with File objects;

PropertyValueFactory for columns can take properties of object, trying search somenameProrperty, getSomename, isSomename;
I'm need to get length() method from File.

```<code>columnName.setCellValueFactory(new PropertyValueFactory<>("name"));
columnSize.setCellValueFactory(new PropertyValueFactory<>("length"));
</code>```

This code view file names (getName() method), but length colums is empty.
Know anyone what i can do with factory to get length() from File?

答:
Found solution</p>

```<code>columnSize.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<File, String>, ObservableValue<String>>() {
    @Override
    public ObservableValue<String> call(TableColumn.CellDataFeatures<File, String> param) {
        long size = param.getValue().length();
        size = size/1024;
        return new ReadOnlyObjectWrapper(String.valueOf(size));
    }
});
</code>```

Body:
I have some TableView with two columns - name and size;
This Table works with File objects;

PropertyValueFactory for columns can take properties of object, trying search somenameProrperty, getSomename, isSomename;
I'm need to get length() method from File.

columnName.setCellValueFactory(new PropertyValueFactory<>("name"));
columnSize.setCellValueFactory(new PropertyValueFactory<>("length"));

This code view file names (getName() method), but length colums is empty.
Know anyone what i can do with factory to get length() from File?

Body:
Found solution

columnSize.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<File, String>, ObservableValue<String>>() {
    @Override
    public ObservableValue<String> call(TableColumn.CellDataFeatures<File, String> param) {
        long size = param.getValue().length();
        size = size/1024;
        return new ReadOnlyObjectWrapper(String.valueOf(size));
    }
});


问:
Waiting for service media.audio_policy on android boot
i am developing cyanogenmod 11 for my device samsung sm-g7102 garnd2
but it does not boot and gives bootloop on cyanogenmod logo.
the logcat shows following

#

```<code>W/AudioSystem( 684): AudioPolicyService not published, waiting...
I/ServiceManager( 684): Waiting for service media.audio_policy...
I/ServiceManager( 684): Waiting for service media.audio_policy...
I/ServiceManager( 684): Waiting for service media.audio_policy...
I/ServiceManager( 684): Waiting for service media.audio_policy...
I/ServiceManager( 684): Waiting for service media.audio_policy...
W/AudioSystem( 684): AudioPolicyService not published, waiting...
I/ServiceManager( 684): Waiting for service media.audio_policy...
I/ServiceManager( 684): Waiting for service media.audio_policy...
</code>```

#

this goes on and on....

also if i delete libsecnativefeature.so from system/lib
it boots fine but there is no sound, camera, ril.

答:
A Samsung Galaxy J5 I came around recently had a similar (if not same) problem and was stuck in a bootloop. Doing a quick search online, it seems this "bootloop caused by audio error" is common in many Samsung models, but not much information on it is out there.

The errors which were looping (obtained from logcat) included:

```<code>I/ServiceManager(  248): service 'media.audio_flinger' died
I/ServiceManager(  248): service 'media.player' died
I/ServiceManager(  248): service 'media.camera' died
I/ServiceManager(  513): Waiting for service media.audio_policy...
E/SamsungPowerSound(  513): wait_for_audio_policy
E/SamsungPowerSound(  513): media.audio_policy not published, waiting...
</code>```

I was able to resolve the problem by chmoding the file /system/lib/libaudioflinger.so to 755 (rwx-rx-rx). By default, the permissions were 644 (rw-r-r).

Since this solved the issue, my speculation is that a process with low privileges needed to execute the library file.

Note: I had to root the phone before I could edit the the permissions of the file. This voids the warranty. Also for most Samsung models, make sure you have enabled OEM Unlock else you risk wiping your phone via some flashing methods like Odin.

Body:
i am developing cyanogenmod 11 for my device samsung sm-g7102 garnd2
but it does not boot and gives bootloop on cyanogenmod logo.
the logcat shows following

#

W/AudioSystem( 684): AudioPolicyService not published, waiting...
I/ServiceManager( 684): Waiting for service media.audio_policy...
I/ServiceManager( 684): Waiting for service media.audio_policy...
I/ServiceManager( 684): Waiting for service media.audio_policy...
I/ServiceManager( 684): Waiting for service media.audio_policy...
I/ServiceManager( 684): Waiting for service media.audio_policy...
W/AudioSystem( 684): AudioPolicyService not published, waiting...
I/ServiceManager( 684): Waiting for service media.audio_policy...
I/ServiceManager( 684): Waiting for service media.audio_policy...

#

this goes on and on....

also if i delete libsecnativefeature.so from system/lib
it boots fine but there is no sound, camera, ril.

Body:
A Samsung Galaxy J5 I came around recently had a similar (if not same) problem and was stuck in a bootloop. Doing a quick search online, it seems this "bootloop caused by audio error" is common in many Samsung models, but not much information on it is out there.

The errors which were looping (obtained from logcat) included:

I/ServiceManager(  248): service 'media.audio_flinger' died
I/ServiceManager(  248): service 'media.player' died
I/ServiceManager(  248): service 'media.camera' died
I/ServiceManager(  513): Waiting for service media.audio_policy...
E/SamsungPowerSound(  513): wait_for_audio_policy
E/SamsungPowerSound(  513): media.audio_policy not published, waiting...

I was able to resolve the problem by chmoding the file /system/lib/libaudioflinger.so to 755 (rwx-rx-rx). By default, the permissions were 644 (rw-r-r).

Since this solved the issue, my speculation is that a process with low privileges needed to execute the library file.

Note: I had to root the phone before I could edit the the permissions of the file. This voids the warranty. Also for most Samsung models, make sure you have enabled OEM Unlock else you risk wiping your phone via some flashing methods like Odin.


问:
C# - Passing different type of objects through the same method
Original Question

So I have this 3 objects...

```<code>public class obj1
{
  public int Id { get; set; }
  public string Name { get; set; }
}

public class obj2
{
  public int AccNum { get; set; }
  public string Name { get; set; }
}

public class obj3
{
  public string Email { get; set; }
  public string Phone { get; set; }
}
</code>```

... and one method that is supposed to receive one of them, after evaluating the object type the program should decide which function to call.

I've tried with generics but it doesn't work as I expected. So far this is what I've got...

```<code>    public class NotificationHelper: INotificationHelper
    {

        public bool SendNotification<TNotInfo>(TNotInfo obj) where TNotInfo : class
        {
            if (contract.GetType() == typeof (obj1))
            {
                var sender = new SendSMS();
                return sender.Send(obj);
            }
            if (contract.GetType() == typeof(obj2))
            {
                var sender = new SendPush();
                return sender.Send(obj);
            }
            else
            {
                var sender = new SendEmail();
                return sender.Send(obj);
            }
        }
    }
</code>```

but I get the error "Cannot convert from TNotInfo to Models.obj1". Is there any way to overcome this issue? Or I have to change my logic?

Appreciate any help, thanks in advance.

*Edit

```<code>using System;

namespace EmailNotifications
{

    public interface IEmailNotification
    {
        void SendEmailNotification();
    }

    public class EmailNotificationA : IEmailNotification
    {

        public void SendEmailNotification(Contract1 a)
        {
            Console.WriteLine($"Sending EmailNotificationA ({a})");
        }
    }

    public class EmailNotificationB : IEmailNotification
    {
        public void SendEmailNotification(Contract2 b)
        {
            Console.WriteLine($"Sending EmailNotificationB ({b})");
        }
    }

    public class EmailNotificationC : IEmailNotification
    {

        public void SendEmailNotification(Contrac3 c)
        {
            Console.WriteLine($"Sending EmailNotificationC ({c})");
        }
    }

    public class EmailNotificationService
    {
        private readonly IEmailNotification _emailNotification;

        public EmailNotificationService(IEmailNotification emailNotification)
        {
            this._emailNotification = emailNotification;
        }

        public void ServiceHelper()
        {
            _emailNotification.SendEmailNotification();
        }
    }
}
</code>```

Above solution is what I was trying to achieve, applying strategy design pattern. But I couldn't manage to make my interface method receive different objects, this is required because each notification has is own implementation. As visible at the none working example above, I have 3 different implementation of the same method all of them receiving different objects. Any idea of how to make this logic work?

答:
I would suggest creating a parent class from which these 3 inherit

```<code>public class ParentType { }
public class Obj1 : ParentType { ... }
</code>```

The method would then just request the parent type, such as:

```<code>public bool SendNotification(ParentType obj) { ... }
</code>```

Body:
Original Question

So I have this 3 objects...

public class obj1
{
  public int Id { get; set; }
  public string Name { get; set; }
}

public class obj2
{
  public int AccNum { get; set; }
  public string Name { get; set; }
}

public class obj3
{
  public string Email { get; set; }
  public string Phone { get; set; }
}

... and one method that is supposed to receive one of them, after evaluating the object type the program should decide which function to call.

I've tried with generics but it doesn't work as I expected. So far this is what I've got...

    public class NotificationHelper: INotificationHelper
    {

        public bool SendNotification<TNotInfo>(TNotInfo obj) where TNotInfo : class
        {
            if (contract.GetType() == typeof (obj1))
            {
                var sender = new SendSMS();
                return sender.Send(obj);
            }
            if (contract.GetType() == typeof(obj2))
            {
                var sender = new SendPush();
                return sender.Send(obj);
            }
            else
            {
                var sender = new SendEmail();
                return sender.Send(obj);
            }
        }
    }

but I get the error "Cannot convert from TNotInfo to Models.obj1". Is there any way to overcome this issue? Or I have to change my logic?

Appreciate any help, thanks in advance.

*Edit

using System;

namespace EmailNotifications
{

    public interface IEmailNotification
    {
        void SendEmailNotification();
    }

    public class EmailNotificationA : IEmailNotification
    {

        public void SendEmailNotification(Contract1 a)
        {
            Console.WriteLine($"Sending EmailNotificationA ({a})");
        }
    }

    public class EmailNotificationB : IEmailNotification
    {
        public void SendEmailNotification(Contract2 b)
        {
            Console.WriteLine($"Sending EmailNotificationB ({b})");
        }
    }

    public class EmailNotificationC : IEmailNotification
    {

        public void SendEmailNotification(Contrac3 c)
        {
            Console.WriteLine($"Sending EmailNotificationC ({c})");
        }
    }

    public class EmailNotificationService
    {
        private readonly IEmailNotification _emailNotification;

        public EmailNotificationService(IEmailNotification emailNotification)
        {
            this._emailNotification = emailNotification;
        }

        public void ServiceHelper()
        {
            _emailNotification.SendEmailNotification();
        }
    }
}

Above solution is what I was trying to achieve, applying strategy design pattern. But I couldn't manage to make my interface method receive different objects, this is required because each notification has is own implementation. As visible at the none working example above, I have 3 different implementation of the same method all of them receiving different objects. Any idea of how to make this logic work?

Body:
I would suggest creating a parent class from which these 3 inherit

public class ParentType { }
public class Obj1 : ParentType { ... }

The method would then just request the parent type, such as:

public bool SendNotification(ParentType obj) { ... }


问:
How to use $_GET variable (index.php?cat=about)
I know there must already has this question been asked but I didn't find the answer cause I don't know how to search exactly what I want.

So, I wanna make such a link http://example.com/index.php?cat=about where I should insert some about info. But I don't know how to make a page with this URL containing ? symbol and other stuff, or how to edit that page then, where to edit and etc.

```<code><a href="index.php?cat=about">About Us</a>
</code>```

I've also made cat.php file but what next?

答:
In your index.php file you can use the following:

```<code>if(isset($_GET['cat']) { // means if the user use the url with ?cat=something
    echo "<1>About {$_GET['cat']}</h1>"; //print the about of the cat as html
}
</code>```

Body:
I know there must already has this question been asked but I didn't find the answer cause I don't know how to search exactly what I want.

So, I wanna make such a link http://example.com/index.php?cat=about where I should insert some about info. But I don't know how to make a page with this URL containing ? symbol and other stuff, or how to edit that page then, where to edit and etc.

About Us

I've also made cat.php file but what next?

Body:
In your index.php file you can use the following:

if(isset($_GET['cat']) { // means if the user use the url with ?cat=something
    echo "<1>About {$_GET['cat']}</h1>"; //print the about of the cat as html
}


问:
Change Class to Hover Class
I have a couple of nested divs and have set a CSS class for one of the interior divs. How would I go about setting off the hover version of the class (class.hover) when the user hovers of the outer div, but not necessarily over the interior div's area.

I'm assuming this has to be done via JavaScript. I need some inputs with this.

Thanks

答:
Unless I misunderstand the question, you're asking how to make a parent  inherit the hover behavior of its child? If that's the question, it can't be done through CSS, at least not directly. Style inheritance goes downward in the document tree, not up.

One possible workaround would be (via a JQuery ready() function, for example) to add the hover style to any  that has a child  with a hover style. But this would obfuscate what's really happening to later developers. A much clearer way to design this would be simply to give the parent  the hover class (& thus the hover behavior) in the first place, as some of the other replies show.

Hope that helps.

Title: Change Class to Hover Class


问:
Ckeditor not displaying in production Rails
So I updated Ckeditor to 4.2. After I did this, Ckeditor no longer appears in production. Instead, I get the following error in the console:

```<code>Uncaught TypeError: CKEDITOR.style.customHandlers[e.type] is not a constructor
</code>```

I've consulted a few sources, including this post, which claimed the issue was in precompilation. I've edited my application.rb to include Ckeditor in precompilation, but it still doesn't work.

```<code>require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module DeployTest
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.
    config.assets.precompile += Ckeditor.assets
    config.assets.precompile += %w( ckeditor/* )
    config.autoload_paths += %W(#{config.root}/app/models/ckeditor)
    config.active_record.default_timezone = :local
    config.time_zone = 'Eastern Time (US & Canada)'
  end
end
</code>```

Weirdly enough, when I turn config.assets.debug = true, Ckeditor starts working again, but my CSS turns off.

Why does config.assets.debug work? Why does it turn off my CSS? And how can I get a permanent solution for ckeditor?

答:
Using ckeditor gem from git solved this issue for me

gemfile:

```<code>gem 'ckeditor', github: 'galetahub/ckeditor'
</code>```

https://github.com/galetahub/ckeditor/issues/719

Body:
So I updated Ckeditor to 4.2. After I did this, Ckeditor no longer appears in production. Instead, I get the following error in the console:

Uncaught TypeError: CKEDITOR.style.customHandlers[e.type] is not a constructor

I've consulted a few sources, including this post, which claimed the issue was in precompilation. I've edited my application.rb to include Ckeditor in precompilation, but it still doesn't work.

require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module DeployTest
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.
    config.assets.precompile += Ckeditor.assets
    config.assets.precompile += %w( ckeditor/* )
    config.autoload_paths += %W(#{config.root}/app/models/ckeditor)
    config.active_record.default_timezone = :local
    config.time_zone = 'Eastern Time (US & Canada)'
  end
end

Weirdly enough, when I turn config.assets.debug = true, Ckeditor starts working again, but my CSS turns off.

Why does config.assets.debug work? Why does it turn off my CSS? And how can I get a permanent solution for ckeditor?

Body:
Using ckeditor gem from git solved this issue for me

gemfile:

gem 'ckeditor', github: 'galetahub/ckeditor'

https://github.com/galetahub/ckeditor/issues/719


问:
Getting Cannot change locked branch exception in Guidewire PC
I am trying to make a readonly entity to writable by using

```<code>Transaction.runwithNewBundle(\bundle -> {
   entity = bundle.add(entity)
})
</code>```

but I am getting

```<code>java.lang.IllegalArgumentException: You cannot change a locked branch.
</code>```

Please help me out with this.

答: I got it resolved. Guidewire provides one field in entity called "Locked". If it is set to true, the entity cannot be modified even in the Transaction.runwithNewBundle scope.Set it to false to resolve the exception.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make a readonly entity to writable by using

Transaction.runwithNewBundle(\bundle -> {
   entity = bundle.add(entity)
})

but I am getting

java.lang.IllegalArgumentException: You cannot change a locked branch.

Please help me out with this.


问:
How to round up result of dividing
```<code>finalResult = Math.Ceiling(result = (x - y) / (z - 1));
</code>```

I am trying to get whole rounded number. finalResult and result are double. Others are int. And well... not working.
I would appreciate some help. Thank you.

答:
In order to get the result of this operation as double you have to make at least one operand double (see https://msdn.microsoft.com/en-us/library/3t4w2bkb.aspx). Try adding 'd' to literal:

```<code>finalResult = Math.Ceiling(result = (x - y) / (z - 1d));
</code>```

By doing this little trick you ensure that '1' will be treated as double, not as int, so the whole operation outcome will be a double.
Note: Unless you want to round this value up, you should change the rounding method to Math.Round().
Note 2: Make sure to prevent division by 0 by checking if(z != 0).

Title: How to round up result of dividing

Body:
finalResult = Math.Ceiling(result = (x - y) / (z - 1));

I am trying to get whole rounded number. finalResult and result are double. Others are int. And well... not working.
I would appreciate some help. Thank you.

Body:
In order to get the result of this operation as double you have to make at least one operand double (see https://msdn.microsoft.com/en-us/library/3t4w2bkb.aspx). Try adding 'd' to literal:

finalResult = Math.Ceiling(result = (x - y) / (z - 1d));

By doing this little trick you ensure that '1' will be treated as double, not as int, so the whole operation outcome will be a double.
Note: Unless you want to round this value up, you should change the rounding method to Math.Round().
Note 2: Make sure to prevent division by 0 by checking if(z != 0).


问:
301 Redirect not working with '%'
I am trying to create a 301 redirect on my WordPress site because an author's name has recently changed. Other redirects are working, but not the ones below.

```<code>Redirect 301 /author/old%20author /author/new_auther/
Redirect 301 /author/old%20author/ /author/new_auther/
</code>```

Is it anything to do with the '%' characters and is there any way I can work around this without having to do it via PHP?

答:
There is no need for percent encoding of spaces, just enclose the URL in quotes. See also Redirect

The old URL-path is a case-sensitive (%-decoded) path beginning with a slash. A relative path is not allowed.

```<code>Redirect "/author/old author" /author/new_auther/
</code>```

When everything works as it should, you may change the status code to 301. Never test with 301.

Title: 301 Redirect not working with '%'

Body:
I am trying to create a 301 redirect on my WordPress site because an author's name has recently changed. Other redirects are working, but not the ones below.

Redirect 301 /author/old%20author /author/new_auther/
Redirect 301 /author/old%20author/ /author/new_auther/

Is it anything to do with the '%' characters and is there any way I can work around this without having to do it via PHP?

Body:
There is no need for percent encoding of spaces, just enclose the URL in quotes. See also Redirect

The old URL-path is a case-sensitive (%-decoded) path beginning with a slash. A relative path is not allowed.

Redirect "/author/old author" /author/new_auther/

When everything works as it should, you may change the status code to 301. Never test with 301.


答:
OK, Suppose you've two PHP files. page_a.php & page_b.php.

page_a.php

```<code><?php
echo "<a href='page_b.php?cat=about'>Click Me</a>";
</code>```

page_b.php

```<code><?php
print_r($_GET); // Show all GET contents
echo $_GET['cat']; // Show what content exist in 'cat' part of url
</code>```

Hope, this will clear your doubt of how to send data in url from one page to another using GET mehtod.

Title: How to use $_GET variable (index.php?cat=about)

Body:
OK, Suppose you've two PHP files. page_a.php & page_b.php.

page_a.php

<?php
echo "<a href='page_b.php?cat=about'>Click Me</a>";

page_b.php

<?php
print_r($_GET); // Show all GET contents
echo $_GET['cat']; // Show what content exist in 'cat' part of url

Hope, this will clear your doubt of how to send data in url from one page to another using GET mehtod.


问:
When trying to delete a row, I get a Login failure when trying to open connection
I'm trying to create a simple gridview for a table in my database. I am trying to enable the delete feature of the gridview but i'm getting a strange error when I hit delete on one of my rows. Does anyone know why i'm getting this issue? I am connected to my Oracle database through the server explorer and the connection string is correct. Here is a screenshot of the error I get when I run the page and click on a delete link. Thanks in advance!

Web.config -

```<code><configuration>
<connectionStrings>
<add name="ConnectionString3" connectionString="Data Source=obiwan;User ID=ac9555f;Password=*******"
providerName="System.Data.OracleClient" />
</code>```

AvatarView Source Code -

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AvatarView.aspx.cs" Inherits="DatabaseTest.AvatarView" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

    <asp:GridView ID="GridView1" runat="server" OnRowDeleting="Gridview1_RowDeleting" AllowSorting="True" AutoGenerateColumns="False" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" CellPadding="2" DataKeyNames="AVATARID" DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="None" AllowPaging="True" Height="422px" Width="1020px">
        <AlternatingRowStyle BackColor="PaleGoldenrod" />
        <Columns>
            <asp:BoundField DataField="AVATARID" HeaderText="AVATARID" SortExpression="AVATARID" ReadOnly="True" />
            <asp:BoundField DataField="AVATARNAME" HeaderText="AVATARNAME" SortExpression="AVATARNAME" />
            <asp:BoundField DataField="DOB" HeaderText="DOB" SortExpression="DOB" />
            <asp:BoundField DataField="STRENGTH_CURR" HeaderText="STRENGTH_CURR" SortExpression="STRENGTH_CURR" />
            <asp:BoundField DataField="GENDER" HeaderText="GENDER" SortExpression="GENDER" />
            <asp:BoundField DataField="HOARD" HeaderText="HOARD" SortExpression="HOARD" />
            <asp:BoundField DataField="SPECIESID" HeaderText="SPECIESID" SortExpression="SPECIESID" />
            <asp:BoundField DataField="USERID" HeaderText="USERID" SortExpression="USERID" />
            <asp:CommandField ShowDeleteButton="True" />

        </Columns>
        <FooterStyle BackColor="Tan" />
        <HeaderStyle BackColor="Tan" Font-Bold="True" />
        <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
        <SortedAscendingCellStyle BackColor="#FAFAE7" />
        <SortedAscendingHeaderStyle BackColor="#DAC09E" />
        <SortedDescendingCellStyle BackColor="#E1DB9C" />
        <SortedDescendingHeaderStyle BackColor="#C2A47B" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString3 %>" ProviderName="<%$ ConnectionStrings:ConnectionString3.ProviderName %>" SelectCommand="SELECT * FROM "AVATAR""></asp:SqlDataSource>

</div>
</form>
</body>
</html>
</code>```

AvatarView Code Behind -

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Configuration;

using System.Data.OracleClient;

namespace DatabaseTest
{
public partial class AvatarView : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string avatarID = GridView1.DataKeys[e.RowIndex].Value.ToString();
        string deleteSql = "DELETE FROM Avatar WHERE AvatarID = :AvatarID; ";

        using (var con = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionString3"].ConnectionString))
        using (var cmd = new OracleCommand(deleteSql, con))
        {
            cmd.Parameters.Add(":AvatarID", OracleType.VarChar).Value = avatarID;
            con.Open();
            int deleted = cmd.ExecuteNonQuery();
        }

        GridView1.DataSource = SqlDataSource1;
        GridView1.DataBind();
    }
}
}
</code>```

答:
You are using SQL Server specific classes to connect to an Oracle server. Use the Oracle ones OracleConnection or a more generic approach IDbConnection

Example using Oracle clases:

```<code>using (var con = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionString3"].ConnectionString))
</code>```

Body:
I'm trying to create a simple gridview for a table in my database. I am trying to enable the delete feature of the gridview but i'm getting a strange error when I hit delete on one of my rows. Does anyone know why i'm getting this issue? I am connected to my Oracle database through the server explorer and the connection string is correct. Here is a screenshot of the error I get when I run the page and click on a delete link. Thanks in advance!

Web.config -

<configuration>
<connectionStrings>
<add name="ConnectionString3" connectionString="Data Source=obiwan;User ID=ac9555f;Password=*******"
providerName="System.Data.OracleClient" />

AvatarView Source Code -

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AvatarView.aspx.cs" Inherits="DatabaseTest.AvatarView" %>

<!DOCTYPE html>

<title></title>

<form id="form1" runat="server">

    <asp:GridView ID="GridView1" runat="server" OnRowDeleting="Gridview1_RowDeleting" AllowSorting="True" AutoGenerateColumns="False" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" CellPadding="2" DataKeyNames="AVATARID" DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="None" AllowPaging="True" Height="422px" Width="1020px">
        <AlternatingRowStyle BackColor="PaleGoldenrod" />
        <Columns>
            <asp:BoundField DataField="AVATARID" HeaderText="AVATARID" SortExpression="AVATARID" ReadOnly="True" />
            <asp:BoundField DataField="AVATARNAME" HeaderText="AVATARNAME" SortExpression="AVATARNAME" />
            <asp:BoundField DataField="DOB" HeaderText="DOB" SortExpression="DOB" />
            <asp:BoundField DataField="STRENGTH_CURR" HeaderText="STRENGTH_CURR" SortExpression="STRENGTH_CURR" />
            <asp:BoundField DataField="GENDER" HeaderText="GENDER" SortExpression="GENDER" />
            <asp:BoundField DataField="HOARD" HeaderText="HOARD" SortExpression="HOARD" />
            <asp:BoundField DataField="SPECIESID" HeaderText="SPECIESID" SortExpression="SPECIESID" />
            <asp:BoundField DataField="USERID" HeaderText="USERID" SortExpression="USERID" />
            <asp:CommandField ShowDeleteButton="True" />

        </Columns>
        <FooterStyle BackColor="Tan" />
        <HeaderStyle BackColor="Tan" Font-Bold="True" />
        <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
        <SortedAscendingCellStyle BackColor="#FAFAE7" />
        <SortedAscendingHeaderStyle BackColor="#DAC09E" />
        <SortedDescendingCellStyle BackColor="#E1DB9C" />
        <SortedDescendingHeaderStyle BackColor="#C2A47B" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString3 %>" ProviderName="<%$ ConnectionStrings:ConnectionString3.ProviderName %>" SelectCommand="SELECT * FROM "AVATAR""></asp:SqlDataSource>

</form>

AvatarView Code Behind -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Configuration;

using System.Data.OracleClient;

namespace DatabaseTest
{
public partial class AvatarView : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string avatarID = GridView1.DataKeys[e.RowIndex].Value.ToString();
        string deleteSql = "DELETE FROM Avatar WHERE AvatarID = :AvatarID; ";

        using (var con = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionString3"].ConnectionString))
        using (var cmd = new OracleCommand(deleteSql, con))
        {
            cmd.Parameters.Add(":AvatarID", OracleType.VarChar).Value = avatarID;
            con.Open();
            int deleted = cmd.ExecuteNonQuery();
        }

        GridView1.DataSource = SqlDataSource1;
        GridView1.DataBind();
    }
}
}

Body:
You are using SQL Server specific classes to connect to an Oracle server. Use the Oracle ones OracleConnection or a more generic approach IDbConnection

Example using Oracle clases:

using (var con = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionString3"].ConnectionString))


问:
xpages anonymous access looses login credentials
I have a xpages app. with anonymous access.
For some parts to access I need to login in (I use roles to hide the admin parts of the application)
When I login via a url like http://myapp.com/app.nsf?opendatabase&login I can enter my credentials and I am authenticated to the server and app.
When I navigate to some pages I notice it starts to work with anonymous access again.
So for some reason the server drops the credentials.

Any idea?

Regards,
Peter

答:
Seems to be a Safari issue.
After cleaning my history and cache it works..

Thanks all for the help.

Regards,
Peter


问:
Javascript push method to populate array
I want to display the pushIssue array on screen with  object issue pushed into array pushIssue with help of Javascript only. According to my knowledge it can be done with pushIssue.push(issue), then I tried to display it on screen using document.write() but unable to display it

```<code>var issue = {
    id: 1,
    description: "This space is for description",
    severity: "This is severity",
    assignedTo: "Name of the assigned person",
    status: "Issue Status "
  }
var pushIssue = [];
</code>```

答: Use pushIssue.toString() instead of only pushIssue.</p>

Body:
I want to display the pushIssue array on screen with  object issue pushed into array pushIssue with help of Javascript only. According to my knowledge it can be done with pushIssue.push(issue), then I tried to display it on screen using document.write() but unable to display it

var issue = {
    id: 1,
    description: "This space is for description",
    severity: "This is severity",
    assignedTo: "Name of the assigned person",
    status: "Issue Status "
  }
var pushIssue = [];


答:
You need a type casting to get Math.Ceiling to work.</p>

```<code>Decimal finalResult = Math.Ceiling(((Decimal)(x - y)) / (z - 1));
</code>```

Title: How to round up result of dividing

Body:
You need a type casting to get Math.Ceiling to work.

Decimal finalResult = Math.Ceiling(((Decimal)(x - y)) / (z - 1));


问:
How can I put validation in the getter and setter methods in C#?
In C#, I can have a property without having the need to declare a private variable.
My VB6 code that looked like this

```<code>'local variable(s) to hold property value(s)
Private mvarPhoneNumber As String 'local copy
Public Property Let PhoneNumber(ByVal vData As String)
'used when assigning a value to the property, on the left side of an assignment.
'Syntax: X.PhoneNumber = 5
    mvarPhoneNumber = vData
End Property

Public Property Get PhoneNumber() As String
'used when retrieving value of a property, on the right side of an assignment.
'Syntax: Debug.Print X.PhoneNumber
    PhoneNumber = mvarPhoneNumber
End Property
</code>```

can now look like this.

```<code>public string PhoneNumber{get;set;}
</code>```

How can I put validation in the getter and setter methods in C#?
I tried adding a validation like this.

```<code>public string PhoneNumber
        {
            get
            {
                return PhoneNumber;
            }
            set
            {
                if (value.Length <= 30)
                {
                    PhoneNumber = value;
                }
                else
                {
                    PhoneNumber = "EXCEEDS LENGTH";
                }
            }
        }
</code>```

The get part of this code won't compile.
Do I need to revert to using a private variable?

答:
Yes you do.  When you use the shortcut "implicit" syntax, it secretly creates a backing field called _phoneNumber for you.  When you explicitly define your property, you need to make your own backing field.  Right above your property definition put:

```<code>private string _phoneNumber;
</code>```

and then in your property get use:

```<code>get
{
    return _phoneNumber;
}
</code>```

Body:
In C#, I can have a property without having the need to declare a private variable.
My VB6 code that looked like this

'local variable(s) to hold property value(s)
Private mvarPhoneNumber As String 'local copy
Public Property Let PhoneNumber(ByVal vData As String)
'used when assigning a value to the property, on the left side of an assignment.
'Syntax: X.PhoneNumber = 5
    mvarPhoneNumber = vData
End Property

Public Property Get PhoneNumber() As String
'used when retrieving value of a property, on the right side of an assignment.
'Syntax: Debug.Print X.PhoneNumber
    PhoneNumber = mvarPhoneNumber
End Property

can now look like this.

public string PhoneNumber{get;set;}

How can I put validation in the getter and setter methods in C#?
I tried adding a validation like this.

public string PhoneNumber
        {
            get
            {
                return PhoneNumber;
            }
            set
            {
                if (value.Length <= 30)
                {
                    PhoneNumber = value;
                }
                else
                {
                    PhoneNumber = "EXCEEDS LENGTH";
                }
            }
        }

The get part of this code won't compile.
Do I need to revert to using a private variable?

Body:
Yes you do.  When you use the shortcut "implicit" syntax, it secretly creates a backing field called _phoneNumber for you.  When you explicitly define your property, you need to make your own backing field.  Right above your property definition put:

private string _phoneNumber;

and then in your property get use:

get
{
    return _phoneNumber;
}


问:
Angular select is not updating
I have problem with select in angular.

HTML:

```<code><select ng-model="vm.targetClassName" ng-options="item for item in vm.classList">
</select>
</code>```

CONTROLLER:

```<code>vm.targetClassName = 'b';
generalResources.getClasses().then(setClasses);
function setClasses(classes) {
    vm.classList = classes.value;
}
</code>```

After this block of code vm.classList is containing array of Strings, for example ['a', 'b', 'c']

What I expect is that select has three options, and the 'b' is selected however I only got select with three options, but nothing is selected.

I checked these values with AngularJS Inspector and it clearly shows that vm.classList is ['a', 'b', 'c'] and vm.targetClassName is 'b';

How can I fix this problem?

答:
This issue isn't reproducible with Angular current version 1.6.3. It seems like Angular 1.3 specific issue. Though you could fix this issue by using track by on ng-options directive

```<code><select ng-model="vm.targetClassName"
   ng-options="item for item in vm.classList track by item">
</select>
</code>```

Demo Plunker

Title: Angular select is not updating

Body:
I have problem with select in angular.

HTML:

<select ng-model="vm.targetClassName" ng-options="item for item in vm.classList">
</select>

CONTROLLER:

vm.targetClassName = 'b';
generalResources.getClasses().then(setClasses);
function setClasses(classes) {
    vm.classList = classes.value;
}

After this block of code vm.classList is containing array of Strings, for example ['a', 'b', 'c']

What I expect is that select has three options, and the 'b' is selected however I only got select with three options, but nothing is selected.

I checked these values with AngularJS Inspector and it clearly shows that vm.classList is ['a', 'b', 'c'] and vm.targetClassName is 'b';

How can I fix this problem?

Body:
This issue isn't reproducible with Angular current version 1.6.3. It seems like Angular 1.3 specific issue. Though you could fix this issue by using track by on ng-options directive

<select ng-model="vm.targetClassName"
   ng-options="item for item in vm.classList track by item">
</select>

Demo Plunker


问:
How to initialize variable without value
I want to show value inside Textview. But problem is that its showing 0 in my Textview. It is coming from int total=0. I am doing setText but its not giving value I want.

If I remove 0 and keep int total then it's showing variable total is not initialized. If I initialize it then it shows that value in Textview.

```<code>public int getTotal(ArrayList<Integer> price){
    int total=0;
    for(int i=0;i<price.size();i++){
        total= total+Integer.parseInt(String.valueOf(price.get(i)));
    }
    return total;
}

textViewamount=(TextView)findViewById(R.id.amountdisplay);
textViewamount.setText(" "+getTotal(price));
</code>```

答: This might happen if the size of ArrayList is 0. In that case, the loop will not execute and it will return the initial value of total if it is set before</p>

Body:
I want to show value inside Textview. But problem is that its showing 0 in my Textview. It is coming from int total=0. I am doing setText but its not giving value I want.

If I remove 0 and keep int total then it's showing variable total is not initialized. If I initialize it then it shows that value in Textview.

public int getTotal(ArrayList<Integer> price){
    int total=0;
    for(int i=0;i<price.size();i++){
        total= total+Integer.parseInt(String.valueOf(price.get(i)));
    }
    return total;
}

textViewamount=(TextView)findViewById(R.id.amountdisplay);
textViewamount.setText(" "+getTotal(price));


问:
MySQL making search function won't work
I am trying to build a search function into my site, which lets you find users based on their name or surname and then it will print all found names. Problem is, that I won't work at all. Can you guys help me?

EDIT: if I try to search something, it will always give me the answer that nothing was found.

The php code:

```<code><?php
    $search = $_POST["search"];
    if(isset($search)) {
        $findname = "SELECT `name` FROM Account WHERE $search = `name`
                    OR SELECT `name` FROM `Account` WHERE $search = `surname`
                    OR SELECT `name` FROM `Account`
                    WHERE $search = `name` . `surname`
                    OR SELECT `name` FROM `Account` WHERE $search = `name` . `surnameprefix` . `surname`";

        $findsurname = "SELECT `surname` from Account WHERE $search = `name`
                        OR SELECT `surname` FROM `Account` WHERE $search = `surname`
                        OR SELECT `surname` FROM `Account` WHERE $search = `name` . `surname`
                        OR SELECT `surname` FROM `Account` WHERE $search = `name` . `surnameprefix` . `surname`";

        $result2 = mysql_query($findsurname);
        $result1 = mysql_query($findname);
            if($result1 == false && $result2 == false) {
                echo '<div id="searchresult"><h1>People found:</h1> <p>No one was found...</p>';
            } else {
                echo '<div id="searchresult">
                        <h1>People found:</h1>
                        <table id="searchtable">
                            while($result = mysql_fetch_array($result1)){
                                <tr id="searchtablerow">
                                    <td> $findname ' . '$findsurname</td>
                                    <td><img src="standard-profile-square.jpg" id="searchpicture"></td>
                                </tr>
                            }
                        </table>
                    </div>';
            }
        }
?>
</code>```

The html form code:

```<code>    <div id="searchform">
        <h1>Search friends:</h1>
        <form name="searchform" method="post" action ="searchlink.php">
            <input type="text" name="search" id="search" autofocus placeholder="e.g. John Smith..."></input> <br>
            <input type="submit" name="submitsearch" value="Search" id="searchbutton"></input>
        </form>
    </div>
</code>```

Thank you guys in advance for helping me!

Yours sincerely,
Unheil

答:
Your last echo is too long. The php instructions for outputting your result are not interpreted but outputted.

```<code><?php
} else {
  echo '<div id="searchresult">
  <h1>People found:</h1>
  <table id="searchtable">';
  while($result = mysql_fetch_array($result1)){
    echo '<tr id="searchtablerow">
        <td> '.$findname.' '.$findsurname.'</td>
        <td><img src="standard-profile-square.jpg" id="searchpicture"></td>
      </tr>';
  }
  echo '</table></div>';
}
?>
</code>```

And if you use ' for Strings, you have to concat your variables into it.

Title: MySQL making search function won't work

Body:
I am trying to build a search function into my site, which lets you find users based on their name or surname and then it will print all found names. Problem is, that I won't work at all. Can you guys help me?

EDIT: if I try to search something, it will always give me the answer that nothing was found.

The php code:

<?php
    $search = $_POST["search"];
    if(isset($search)) {
        $findname = "SELECT `name` FROM Account WHERE $search = `name`
                    OR SELECT `name` FROM `Account` WHERE $search = `surname`
                    OR SELECT `name` FROM `Account`
                    WHERE $search = `name` . `surname`
                    OR SELECT `name` FROM `Account` WHERE $search = `name` . `surnameprefix` . `surname`";

        $findsurname = "SELECT `surname` from Account WHERE $search = `name`
                        OR SELECT `surname` FROM `Account` WHERE $search = `surname`
                        OR SELECT `surname` FROM `Account` WHERE $search = `name` . `surname`
                        OR SELECT `surname` FROM `Account` WHERE $search = `name` . `surnameprefix` . `surname`";

        $result2 = mysql_query($findsurname);
        $result1 = mysql_query($findname);
            if($result1 == false && $result2 == false) {
                echo '

People found:

No one was found...
';
            } else {
                echo '

People found:

                            while($result = mysql_fetch_array($result1)){

                                     $findname ' . '$findsurname

                            }

';
            }
        }
?>

The html form code:

Search friends:

        <form name="searchform" method="post" action ="searchlink.php">
            <input type="text" name="search" id="search" autofocus placeholder="e.g. John Smith..."></input>

            <input type="submit" name="submitsearch" value="Search" id="searchbutton"></input>
        </form>

Thank you guys in advance for helping me!

Yours sincerely,
Unheil

Body:
Your last echo is too long. The php instructions for outputting your result are not interpreted but outputted.

<?php
} else {
  echo '<div id="searchresult">
  <h1>People found:</h1>
  <table id="searchtable">';
  while($result = mysql_fetch_array($result1)){
    echo '<tr id="searchtablerow">
        <td> '.$findname.' '.$findsurname.'</td>
        <td><img src="standard-profile-square.jpg" id="searchpicture"></td>
      </tr>';
  }
  echo '</table></div>';
}
?>

And if you use ' for Strings, you have to concat your variables into it.


问:
How to add new line character in DBMS_OUTPUT.put_line in LINUX
In UNIX, in a SQL script, i have following code:

```<code>LOOP
  DBMS_OUTPUT.put_line (p_key||'|'||p_loc||'\n');
END LOOP
</code>```

Output is:

```<code>5482004|Dir/3-30-2017/file:47923.xml

5482009|Dir/3-30-2017/file:49288.xml
</code>```

However in Linux, since "\n" doesn't work, i am replacing the above code with following code:

```<code>LOOP
  DBMS_OUTPUT.put_line (p_key||'|'||p_loc);
  DBMS_OUTPUT.new_line;
END LOOP
</code>```

Output is:

```<code>20 5482004|Dir/3-30-2017/file:447923.xml 5482009|Dir/3-30-2017/file:449288.xml 5482010|Dir/3-30-2017/file:449739.xml 5482012|Dir/3-30-2017/file:45015.xml
</code>```

The output in this format is without the new line after each line. Please suggest what is in correct in the loop.

P.S. I have also tried DBMS_OUTPUT.put_line (p_key||'|'||p_loc||chr(10)) but the output is still without the new line.

答:
Please refer below SO answer for this question.

New Line Character in dbms_output

Body:
In UNIX, in a SQL script, i have following code:

LOOP
  DBMS_OUTPUT.put_line (p_key||'|'||p_loc||'\n');
END LOOP

Output is:

5482004|Dir/3-30-2017/file:47923.xml

5482009|Dir/3-30-2017/file:49288.xml

However in Linux, since "\n" doesn't work, i am replacing the above code with following code:

LOOP
  DBMS_OUTPUT.put_line (p_key||'|'||p_loc);
  DBMS_OUTPUT.new_line;
END LOOP

Output is:

20 5482004|Dir/3-30-2017/file:447923.xml 5482009|Dir/3-30-2017/file:449288.xml 5482010|Dir/3-30-2017/file:449739.xml 5482012|Dir/3-30-2017/file:45015.xml

The output in this format is without the new line after each line. Please suggest what is in correct in the loop.

P.S. I have also tried DBMS_OUTPUT.put_line (p_key||'|'||p_loc||chr(10)) but the output is still without the new line.


问:
How to show multiple values in an input element using Angular JS
I have an array of months like this

```<code>Array[0]
0
:
"January"
1
:
"February"
2
:
"March"
</code>```

Now I need to show all three values of this array in one input element.
like

How can I do this using angular js. Please help

here's the html

```<code><div class="col-md-4">
                <div asterick class="form-group" ng-class="{'form-group has-success': !error['months'] && (submitted), 'form-group has-error': (error['months']) && (submitted)}">
                    <label for="months">Months</label>
                    <input type="hidden" name="year" ng-model="data.year" value="">
                    <input type="text" name="months" id="months" ng-model="data.months" class="form-control" ng-required="true">
                    <span class="er-block" ng-show="monthlyReportFormPage.months.$touched && monthlyReportFormPage.months.$error.required">Please select months.</span>
                    <span ng-show="error.months" class="er-block">{{error.months}}</span>
                </div>
            </div>
</code>```

答:
Hey in case you work with angular 1.X try the ui-select plugin (https://github.com/angular-ui/ui-select/wiki). I think its exactly what you are looking for. Here are some examples https://angular-ui.github.io/ui-select/demo-multiple-selection.html.

best regards Peter

Body:
I have an array of months like this

Array[0]
0
:
"January"
1
:
"February"
2
:
"March"

Now I need to show all three values of this array in one input element.
like

How can I do this using angular js. Please help

here's the html

                    Months
                    <input type="hidden" name="year" ng-model="data.year" value="">
                    <input type="text" name="months" id="months" ng-model="data.months" class="form-control" ng-required="true">
                    Please select months.
                    {{error.months}}


问:
Handle change event not working for input types?
I am new to react… my handle change event is not working while typing text into an input. How do I go about fixing that? I want to handle both inputs with the same handle change.

```<code>import React from 'react'
import TextField from 'material-ui/TextField'
class Settings extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            first_name:'',
            last_name:''
        }
    }
    handleChange(e){
        var first_name = e.target.first_name
        var last_name = e.target.last_name
        var state = this.state
        state[first_name] = e.target.value
        state[last_name] = e.target.value
        this.setState(state)
    }
    render() {
        return (
          <div>
              <TextField hint text="First Name" id="user_first_name" floatingLabelFixed="editprofile" onChange={this.handleChange.bind(this)} name="user[first_name]" size="30" type="text" value={this.state.first_name} />
              <TextField hint text="Last Name" id="user_last_name" floatingLabelFixed="editprofile" name="user[last_name]" onChange={this.handleChange.bind(this)} size="30" type="text" value={this.state.last_name} />
          </div>
        )
    }
}
</code>```

答:
Based on id you should update the state and not both on them together. Try the below method. Also change the ids

import React from 'react'
import TextField from 'material-ui/TextField'
class Settings extends React.Component {
  constructor(props) {
    super(props)
     this.state = {
      first_name:'',
      last_name:''
    }
  }
  handleChange(e){
     this.setState({[e.target.id]: e.target.value});
  }
  render() {
    return (

            <TextField hint text="First Name" id="first_name" floatingLabelFixed="editprofile" onChange={this.handleChange.bind(this)} name="user[first_name]" size="30" type="text" value={this.state.first_name} />
            <TextField hint text="Last Name" id="last_name" floatingLabelFixed="editprofile" name="user[last_name]" onChange={this.handleChange.bind(this)} size="30" type="text" value={this.state.last_name} />

  )}
}```

Body:
I am new to react… my handle change event is not working while typing text into an input. How do I go about fixing that? I want to handle both inputs with the same handle change.

import React from 'react'
import TextField from 'material-ui/TextField'
class Settings extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            first_name:'',
            last_name:''
        }
    }
    handleChange(e){
        var first_name = e.target.first_name
        var last_name = e.target.last_name
        var state = this.state
        state[first_name] = e.target.value
        state[last_name] = e.target.value
        this.setState(state)
    }
    render() {
        return (

              <TextField hint text="First Name" id="user_first_name" floatingLabelFixed="editprofile" onChange={this.handleChange.bind(this)} name="user[first_name]" size="30" type="text" value={this.state.first_name} />
              <TextField hint text="Last Name" id="user_last_name" floatingLabelFixed="editprofile" name="user[last_name]" onChange={this.handleChange.bind(this)} size="30" type="text" value={this.state.last_name} />

        )
    }
}

Body:
Based on id you should update the state and not both on them together. Try the below method. Also change the ids

import React from 'react'
import TextField from 'material-ui/TextField'
class Settings extends React.Component {
  constructor(props) {
    super(props)
     this.state = {
      first_name:'',
      last_name:''
    }
  }
  handleChange(e){
     this.setState({[e.target.id]: e.target.value});
  }
  render() {
    return (
    <div>
            <TextField hint text="First Name" id="first_name" floatingLabelFixed="editprofile" onChange={this.handleChange.bind(this)} name="user[first_name]" size="30" type="text" value={this.state.first_name} />
            <TextField hint text="Last Name" id="last_name" floatingLabelFixed="editprofile" name="user[last_name]" onChange={this.handleChange.bind(this)} size="30" type="text" value={this.state.last_name} />
      </div>
  )}
}


问:
dataframe too many arguments in the rdd object
I tryed to use this question to convert rdd object to dataframe in spark. The class in my use case contains more than 100 arguments (columns)

```<code>case class MyClass(val1: String, ..., val104: String )

    val df = rdd.map({
      case Row(val1: String, ..., val104: String) => MyClass(val1, ..., val104)
    }).toDF("col1_name", ..., "col104_name")
</code>```

I got this Error: too many arguments for unapply pattern, maximum = 22

May someone help me with a concrete example; i'm using spark 1.6 with scala .
Thank you

答:
Your problem is the limitation on case classes to 22 fields.

You need to define your case class as a more structured data type, so that there are only 22 top fields (but some of those may be case classes again).

Once you've done this, you can use your Row (which itself cannot be pattern matched with 104 fields, you will have to use row(0), row(1), ..., row(103)) to build your MyClass.

Body:
I tryed to use this question to convert rdd object to dataframe in spark. The class in my use case contains more than 100 arguments (columns)

case class MyClass(val1: String, ..., val104: String )

    val df = rdd.map({
      case Row(val1: String, ..., val104: String) => MyClass(val1, ..., val104)
    }).toDF("col1_name", ..., "col104_name")

I got this Error: too many arguments for unapply pattern, maximum = 22

May someone help me with a concrete example; i'm using spark 1.6 with scala .
Thank you


问:
Grouping Variables in C#?
I'm new to C# started recently and had an idea to make a small text based RPG sort of a game, I am using Visual Studio 2017. I want to have a few different files, including one that marks down all the different types of enemies in the game, how much damage one of their attacks do, their defense and how much health they have. I have this so far:

```<code>        string rat;
        int enemyHealth;
        int enemyAtkDmg;
        int enemyDef;
</code>```

But then I started wondering how I could group "string rat;" and the rest together, so for example:

Rat - 10 Health, 2 Attack Damage, 0 Defense.

Any suggestions on how I could do that?
Thank you.

答:
Additionally you can use structs

A struct type is a value type that is typically used to encapsulate
  small groups of related variables, such as the coordinates of a
  rectangle or the characteristics of an item in an inventory

```<code>public struct Rat
{
    public int enemyHealth;
    public int enemyAtkDmg;
    public int enemyDef
}
</code>```

Here is a "discussion" about structs vs classes

Title: Grouping Variables in C#?

Body:
I'm new to C# started recently and had an idea to make a small text based RPG sort of a game, I am using Visual Studio 2017. I want to have a few different files, including one that marks down all the different types of enemies in the game, how much damage one of their attacks do, their defense and how much health they have. I have this so far:

        string rat;
        int enemyHealth;
        int enemyAtkDmg;
        int enemyDef;

But then I started wondering how I could group "string rat;" and the rest together, so for example:

Rat - 10 Health, 2 Attack Damage, 0 Defense.

Any suggestions on how I could do that?
Thank you.

Body:
Additionally you can use structs

A struct type is a value type that is typically used to encapsulate
  small groups of related variables, such as the coordinates of a
  rectangle or the characteristics of an item in an inventory

public struct Rat
{
    public int enemyHealth;
    public int enemyAtkDmg;
    public int enemyDef
}

Here is a "discussion" about structs vs classes