问:
Extract a string value from code
I am trying to extract the string : "Plan B Warranty & Breakdown Recovery"

from the following block of code. I am having problems locating it via xpath and get text. I would be grateful for some pointers.

```<code><!DOCTYPE html>
<html class="ng-scope" ng-app="dan">
<head>
<body class="u-scroll-y ng-scope" ng-controller="CoreController as cc">
<div class="c-animate c-animate--show u-pos-f-t ng-hide" ng-show="global.alerts.length">
<div class="o-grid-fluid u-h-100 u-pl-0">
<div class="o-grid__row u-ml-0 u-h-100">
<div class="c-loader ng-hide" ng-show="loadingHome" style="">
<nav class="o-grid__col-xl-2 o-grid__col-lg-3 o-grid__col-xs-4 u-p-0 c-card__block u-h-100 u-shadowed u-pos-f-t ng-scope" ng-if="global.loggedIn">
<div class="u-p-0 u-h-100 o-grid__col-xl-10 o-grid__col-lg-9 o-grid__col-xs-8 u-pull-right" ng-class="{ 'o-grid__col-xl-10 o-grid__col-lg-9 o-grid__col-xs-8 u-pull-right' : global.loggedIn }">
<header class="o-layout-table__row u-bg-primary u-shadowed u-clearfix u-px ng-scope" ng-if="global.loggedIn">
<main class="o-view-container">
<div class="o-grid-fluid u-py-md">
<div class="o-grid__row">
<div class="c-animate c-animate--view-slide-in-right c-animate--view-slide-out-right ng-scope" ng-view="" style="">
<div class="o-grid__col-md-10 o-grid__col-xl-8 o-grid__col-xl-offset-2 o-grid__col-md-offset-1 ng-scope">
<div class="u-mb-lg u-text-center">
<h1 class="u-text-bold">Recommendations</h1>
</div>
<form class="ng-pristine ng-valid ng-valid-min ng-valid-max ng-valid-required" name="recommend" ng-submit="recommend.$valid">
<div class="o-media c-card c-card__block u-shadowed u-mb-lg ng-scope" ng-if="rc.WarrantyEligible && !rc.prevWarranty()">
<label class="c-form-control-label u-px u-py-sm u-w-100">Warranty Options:</label>
<div class="c-form-group u-p-0 u-mb-sm u-clearfix">
<div class="o-grid__col-md-8">
<label class="c-form-control-label u-text-normal">Product Recommendations (Years):</label>
</div>
<div class="o-grid__col-md-4">
<input class="c-form-control ng-pristine ng-untouched ng-valid ng-valid-min ng-valid-max ng-valid-required" required="" placeholder="Years" ng-model="rc.recommend.year" min="1" max="3" type="number">
</div>
</div>
<div class="c-form-group ng-scope" ng-if="!data.answer_taxi">
<label class="c-option c-option--right u-px u-py-sm u-clearfix ng-scope" ng-if="!rc.planA && !rc.prestige" ng-click="cc.utils.audit('recommendation_warranty_plan_b')">
<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.warrantyPlan" value="planB" name="warrantyPlan" type="radio">
<i class="c-option__radio"></i>
Plan B Warranty & Breakdown Recovery
</label>
</div>
</div>
<div class="o-media c-card c-card__block u-shadowed u-mb-lg u-text-body u-bg-success" ng-if="!rc.prevVap() && rc.VapEligible ">
<div class="c-form-group">
<label class="c-form-control-label u-px u-py-sm u-w-100">Vehicle Asset Protection Options:</label>
<label class="c-option c-option--right u-px u-py-sm u-clearfix" ng-click="cc.utils.audit('recommend_vap')">
<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.vapPlan.plan" value="standard" name="vapPlan" type="radio">
<i class="c-option__radio"></i>
Vehicle Asset Protection - Standard Cover
</label>
<label class="c-option c-option--right u-px u-py-sm u-clearfix" ng-click="cc.utils.audit('vap_key_facts_checked')">
<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.vapCheck" name="vapCheck" type="checkbox">
<i class="c-option__checkbox"></i>
You confirm that you have received the VAP key facts leaflet?
</label>
</div>
</div>
</form>
<div class="c-form-group">
<input class="c-btn c-btn--primary c-btn--block u-pull-right" value="Complete and Preview" ng-click="rc.complete(recommend.$valid); cc.utils.audit('recommend_complete')" ng-disabled="recommend.$invalid" type="submit">
</div>
</div>
</div>
</div>
</div>
</main>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js">
<script src="./build/app.js?v=2.13" defer="">
<script src="/build/standalone/jspdf.js" defer="">
<script src="/build/standalone/sigWebTablet.js" defer="">
</body>
</html>
</code>```

ignore this ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

答:
First get the element by classname. Then get the text from it.

EDIT:

```<code>WebElement element = driver.findElement(By.xpath("//label[@class='c-option c-option--right u-px u-py-sm u-clearfix ng-scope' and not(@class='ng-pristine ng-untouched ng-valid ng-valid-required') and not (@class='c-option__radio')]"));
String desiredText = element.getAttribute("innerHTML");
System.out.println(desiredText);
</code>```

Title: Extract a string value from code

Body:
I am trying to extract the string : "Plan B Warranty & Breakdown Recovery"

from the following block of code. I am having problems locating it via xpath and get text. I would be grateful for some pointers.

<!DOCTYPE html>

Recommendations

<form class="ng-pristine ng-valid ng-valid-min ng-valid-max ng-valid-required" name="recommend" ng-submit="recommend.$valid">

Warranty Options:

Product Recommendations (Years):

<input class="c-form-control ng-pristine ng-untouched ng-valid ng-valid-min ng-valid-max ng-valid-required" required="" placeholder="Years" ng-model="rc.recommend.year" min="1" max="3" type="number">

<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.warrantyPlan" value="planB" name="warrantyPlan" type="radio">

Plan B Warranty & Breakdown Recovery

Vehicle Asset Protection Options:

<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.vapPlan.plan" value="standard" name="vapPlan" type="radio">

Vehicle Asset Protection - Standard Cover

<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.vapCheck" name="vapCheck" type="checkbox">

You confirm that you have received the VAP key facts leaflet?

</form>

<input class="c-btn c-btn--primary c-btn--block u-pull-right" value="Complete and Preview" ng-click="rc.complete(recommend.$valid); cc.utils.audit('recommend_complete')" ng-disabled="recommend.$invalid" type="submit">

Body:
First get the element by classname. Then get the text from it.

EDIT:

WebElement element = driver.findElement(By.xpath("//label[@class='c-option c-option--right u-px u-py-sm u-clearfix ng-scope' and not(@class='ng-pristine ng-untouched ng-valid ng-valid-required') and not (@class='c-option__radio')]"));
String desiredText = element.getAttribute("innerHTML");
System.out.println(desiredText);


来源: stackexchange

问:
Generics in Java - Why I am not allowed to do Comparable<? extends T> instead of Comparable<? super T>?
I have rewritten this ArrayIndexComparator class based on this answer of Jon Skeet so that it can support generic types: Get the indices of an array after sorting?

```<code>public class ArrayIndexComparator<T extends Comparable<? super T>> implements Comparator<Integer> {
    private final T[] array;

    public ArrayIndexComparator(T[] array) {
        this.array = array;
    }

    public Integer[] createIndexArray() {
        Integer[] indexes = new Integer[array.length];
        for (int i = 0; i < array.length; i++) {
            indexes[i] = i; // Autoboxing
        }
        return indexes;
    }

    @Override
    public int compare(Integer index1, Integer index2) {
        // Autounbox from Integer to int to use as array indexes
        return array[index2].compareTo(array[index1]);
    }
}
</code>```

And I can use this class as long as the T type or a supertype of T implements the Comparable interface (Comparable<? super T>).

If I write Comparable<? extends T> instead of Comparable<? super T>, the compiler gives me an error:

```<code>@Override
public int compare(Integer index1, Integer index2) {
    // Autounbox from Integer to int to use as array indexes
    return array[index2].compareTo(array[index1]); // ERROR -> compareTo (capture<? extends T>) in Comparable cannot be applied to (T)
}
</code>```

What does this compareTo (capture<? extends T>) in Comparable cannot be applied to (T) error mean?

I can assume that it does not make sense to define a class AClass which implements Comparable<AChildClassOfAClass>, but yet it is possible:

```<code>class AClass implements Comparable<AChildClassOfAClass> {

    @Override
    public int compareTo(AChildClassOfAClass o) {
        return 0;
    }
}

class AChildClassOfAClass extends AClass {
}
</code>```

In this strange scenario, I assume to be able to use ArrayIndexComparator if I have defined it as ArrayIndexComparator<T extends Comparable<? extends T>>, because in this case T is AClass which implements Comparable<AChildClassOfAClass> which turns out to be a subclass of AClass (therefore Comparable<? extends T> → Comparable<AChildClassOfAClass extends AClass>).

Of course, it makes more sense to use Comparable<? super T>, but I guess I should be able to do it anyway if I want to.

Why doesn't Java allow me to do this?

Thank you very much for your attention.

EDIT: after reading answer to the question Difference between <? super T> and <? extends T> in Java, here is what I understood and I hope I understood it correctly:

array[index1] is of type T but compareTo would expect a type <? extends T>, i.e. an unknown specific type of T (or T itself, but the compiler can't assure that).

Therefore the compiler can't safely cast T to the specific unknown type, whereas it could do it if we use <? super T> because in this case compareTo would expect an unknown supertype of T as a parameter, and as we are passing T, the compiler can safely cast the type T to its supertype as a type T is also a supertype of T (like when we say that an Integer is also a Number, but a Number is not necessarily an Integer).

In this Comparable<? extends T> case we are trying to consume array[index1] by passing it to the compareTo method, but the compiler can't safely cast the type T to the specific type required by compareTo(<? extends T>), which is unknown.

That's why I get the error.

Are this thoughts right?

答:
To manage a ? generic type argument, the compiler uses "captures"; in your case, the capture-of-? super T.

The generic term ? super T means "any superclass of T"; so note it can be Object; so you might have a Comparable<Object> when that method is called. However, this is not valid:

```<code>Comparable<AChildClassOfAClass> yourComparable == new YourClass();
yourComparable.compareTo(new Object());
</code>```

which is what your code might get into with that definition.

ContentLicense: CC BY-SA 3.0

Body:
I have rewritten this ArrayIndexComparator class based on this answer of Jon Skeet so that it can support generic types: Get the indices of an array after sorting?

public class ArrayIndexComparator<T extends Comparable<? super T>> implements Comparator<Integer> {
    private final T[] array;

    public ArrayIndexComparator(T[] array) {
        this.array = array;
    }

    public Integer[] createIndexArray() {
        Integer[] indexes = new Integer[array.length];
        for (int i = 0; i < array.length; i++) {
            indexes[i] = i; // Autoboxing
        }
        return indexes;
    }

    @Override
    public int compare(Integer index1, Integer index2) {
        // Autounbox from Integer to int to use as array indexes
        return array[index2].compareTo(array[index1]);
    }
}

And I can use this class as long as the T type or a supertype of T implements the Comparable interface (Comparable<? super T>).

If I write Comparable<? extends T> instead of Comparable<? super T>, the compiler gives me an error:

@Override
public int compare(Integer index1, Integer index2) {
    // Autounbox from Integer to int to use as array indexes
    return array[index2].compareTo(array[index1]); // ERROR -> compareTo (capture<? extends T>) in Comparable cannot be applied to (T)
}

What does this compareTo (capture<? extends T>) in Comparable cannot be applied to (T) error mean?

I can assume that it does not make sense to define a class AClass which implements Comparable<AChildClassOfAClass>, but yet it is possible:

class AClass implements Comparable<AChildClassOfAClass> {

    @Override
    public int compareTo(AChildClassOfAClass o) {
        return 0;
    }
}

class AChildClassOfAClass extends AClass {
}

In this strange scenario, I assume to be able to use ArrayIndexComparator if I have defined it as ArrayIndexComparator<T extends Comparable<? extends T>>, because in this case T is AClass which implements Comparable<AChildClassOfAClass> which turns out to be a subclass of AClass (therefore Comparable<? extends T> → Comparable<AChildClassOfAClass extends AClass>).

Of course, it makes more sense to use Comparable<? super T>, but I guess I should be able to do it anyway if I want to.

Why doesn't Java allow me to do this?

Thank you very much for your attention.

EDIT: after reading answer to the question Difference between <? super T> and <? extends T> in Java, here is what I understood and I hope I understood it correctly:

array[index1] is of type T but compareTo would expect a type <? extends T>, i.e. an unknown specific type of T (or T itself, but the compiler can't assure that).

Therefore the compiler can't safely cast T to the specific unknown type, whereas it could do it if we use <? super T> because in this case compareTo would expect an unknown supertype of T as a parameter, and as we are passing T, the compiler can safely cast the type T to its supertype as a type T is also a supertype of T (like when we say that an Integer is also a Number, but a Number is not necessarily an Integer).

In this Comparable<? extends T> case we are trying to consume array[index1] by passing it to the compareTo method, but the compiler can't safely cast the type T to the specific type required by compareTo(<? extends T>), which is unknown.

That's why I get the error.

Are this thoughts right?

Body:
To manage a ? generic type argument, the compiler uses "captures"; in your case, the capture-of-? super T.

The generic term ? super T means "any superclass of T"; so note it can be Object; so you might have a Comparable<Object> when that method is called. However, this is not valid:

Comparable<AChildClassOfAClass> yourComparable == new YourClass();
yourComparable.compareTo(new Object());

which is what your code might get into with that definition.


问:
Trouble debugging binarysearch function in C
i'm trying to make a binary search that searches through an ordered file of numbers. Although, even though it worked in "main" before I converted this into a function, it has managed to have some weird behavior after my fseek().

Any suggestions?

```<code>int BinarySearch(FILE *cp, char *CPR, int *position) {

  int i, lines, current_line;
  double CPR_number, CPR_check;
  char CPR_check_string[CPR_LEN];

  sscanf(CPR, "%lf", &CPR_number);

  fseek(cp, 0L, SEEK_END);
  lines = ftell(cp)/12;

  current_line = ftell(cp)/2 - ((ftell(cp)/2) % 12);

  for (i = 0; i < log10(lines)/log10(2); i++) {

    fseek(cp, current_line, SEEK_SET);

    /* Read CPR as string */
    fscanf(cp, "%[0-9]", CPR_check_string);

    /* Convert to number */
    sscanf(CPR_check_string, "%lf", &CPR_check);

    if (CPR_number == CPR_check) {
      printf("This happens\n");
      *position = ftell(cp);
      return TRUE;
    } else if (CPR_number < CPR_check) {
      current_line = ftell(cp)/2 - ((ftell(cp)/2) % 12);
    } else if (CPR_number > CPR_check) {
      current_line = ftell(cp) + ftell(cp)/2 - ((ftell(cp) + ftell(cp)/2) % 12);
    }
  }

  return FALSE;
}
</code>```

It doesn't seem to run the rest of the code.

Thanks in advance.

答: I found my answer, it was my FILE pointer that was off, it had to be a pointer to a pointer so FILE **. </p>

Body:
i'm trying to make a binary search that searches through an ordered file of numbers. Although, even though it worked in "main" before I converted this into a function, it has managed to have some weird behavior after my fseek().

Any suggestions?

int BinarySearch(FILE *cp, char *CPR, int *position) {

  int i, lines, current_line;
  double CPR_number, CPR_check;
  char CPR_check_string[CPR_LEN];

  sscanf(CPR, "%lf", &CPR_number);

  fseek(cp, 0L, SEEK_END);
  lines = ftell(cp)/12;

  current_line = ftell(cp)/2 - ((ftell(cp)/2) % 12);

  for (i = 0; i < log10(lines)/log10(2); i++) {

    fseek(cp, current_line, SEEK_SET);

    /* Read CPR as string */
    fscanf(cp, "%[0-9]", CPR_check_string);

    /* Convert to number */
    sscanf(CPR_check_string, "%lf", &CPR_check);

    if (CPR_number == CPR_check) {
      printf("This happens\n");
      *position = ftell(cp);
      return TRUE;
    } else if (CPR_number < CPR_check) {
      current_line = ftell(cp)/2 - ((ftell(cp)/2) % 12);
    } else if (CPR_number > CPR_check) {
      current_line = ftell(cp) + ftell(cp)/2 - ((ftell(cp) + ftell(cp)/2) % 12);
    }
  }

  return FALSE;
}

It doesn't seem to run the rest of the code.

Thanks in advance.


问:
Writing the xpath for the below code
Below is a code snippet from one of my project for which I need the xpath of a certain element.

```<code><div class="panel panel-default">
   <div class="panel-body">
      <div class="row">
         <div class="col-md-5 text-right boldText">Service Group Id:</div>
         <div class="col-md-5 ng-binding">436095</div>
      </div>
   </div>
</div>
</code>```

I need the xpath for 436095 element.But, the class is same for some other elements, so I can't use the same and the text is also different. So i wanted a generic solution and used the xpath as

```<code>//div[contains(text(),"Service Order Id:")]/../div[2]
</code>```

But this doesn't work. Kindly suggest me a better solution.

答:
You can try with the below xpaths. It will work for you.</p>

```<code>//div[@class='row']/child::div[2]
//div[@class='col-md-5 text-right boldText']/following-sibling::div
//div[contains(.,'Service Group Id:')]/following-sibling::div
</code>```

Title: Writing the xpath for the below code

Body:
Below is a code snippet from one of my project for which I need the xpath of a certain element.

Service Group Id:

436095

I need the xpath for 436095 element.But, the class is same for some other elements, so I can't use the same and the text is also different. So i wanted a generic solution and used the xpath as

//div[contains(text(),"Service Order Id:")]/../div[2]

But this doesn't work. Kindly suggest me a better solution.

Body:
You can try with the below xpaths. It will work for you.

//div[@class='row']/child::div[2]
//div[@class='col-md-5 text-right boldText']/following-sibling::div
//div[contains(.,'Service Group Id:')]/following-sibling::div


问:
Does MediaPlayer have problems with playing files with # in their paths?
I've noticed recently that the audioplayer developed by me stopped playing.

It turned out that MediaPlayer.prepare() threw an exception:

```<code>"Prepare failed.: status=0x1"
</code>```

The file name contained # symbol. After I removed #, it could be played back. I just removed # symbol. The file path itself was long and contained spaces, [ etc.

```<code>final Uri uri = Uri.parse("/storage/sdcard1/audio/Die Toten Hosen/03 - Boxed Set/2007 - Die DTH Jubiläumsedition [17 CD Boxed Set Remasted]/CD 1 - Opel-Gang/18. Radio Argentina #1.mp3");
mediaPlayer.reset();
mediaPlayer.setDataSource(context, uri);
</code>```

The question is why when I transfer files to my phone with

```<code>adb push /tmp/ /storage/sdcard1/audio/
</code>```

and some of them contain ? symbols, then they are skipped (or an errors/warning occur. Don't remember exactly), but the files that had # in their names were copied successfully. If there are some escaping rules then problems should be the same with files containing ? and files containing #.

Because I don't see any logic in what happened. It looks like there is no central place defining what should be escaped and how.

答:
Because you are passing a Uri into the audioplayer, # and ? are special characters. Within a Uri, a hash # is known as a Fragment Identifier, which for example automatically skips a web page down to a certain anchor tag, or skips plaback to a given start time. A question mark ? in a Uri allows for query paramaters, extra arguments that may be used by whatever is consuming the Uri.

As these are special characters in the context of a Uri, this is why playback is initially failing, and works once the files are renamed. You can escape these special characters by using URLEncoder.encode()

public static String encode(String s,
              String enc)
                       throws UnsupportedEncodingException

Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme. This method uses the supplied encoding scheme to obtain the bytes for unsafe characters.
  Note: The World Wide Web Consortium Recommendation states that UTF-8 should be used. Not doing so may introduce incompatibilites.

Parameters:

s - String to be translated.

enc - The name of a supported character encoding.

Returns:
  the translated String.

So in your case:

```<code>final String encoded = URLEncoder.encode("/storage/sdcard1/audio/Die Toten Hosen/03 - Boxed Set/2007 - Die DTH Jubiläumsedition [17 CD Boxed Set Remasted]/CD 1 Opel-Gang/18. Radio Argentina #1.mp3", "UTF-8");
final Uri uri = Uri.parse(encoded);
mediaPlayer.reset();
mediaPlayer.setDataSource(context, uri);
</code>```

Body:
I've noticed recently that the audioplayer developed by me stopped playing.

It turned out that MediaPlayer.prepare() threw an exception:

"Prepare failed.: status=0x1"

The file name contained # symbol. After I removed #, it could be played back. I just removed # symbol. The file path itself was long and contained spaces, [ etc.

final Uri uri = Uri.parse("/storage/sdcard1/audio/Die Toten Hosen/03 - Boxed Set/2007 - Die DTH Jubiläumsedition [17 CD Boxed Set Remasted]/CD 1 - Opel-Gang/18. Radio Argentina #1.mp3");
mediaPlayer.reset();
mediaPlayer.setDataSource(context, uri);

The question is why when I transfer files to my phone with

adb push /tmp/ /storage/sdcard1/audio/

and some of them contain ? symbols, then they are skipped (or an errors/warning occur. Don't remember exactly), but the files that had # in their names were copied successfully. If there are some escaping rules then problems should be the same with files containing ? and files containing #.

Because I don't see any logic in what happened. It looks like there is no central place defining what should be escaped and how.

Body:
Because you are passing a Uri into the audioplayer, # and ? are special characters. Within a Uri, a hash # is known as a Fragment Identifier, which for example automatically skips a web page down to a certain anchor tag, or skips plaback to a given start time. A question mark ? in a Uri allows for query paramaters, extra arguments that may be used by whatever is consuming the Uri.

As these are special characters in the context of a Uri, this is why playback is initially failing, and works once the files are renamed. You can escape these special characters by using URLEncoder.encode()

public static String encode(String s,
              String enc)
                       throws UnsupportedEncodingException

Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme. This method uses the supplied encoding scheme to obtain the bytes for unsafe characters.
  Note: The World Wide Web Consortium Recommendation states that UTF-8 should be used. Not doing so may introduce incompatibilites.

Parameters:

s - String to be translated.

enc - The name of a supported character encoding.

Returns:
  the translated String.

So in your case:

final String encoded = URLEncoder.encode("/storage/sdcard1/audio/Die Toten Hosen/03 - Boxed Set/2007 - Die DTH Jubiläumsedition [17 CD Boxed Set Remasted]/CD 1 Opel-Gang/18. Radio Argentina #1.mp3", "UTF-8");
final Uri uri = Uri.parse(encoded);
mediaPlayer.reset();
mediaPlayer.setDataSource(context, uri);


问:
ASP.NET Forms Authentication - JavaScript errors on Login page (when anonymous users visit)
On my Login page only I am getting 18 JavaScript errors and the main one seems to be: 'ASP.NET Ajax client-side framework failed to load.' I have a feeling it has to do with security since I just recently added Forms Authentication to the site. If I login all errors go away.

It seems like sys is undefined when this line tries to run  :

```<code>if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
</code>```

I have the following in my Web.config:

```<code><authentication mode="Forms">
  <forms name=".FormsAuthCookie" loginUrl="Security/Login" protection="All" timeout="120" cookieless="AutoDetect" />
</authentication>
<authorization>
  <deny users="?"/>
</authorization>
</code>```

THE MAIN PROBLEM after adding deny users="?":
ASP.NET Ajax client-side framework is failing to load on my Login.aspx page when an anonymous user visits the site.

UPDATE:::

This really doesn't make much sense but after adding EnableCdn="true" to my script manager I do not get any errors when an anonymous user visits the login page.... It just seems like it is a hack for whatever my actual problem is since this is a clean .net webforms project.

```<code><asp:ScriptManager runat="server" EnableCdn="True">
</code>```

答:
Based on the accepted answer above here is the web.config configuration needed if you are working with the Visual Studio 2015 ASP.NET 4.5 WebForms Application project template:

```<code><location path="bundles">
  <system.web>
    <authorization>
      <allow users="*"/>
    </authorization>
  </system.web>
</location>
</code>```

The bundles folder does not physically exist but is the virtual path for the bundled scripts. See App_Start\BundleConfig.cs for more information.

Please note that allowing access to ScriptResource.axd and/or WebResource.axd in web.config as suggested over and over again in so many other threads just will not work with the bundling setup of the Visual Studio 2015 ASP.NET 4.5 WebForms Application project template.

Body:
On my Login page only I am getting 18 JavaScript errors and the main one seems to be: 'ASP.NET Ajax client-side framework failed to load.' I have a feeling it has to do with security since I just recently added Forms Authentication to the site. If I login all errors go away.

It seems like sys is undefined when this line tries to run  :

if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');

I have the following in my Web.config:

<authentication mode="Forms">
  <forms name=".FormsAuthCookie" loginUrl="Security/Login" protection="All" timeout="120" cookieless="AutoDetect" />
</authentication>
<authorization>
  <deny users="?"/>
</authorization>

THE MAIN PROBLEM after adding deny users="?":
ASP.NET Ajax client-side framework is failing to load on my Login.aspx page when an anonymous user visits the site.

UPDATE:::

This really doesn't make much sense but after adding EnableCdn="true" to my script manager I do not get any errors when an anonymous user visits the login page.... It just seems like it is a hack for whatever my actual problem is since this is a clean .net webforms project.

<asp:ScriptManager runat="server" EnableCdn="True">

Body:
Based on the accepted answer above here is the web.config configuration needed if you are working with the Visual Studio 2015 ASP.NET 4.5 WebForms Application project template:

<location path="bundles">
  <system.web>
    <authorization>
      <allow users="*"/>
    </authorization>
  </system.web>
</location>

The bundles folder does not physically exist but is the virtual path for the bundled scripts. See App_Start\BundleConfig.cs for more information.

Please note that allowing access to ScriptResource.axd and/or WebResource.axd in web.config as suggested over and over again in so many other threads just will not work with the bundling setup of the Visual Studio 2015 ASP.NET 4.5 WebForms Application project template.


问:
Swift - Taking a value from a cell that's being deleted and applying it elsewhere
I'm a beginner with Swift.

I'm building a budgeting app for practice and I made a purchase history using a TableView with custom cells that contain 4 labels--amount spent, description, date, and a hidden tag to mark which category the purchase was made (For example, a "1" might indicate that an entry was made in the food category).

I'm trying to implement a way for the user to delete a cell from the spending history, and based on the tag of the entry that is being deleted, have the amount spent be returned to the appropriate category.

答: When you displaying data in cell you fill labels with data by index of this cell. So you can get this data by cell index. So when cell deleting you know indexPaht for this cell.</p>


问:
Bootstrap, Popper is missing even after importing bootstrap bundle
I'm struggling with bootstrap4. I've imported the bootstrap.bundle.js which already contain popper.js.

But anyway I get the following error:

```<code>Uncaught ReferenceError: Popper is not defined
</code>```

Including structure

```<code><script type="text/javascript" src=".../js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src=".../js/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src=".../js/bootstrap.min.js"></script>
</code>```

答:
Add popper.min.js to your file

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
</code>```

Body:
I'm struggling with bootstrap4. I've imported the bootstrap.bundle.js which already contain popper.js.

But anyway I get the following error:

Uncaught ReferenceError: Popper is not defined

Including structure

Body:
Add popper.min.js to your file

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>


问:
How to add lines between JTable rows?
I have a JTable and could not make visible the lines between rows or maybe there is no line, I am not sure. Here is my JTable:

How can I make it look like this?

Here is my code:

```<code>public class NodePropertyWindow extends JFrame{

public NodePropertyWindow(CytoVisProject cytoVisProject, CyNode node){
    this.cytoVisProject = cytoVisProject;
    this.adapter = cytoVisProject.getAdapter();
    this.node = node;
    this.setMinimumSize(new Dimension(400, 400));
    this.setPreferredSize(new Dimension(400,400));
    this.setTitle("Node Property Window");
    this.setVisible(true);
    this.initializeTable();
}

public void initializeTable(){
    CyApplicationManager manager = this.adapter.getCyApplicationManager();
    CyNetworkView networkView = manager.getCurrentNetworkView();
    CyNetwork network = networkView.getModel();
    CyTable cyTable = network.getDefaultNodeTable();

    FilterUtil filterUtil = new FilterUtil(network, cyTable);
    Map<String, Object> sampleRow = cyTable.getAllRows().get(filterUtil.findIndex(filterUtil.getAllNodes(), node)).getAllValues();
    Collection<Object> values = sampleRow.values();
    Set<String> attributeNames = sampleRow.keySet();

    String[] columnNames = {"Attribute Name", "Value"};
    this.data = new Object[values.size()][2];
    Object[] attributeNamesObjects = attributeNames.toArray();
    Iterator iterator = values.iterator();

    for(i=0; i<values.size(); i++){
        this.data[i][0] = attributeNamesObjects[i];
        Object object = iterator.next();
        this.data[i][1] = object;

    }
    // Above part is about the content of JTable
    TableModel model = new DefaultTableModel(this.data, columnNames){
        public boolean isCellEditable(int row, int column){
            return false;
        }
    };

    this.table = new JTable(this.data, columnNames);
    this.table.setModel(model);
    this.table.setPreferredScrollableViewportSize(new Dimension(500,300));
    this.table.setFillsViewportHeight(true);
    this.table.setLayout(new BorderLayout());
    Container container = new Container();
    container.setLayout(new BorderLayout());
    container.add(table.getTableHeader(), BorderLayout.PAGE_START);
    container.add(table, BorderLayout.CENTER);
    this.add(container);
}
}
</code>```

This part is inside of a class which extends JFrame.

答:
Just put this one. I choose black color because Jtable gridlines are white as the default color.</p>

```<code>table.setGridColor(Color.BLACK)
</code>```

Title: How to add lines between JTable rows?

Body:
I have a JTable and could not make visible the lines between rows or maybe there is no line, I am not sure. Here is my JTable:

How can I make it look like this?

Here is my code:

public class NodePropertyWindow extends JFrame{

public NodePropertyWindow(CytoVisProject cytoVisProject, CyNode node){
    this.cytoVisProject = cytoVisProject;
    this.adapter = cytoVisProject.getAdapter();
    this.node = node;
    this.setMinimumSize(new Dimension(400, 400));
    this.setPreferredSize(new Dimension(400,400));
    this.setTitle("Node Property Window");
    this.setVisible(true);
    this.initializeTable();
}

public void initializeTable(){
    CyApplicationManager manager = this.adapter.getCyApplicationManager();
    CyNetworkView networkView = manager.getCurrentNetworkView();
    CyNetwork network = networkView.getModel();
    CyTable cyTable = network.getDefaultNodeTable();

    FilterUtil filterUtil = new FilterUtil(network, cyTable);
    Map<String, Object> sampleRow = cyTable.getAllRows().get(filterUtil.findIndex(filterUtil.getAllNodes(), node)).getAllValues();
    Collection<Object> values = sampleRow.values();
    Set<String> attributeNames = sampleRow.keySet();

    String[] columnNames = {"Attribute Name", "Value"};
    this.data = new Object[values.size()][2];
    Object[] attributeNamesObjects = attributeNames.toArray();
    Iterator iterator = values.iterator();

    for(i=0; i<values.size(); i++){
        this.data[i][0] = attributeNamesObjects[i];
        Object object = iterator.next();
        this.data[i][1] = object;

    }
    // Above part is about the content of JTable
    TableModel model = new DefaultTableModel(this.data, columnNames){
        public boolean isCellEditable(int row, int column){
            return false;
        }
    };

    this.table = new JTable(this.data, columnNames);
    this.table.setModel(model);
    this.table.setPreferredScrollableViewportSize(new Dimension(500,300));
    this.table.setFillsViewportHeight(true);
    this.table.setLayout(new BorderLayout());
    Container container = new Container();
    container.setLayout(new BorderLayout());
    container.add(table.getTableHeader(), BorderLayout.PAGE_START);
    container.add(table, BorderLayout.CENTER);
    this.add(container);
}
}

This part is inside of a class which extends JFrame.

Body:
Just put this one. I choose black color because Jtable gridlines are white as the default color.

table.setGridColor(Color.BLACK)


问:
Blocked requests by default to https self signed backend
On my staging server I am connecting to self-signed https api backend. And by default requests can't be made, because browser treat backend as danger.

I have to open backend url in browser

https://my-api-backend.elasticbeanstalk.com

my-api-backend.elasticbeanstalk.com:8443 uses an invalid security certificate. The certificate is not trusted because it is self-signed. The certificate is not valid for the name my-api-backend.elasticbeanstalk.com. Error code: SEC_ERROR_UNKNOWN_ISSUER

After manually confirm that is secure it works. It is fine for me to do this, but not for managers etc. Another thing I was thinking about blocking backend access from outside and allow access only from frontend.

Is there any solution to this problem other than buying domain a sign it properly?

答:
If it is a staging environment it should reflect a production environment so you should use a real domain signed correctly.

Certificates are free through AWS ACM or LetsEncrypt.

Why not use a sub domain like staging.domain.com, it would be free as well. Otherwise domains are cheap and it shouldn't be worth the hassle.


问:
no String-argument constructor/factory method to deserialize from String value when it is a Integer
I am trying to deserialise the following xml into the objects:

```<code><?xml version="1.0" encoding="iso-8859-1" ?>
   <foo>
     <dean>
      <bar>28</bar>
      <bar>31</bar>
    </dean>
  </foo>
</code>```

My classes are the following

```<code>public class Foo {

private final Dean dean;

public Foo(@JacksonXmlProperty(localName = "dean") final Dean dean) {
    this.dean = dean;
}

public Dean getDean() {
    return dean;
}
}

public class Dean {

@JacksonXmlElementWrapper(useWrapping = false)
private final List<Bar> bar;

public Dean(@JacksonXmlProperty(localName = "bar") final List<Bar> bar) {
    this.bar = bar;
}

public List<Bar> getBar() {
    return bar;
}
}

public class Bar {

@JacksonXmlText
private Integer value;

public Bar(@JacksonXmlProperty(localName = " ") Integer value) {
    this.value = value;
}

public Integer getValue() {
    return value;
}
}
</code>```

My mapper dependencies are the following:

```<code>gradle
ext {
jacksonVersion = "2.8.9"
</code>```

}

```<code>compile(group: "com.fasterxml.jackson.dataformat", name: "jackson-dataformat-
xml", version: "$jacksonVersion")
compile(group: "com.fasterxml.jackson.datatype", name: "jackson-datatype-
jsr310", version: "$jacksonVersion")enter code here
</code>```

Here is the failing test with exception being thrown by the xmlMapper

```<code>@Test
public void shouldParseAndCreateObject() throws Exception {
    final JacksonXmlModule jacksonXmlModule = new JacksonXmlModule();
     XmlMapper xmlMapper = (XmlMapper) new XmlMapper(jacksonXmlModule)
            .disable(FAIL_ON_UNKNOWN_PROPERTIES, FAIL_ON_IGNORED_PROPERTIES);
    Foo foo = xmlMapper.readValue("<?xml version=\"1.0\" encoding=\"iso-8859-
1\" ?>\n" +
            "<foo>\n" +
            "    <dean>\n" +
            "        <bar>28</bar>\n" +
            "        <bar>31</bar>\n" +
            "    </dean>\n" +
            "</foo>", Foo.class);
    assertThat(foo.getDean().getBar().get(0).getValue(), is(28));
}

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of Bar: no String-argument constructor/factory method to deserialize from String value ('28')
</code>```

at [Source: out/test/resources/test.xml; line: 4, column: 16] (through reference chain: service.Foo["dean"]->service.Dean["bar"]->java.util.ArrayList[0])

From reading the exception it looks like the mapper is treating the value 28 as a string rather than a Integer but if i change the Bar class to the following and add an attribute to element bar to the raw xml the same test passes.

```<code>public class Bar {

private String test;

@JacksonXmlText
private Integer value;

public Bar(@JacksonXmlProperty(localName = "test", isAttribute = true) String
test, @JacksonXmlProperty(localName = " ") Integer value) {
    this.test = test;
    this.value = value;
}

public String getTest() {
    return test;
}

public Integer getValue() {
    return value;
}

<?xml version="1.0" encoding="iso-8859-1" ?>
<foo>
<dean>
    <bar test="haha1">28</bar>
    <bar test="haha2">31</bar>
</dean>
</foo>

@Test
public void shouldParseAndCreateObject() throws Exception {
    final JacksonXmlModule jacksonXmlModule = new JacksonXmlModule();
     XmlMapper xmlMapper = (XmlMapper) new XmlMapper(jacksonXmlModule)
            .disable(FAIL_ON_UNKNOWN_PROPERTIES, FAIL_ON_IGNORED_PROPERTIES);
    Foo foo = xmlMapper.readValue("<?xml version=\"1.0\" encoding=\"iso-8859-
1\" ?>\n" +
            "<foo>\n" +
            "    <dean>\n" +
            "        <bar test=\"haha1\">28</bar>\n" +
            "        <bar test=\"haha2\">31</bar>\n" +
            "    </dean>\n" +
            "</foo>" +
            "</foo>", Foo.class);
    assertThat(foo.getDean().getBar().get(0).getValue(), is(28));
}
</code>```

I would say that the Mapper should infer the type from the constructor parameter type and try to instantiate that object with the string value and under the hood do something like Integer.valueOf("28")

答:
Add to POJO empty constructor and also for all fields.
Also try the following:</p>

```<code>JacksonXmlModule module = new JacksonXmlModule();
module.setDefaultUseWrapper(false);
XmlMapper xmlMapper = new XmlMapper(module);
</code>```

Body:
I am trying to deserialise the following xml into the objects:

<?xml version="1.0" encoding="iso-8859-1" ?>
   <foo>
     <dean>
      <bar>28</bar>
      <bar>31</bar>
    </dean>
  </foo>

My classes are the following

public class Foo {

private final Dean dean;

public Foo(@JacksonXmlProperty(localName = "dean") final Dean dean) {
    this.dean = dean;
}

public Dean getDean() {
    return dean;
}
}

public class Dean {

@JacksonXmlElementWrapper(useWrapping = false)
private final List<Bar> bar;

public Dean(@JacksonXmlProperty(localName = "bar") final List<Bar> bar) {
    this.bar = bar;
}

public List<Bar> getBar() {
    return bar;
}
}

public class Bar {

@JacksonXmlText
private Integer value;

public Bar(@JacksonXmlProperty(localName = " ") Integer value) {
    this.value = value;
}

public Integer getValue() {
    return value;
}
}

My mapper dependencies are the following:

gradle
ext {
jacksonVersion = "2.8.9"

}

compile(group: "com.fasterxml.jackson.dataformat", name: "jackson-dataformat-
xml", version: "$jacksonVersion")
compile(group: "com.fasterxml.jackson.datatype", name: "jackson-datatype-
jsr310", version: "$jacksonVersion")enter code here

Here is the failing test with exception being thrown by the xmlMapper

@Test
public void shouldParseAndCreateObject() throws Exception {
    final JacksonXmlModule jacksonXmlModule = new JacksonXmlModule();
     XmlMapper xmlMapper = (XmlMapper) new XmlMapper(jacksonXmlModule)
            .disable(FAIL_ON_UNKNOWN_PROPERTIES, FAIL_ON_IGNORED_PROPERTIES);
    Foo foo = xmlMapper.readValue("<?xml version=\"1.0\" encoding=\"iso-8859-
1\" ?>\n" +
            "<foo>\n" +
            "    <dean>\n" +
            "        <bar>28</bar>\n" +
            "        <bar>31</bar>\n" +
            "    </dean>\n" +
            "</foo>", Foo.class);
    assertThat(foo.getDean().getBar().get(0).getValue(), is(28));
}

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of Bar: no String-argument constructor/factory method to deserialize from String value ('28')

at [Source: out/test/resources/test.xml; line: 4, column: 16] (through reference chain: service.Foo["dean"]->service.Dean["bar"]->java.util.ArrayList[0])

From reading the exception it looks like the mapper is treating the value 28 as a string rather than a Integer but if i change the Bar class to the following and add an attribute to element bar to the raw xml the same test passes.

public class Bar {

private String test;

@JacksonXmlText
private Integer value;

public Bar(@JacksonXmlProperty(localName = "test", isAttribute = true) String
test, @JacksonXmlProperty(localName = " ") Integer value) {
    this.test = test;
    this.value = value;
}

public String getTest() {
    return test;
}

public Integer getValue() {
    return value;
}

<?xml version="1.0" encoding="iso-8859-1" ?>
<foo>
<dean>
    <bar test="haha1">28</bar>
    <bar test="haha2">31</bar>
</dean>
</foo>

@Test
public void shouldParseAndCreateObject() throws Exception {
    final JacksonXmlModule jacksonXmlModule = new JacksonXmlModule();
     XmlMapper xmlMapper = (XmlMapper) new XmlMapper(jacksonXmlModule)
            .disable(FAIL_ON_UNKNOWN_PROPERTIES, FAIL_ON_IGNORED_PROPERTIES);
    Foo foo = xmlMapper.readValue("<?xml version=\"1.0\" encoding=\"iso-8859-
1\" ?>\n" +
            "<foo>\n" +
            "    <dean>\n" +
            "        <bar test=\"haha1\">28</bar>\n" +
            "        <bar test=\"haha2\">31</bar>\n" +
            "    </dean>\n" +
            "</foo>" +
            "</foo>", Foo.class);
    assertThat(foo.getDean().getBar().get(0).getValue(), is(28));
}

I would say that the Mapper should infer the type from the constructor parameter type and try to instantiate that object with the string value and under the hood do something like Integer.valueOf("28")

Body:
Add to POJO empty constructor and also for all fields.
Also try the following:

JacksonXmlModule module = new JacksonXmlModule();
module.setDefaultUseWrapper(false);
XmlMapper xmlMapper = new XmlMapper(module);


问:
Rails ActiveRecord summary statement
How to translate this simple query to ruby on rails ActiveRecord

select sum(current*progress) from features;

i have tried

```<code> @feature = Feature.where(project_detail_id: @project_detail.id )
 @current_progress =  @feature.current * @feature.progress
 @total_current_progress =  @feature.sum(@current_progress)
</code>```

but nothing works
i cannot get @total_current_progress result

thanks in advance

答:
try below code:</p>

```<code>@feature = Feature.where(project_detail_id: @project_detail.id )
@current_progress =  @feature.pluck(:current).map(&:to_f).sum * @feature.pluck(:progress).map(&:to_f).sum
@total_current_progress =  @current_progress
</code>```

Title: Rails ActiveRecord summary statement

Body:
How to translate this simple query to ruby on rails ActiveRecord

select sum(current*progress) from features;

i have tried

 @feature = Feature.where(project_detail_id: @project_detail.id )
 @current_progress =  @feature.current * @feature.progress
 @total_current_progress =  @feature.sum(@current_progress)

but nothing works
i cannot get @total_current_progress result

thanks in advance

Body:
try below code:

@feature = Feature.where(project_detail_id: @project_detail.id )
@current_progress =  @feature.pluck(:current).map(&:to_f).sum * @feature.pluck(:progress).map(&:to_f).sum
@total_current_progress =  @current_progress


问:
Upload image using postman
Hi I got this error whenever i want to upload images in NODE JS (MongoDB)using postman could anyone explain .  Below is the screenshot of the error.
 I use the header content type = image/png and use the raw to upload image

[Error: EACCES: permission denied, open '/home/pavithra/node-mobile/uploads/posts/2209fb177948bc4801dc5f6c244013f5'

    at Error (native)

答:
This issue looks like  npm-permissions issue.
please refer this to manage permissions :-

fixing-npm-permissions

Title: Upload image using postman


问:
How can I find n smallest numbers without changing the order of the first list?
I intend to get the n smallest numbers in a list but keep the numbers in the same order they appear in the list. For example:

This is my list:

```<code>A = [1, 3, 4, 6, 7, 6, 8, 7, 2, 6, 8, 7, 0]
</code>```

I like to get the first three lowest numbers as it has been ordered in the first list:

```<code>[1, 2, 0]
</code>```

I do not want to sort the result as:

```<code>[0, 1, 2]
</code>```

I have tried:

```<code>heapq.nsmallest(3,A)
</code>```

but i wonder if it is possible to retain this list as:[1, 2, 0]

By the way, I'm not a Python coder so thanks for the help in advance.

答:
You can try this:

```<code>new_a = []
A=[1, 3, 4, 6, 7, 6, 8, 7, 2, 6, 8, 7, 0]
for a in A:
   if a not in new_a:
      new_a.append(a)
new_a = [i for i in new_a if i in sorted(new_a)[:3]]
</code>```

Output:

```<code>[1, 2, 0]
</code>```

Body:
I intend to get the n smallest numbers in a list but keep the numbers in the same order they appear in the list. For example:

This is my list:

A = [1, 3, 4, 6, 7, 6, 8, 7, 2, 6, 8, 7, 0]

I like to get the first three lowest numbers as it has been ordered in the first list:

[1, 2, 0]

I do not want to sort the result as:

[0, 1, 2]

I have tried:

heapq.nsmallest(3,A)

but i wonder if it is possible to retain this list as:[1, 2, 0]

By the way, I'm not a Python coder so thanks for the help in advance.

Body:
You can try this:

new_a = []
A=[1, 3, 4, 6, 7, 6, 8, 7, 2, 6, 8, 7, 0]
for a in A:
   if a not in new_a:
      new_a.append(a)
new_a = [i for i in new_a if i in sorted(new_a)[:3]]

Output:

[1, 2, 0]


问:
MySQL joining multiple sql results when all data is in one table
I have a table containing lots of data with several fields including:

```<code>day (Monday ~ Sunday)
City (NY, LA, FL, etc.)
</code>```

I would like to use php to make a table to display totals like this:

```<code>  --- Mon --- Tue --- Wed ...
NY    6       8       9
LA    7       5       3
FL    1       0       4
</code>```

But I am having trouble to write the SQL to make this work. I have used union but that appends the result at the bottom, so it seems I need to use inner join, or not even it. The two queries that I can get remotely close to what I want are:

select city, count(id) as 'Monday' from index where city = "NY" and day = 'Monday' group by city
union all
select city, count(id) as 'Monday' from index where city = 'LA' and day = 'Monday' group by city
union all
select city, count(id) as 'Monday' from index where city = 'FL' and day = 'Monday' group by city

This produces the following result

  --- Mon

  NY    6

  LA        7

  FL        1

The problem with this is I don't know how to add the rest of the days to the right of it

Another query I have tried is

select a.day, a.counts as 'NY', b.counts as 'LA' from
(select day, count(id) as counts from index where city='NY' GROUP BY DAY) as a
left join
(select day, count(id) as counts from index where city='LA' GROUP BY DAY) as b
on (a.day = b.day)
order by field (a.day, 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')

This produces the following result

                 NY --- LA ---

  Monday      6        7

  Tuesday        8        5

And the problem with this one is the row and column should be swapped, also I don't know how to add another city (I have many cities).

All the data is in one table called "index". Could someone give me the guidance on how to write the SQL? I would also need the field to show 0 or Null when there is no record. The end goal is to produce the table with PHP.

Thank you for taking the time to read and answer.

答:
It seem's like you want to pivot the data by the day and group it by City. If this then you can try the following query may this help.

```<code>select city,
sum(case when (day = 'Monday') then  1 else 0 end)  'Monday',
sum(case when (day = 'Tuesday') then  1 else 0 end)  'Tuesday',
sum(case when (day = 'Wednesday') then  1 else 0 end)  'Wednesday',
sum(case when (day = 'Thursday') then  1 else 0 end)  'Thursday',
sum(case when (day = 'Friday') then  1 else 0 end)  'Friday',
sum(case when (day = 'Saturday') then  1 else 0 end)  'Saturday',
 sum(case when (day = 'Sunday') then  1 else 0 end)  'Sunday'

from `index` group by city
</code>```

Body:
I have a table containing lots of data with several fields including:

day (Monday ~ Sunday)
City (NY, LA, FL, etc.)

I would like to use php to make a table to display totals like this:

  --- Mon --- Tue --- Wed ...
NY    6       8       9
LA    7       5       3
FL    1       0       4

But I am having trouble to write the SQL to make this work. I have used union but that appends the result at the bottom, so it seems I need to use inner join, or not even it. The two queries that I can get remotely close to what I want are:

select city, count(id) as 'Monday' from index where city = "NY" and day = 'Monday' group by city
union all
select city, count(id) as 'Monday' from index where city = 'LA' and day = 'Monday' group by city
union all
select city, count(id) as 'Monday' from index where city = 'FL' and day = 'Monday' group by city

This produces the following result

  --- Mon

  NY    6

  LA        7

  FL        1

The problem with this is I don't know how to add the rest of the days to the right of it

Another query I have tried is

select a.day, a.counts as 'NY', b.counts as 'LA' from
(select day, count(id) as counts from index where city='NY' GROUP BY DAY) as a
left join
(select day, count(id) as counts from index where city='LA' GROUP BY DAY) as b
on (a.day = b.day)
order by field (a.day, 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')

This produces the following result

                 NY --- LA ---

  Monday      6        7

  Tuesday        8        5

And the problem with this one is the row and column should be swapped, also I don't know how to add another city (I have many cities).

All the data is in one table called "index". Could someone give me the guidance on how to write the SQL? I would also need the field to show 0 or Null when there is no record. The end goal is to produce the table with PHP.

Thank you for taking the time to read and answer.

Body:
It seem's like you want to pivot the data by the day and group it by City. If this then you can try the following query may this help.

select city,
sum(case when (day = 'Monday') then  1 else 0 end)  'Monday',
sum(case when (day = 'Tuesday') then  1 else 0 end)  'Tuesday',
sum(case when (day = 'Wednesday') then  1 else 0 end)  'Wednesday',
sum(case when (day = 'Thursday') then  1 else 0 end)  'Thursday',
sum(case when (day = 'Friday') then  1 else 0 end)  'Friday',
sum(case when (day = 'Saturday') then  1 else 0 end)  'Saturday',
 sum(case when (day = 'Sunday') then  1 else 0 end)  'Sunday'

from `index` group by city


问:
How to make a dynamic char?
```<code>#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void generarCadena(char *);
void generarDimension(int, void **, int);
void reallocarDimensiones(int , void **, int);

int main(void){
    char *caracter=NULL;
    generarCadena(&caracter);
    printf("%d", sizeof(caracter));
    printf("%s", &caracter);//I want to now why this doesn't print
    return 0;
}

void generarCadena(char *scaneado){
    unsigned int cont;
    char lector;
    generarDimension(1,&scaneado,sizeof(char));
    cont = 0;
    while(!scanf("%s", &scaneado)){
        while((strcpy(lector,getchar())) !='\n' && lector!=EOF){
           reallocarDimensiones(1,&scaneado[cont],sizeof(char));
           cont++;
        }
    }
    printf("%s", &scaneado);/*Inside de function it prints,
    however, it doesn't print outside it*/
}//This function is for the dynamic char

void generarDimension(int bloques, void **ptr, int tamanho){
    *ptr = malloc(bloques * tamanho);
    if(*ptr==NULL){
        printf("No se pudo almacenar memoria\n");
    }
}//This function mallocs any given pointer
void reallocarDimensiones(int bloques, void **ptr, int tamanho){
    *ptr = realloc(*ptr,bloques * tamanho);
    if(*ptr==NULL){
        printf("No se pudo almacenar memoria\n");
    }
}//This function reallocs any given pointer
</code>```

Hi, I want to now how to dynamically store a char while writting it on the keyboard, so I made a function for it. I want to send a char pointer in it, but it doesn't seem to modify it. Another problem I have is that my function only stores a few data, so if the data is to long, my program crashes.

答:
I see something wrong here:

```<code>printf("%s", &caracter);//I want to now why this doesn't print
</code>```

caracter is a char pointer. By using & with caracter you are trying to access the address of the char pointer, and not the contents to which the pointer is pointing.

Change it to

```<code>printf("%s", caracter);
</code>```

Secondly, what is lector initialized to before it is used? See here:

```<code>while((strcpy(lector,getchar())) !='\n' && lector!=EOF)
</code>```

Title: How to make a dynamic char?

Body:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void generarCadena(char *);
void generarDimension(int, void **, int);
void reallocarDimensiones(int , void **, int);

int main(void){
    char *caracter=NULL;
    generarCadena(&caracter);
    printf("%d", sizeof(caracter));
    printf("%s", &caracter);//I want to now why this doesn't print
    return 0;
}

void generarCadena(char *scaneado){
    unsigned int cont;
    char lector;
    generarDimension(1,&scaneado,sizeof(char));
    cont = 0;
    while(!scanf("%s", &scaneado)){
        while((strcpy(lector,getchar())) !='\n' && lector!=EOF){
           reallocarDimensiones(1,&scaneado[cont],sizeof(char));
           cont++;
        }
    }
    printf("%s", &scaneado);/*Inside de function it prints,
    however, it doesn't print outside it*/
}//This function is for the dynamic char

void generarDimension(int bloques, void **ptr, int tamanho){
    *ptr = malloc(bloques * tamanho);
    if(*ptr==NULL){
        printf("No se pudo almacenar memoria\n");
    }
}//This function mallocs any given pointer
void reallocarDimensiones(int bloques, void **ptr, int tamanho){
    *ptr = realloc(*ptr,bloques * tamanho);
    if(*ptr==NULL){
        printf("No se pudo almacenar memoria\n");
    }
}//This function reallocs any given pointer

Hi, I want to now how to dynamically store a char while writting it on the keyboard, so I made a function for it. I want to send a char pointer in it, but it doesn't seem to modify it. Another problem I have is that my function only stores a few data, so if the data is to long, my program crashes.

Body:
I see something wrong here:

printf("%s", &caracter);//I want to now why this doesn't print

caracter is a char pointer. By using & with caracter you are trying to access the address of the char pointer, and not the contents to which the pointer is pointing.

Change it to

printf("%s", caracter);

Secondly, what is lector initialized to before it is used? See here:

while((strcpy(lector,getchar())) !='\n' && lector!=EOF)


问:
Applying lightbox to enfold
I built a wordpress site using enfold and I have this one page where i want to add a lightbox to a list that has pictures so when clicking them they will open in a lightbox but im a bit afraid to mess up the theme itself, any ideas?
Heres the page: http://www.rimi.co.il/זרעים/
In the middle of the page theres a few lists with different types of seeds and i want their pictures to open in a lightbox basically </p>

答:
Don't be afraid to try anything new in wordpress as you have action history on each page there.

You can easily roll back to your page before the changes you applied.

Title: Applying lightbox to enfold


问:
join the SAS datases sideways, horizontal
I have a dataset as following

```<code>ID  A1  A2  A3
A   1.2 1.5 1
A   1.3 1.7 1.3
A   1.4 1.8 1.7
B   1.5 1.8 1.9
B  1.6 1.7 1.0
</code>```

and result I am looking for is

```<code>A   1.2 1.5 1 1.3 1.7 1.3 1.4 1.8 1.7
</code>```

I know that SAS variable names cannot be repeated but when I tried Proc SQL, with inner join it gives me more rows.

答:
Similar to Longfish's but as DOW.  However, in DOW processing you do not need to retain the array items because the wide array is populated within a single iteration of the implicit DATA Step loop.</p>

```<code>* measure the data;
data _null_;
  set have end=last_row;
  by ID;
  array A A1-A3;
  retain max_group_size 0;
  if first.ID then group_size = 0;
  group_size + 1; * implicit retain;
  if last.ID then max_group_size = max (max_group_size, group_size);
  if last_row then do;
    call symputx ('wide_count', max_group_size * dim(A));
  end;
run;

* extrude the data;
data want(keep=ID AX:);
  do _wide_index = 0 by 0 until (last.id);  /* initialize wide_index and loop over group */
    set have;
    by ID;

    array A A1-A3;
    array AX AX1-AX&wide_count; * X is for eXtruded :) ;

    do _small_index = 1 to dim (A);
      _wide_index + 1;
      AX [ _wide_index ] = A [ _small_index ];
    end;
  end;
  * implicit output occurs here because there is no explicit output statement elsewhere in the step;
run;
</code>```

Body:
I have a dataset as following

ID  A1  A2  A3
A   1.2 1.5 1
A   1.3 1.7 1.3
A   1.4 1.8 1.7
B   1.5 1.8 1.9
B  1.6 1.7 1.0

and result I am looking for is

A   1.2 1.5 1 1.3 1.7 1.3 1.4 1.8 1.7

I know that SAS variable names cannot be repeated but when I tried Proc SQL, with inner join it gives me more rows.

Body:
Similar to Longfish's but as DOW.  However, in DOW processing you do not need to retain the array items because the wide array is populated within a single iteration of the implicit DATA Step loop.

* measure the data;
data _null_;
  set have end=last_row;
  by ID;
  array A A1-A3;
  retain max_group_size 0;
  if first.ID then group_size = 0;
  group_size + 1; * implicit retain;
  if last.ID then max_group_size = max (max_group_size, group_size);
  if last_row then do;
    call symputx ('wide_count', max_group_size * dim(A));
  end;
run;

* extrude the data;
data want(keep=ID AX:);
  do _wide_index = 0 by 0 until (last.id);  /* initialize wide_index and loop over group */
    set have;
    by ID;

    array A A1-A3;
    array AX AX1-AX&wide_count; * X is for eXtruded :) ;

    do _small_index = 1 to dim (A);
      _wide_index + 1;
      AX [ _wide_index ] = A [ _small_index ];
    end;
  end;
  * implicit output occurs here because there is no explicit output statement elsewhere in the step;
run;


问:
Javascript - A function that accepts parameter and return a string which contains "x"
```<code>function change(o)
{
  var str = "";
  for (var p = 0; p<=o ;p++)
  {
    temp = p;
    str = str + temp;
    if (p == o){
    }
    else{
      str = str + ",";
    }
  }
console.log(str);
}
change(5);
</code>```

(consolelog will be changed into return, it's just to view the output)

Basically, I am a beginner who recently started and I wanted to make a simple function that returns a value of the function. For example; if change(5) was inputted, it would return a string value of 5 x's, so xxxxx. If it was change(7), it would return me xxxxxxx, so any idea how to do this? Because my code only gives value from 0 to my inputted value.

答:
```<code>function change(count){
   var string = ""; // declare an empty string;
   for(var i=0; i<count; i++){
      string = string + "x"; // keep adding an x in each iteration to the string

   }
   return string; // return the string
}

change(5); // gives xxxxx
</code>```

Body:
function change(o)
{
  var str = "";
  for (var p = 0; p<=o ;p++)
  {
    temp = p;
    str = str + temp;
    if (p == o){
    }
    else{
      str = str + ",";
    }
  }
console.log(str);
}
change(5);

(consolelog will be changed into return, it's just to view the output)

Basically, I am a beginner who recently started and I wanted to make a simple function that returns a value of the function. For example; if change(5) was inputted, it would return a string value of 5 x's, so xxxxx. If it was change(7), it would return me xxxxxxx, so any idea how to do this? Because my code only gives value from 0 to my inputted value.


答:
function createX(num) {
  var str = '';
  for(i=0; i<num; i++){
    str += 'x';
  }
  return str;
}

console.log(createX(5));```

Something like this?

Title: Javascript - A function that accepts parameter and return a string which contains "x"

Body:
function createX(num) {
  var str = '';
  for(i=0; i<num; i++){
    str += 'x';
  }
  return str;
}

console.log(createX(5));

Something like this?


问:
Make the parentheses in function calls optional
Hey, I am about to rewrite the core file for my JavaScript library and I am looking for better ways of doing everything. One of these is how I make parentheses optional, for example some function calls look like this.

```<code>Spark('p').content('Hello, World');
</code>```

And others like this.

```<code>Spark.browser();
</code>```

So I have optional parentheses for the Spark function. Am I right in saying this would be the best way?

```<code>window.Spark = function(arg1, arg2) {
    return {
        fn: function() {
            alert('run');
        }
    };
};

for(var f in Spark())
    Spark[f] = Spark()[f];

Spark.fn();
Spark(true, false).fn();
</code>```

It just seems wrong to me although it is the only method I have come up with that works.

答:
Yes it is possible, but why would you do that? To make JavaScript look like the few other languages (like VB and Delphi) that don't need the parentheses (brackets are those square thingies) for functions?
The creators of JavaScript have decided that a function should be called with parentheses, regardless of the amount of parameters. You are actually making properties that refer to function results just to skip two characters.

I think what you are actually looking for, is a class or object. You could write this:

```<code>function MyClass(Parameter /*optional*/)
{
  // Initialization (optional)
  this.anyProperty = parameter;

  this.anyMethod = function(p)
  {
    alert(p);
  }
}

// Or declare methods like this (faster and more efficient)
MyClass.prototype.anyMethod2 = function(p)
{
  alert(p);
}
</code>```

Now, you can instantiate this class and call methods:

```<code>var c = new MyClass;
c.anyMethod2('Hello world!');
</code>```

This is only a small example, but you should really read about declaring and using classes, because I think that might be what you're looking for.

ContentLicense: CC BY-SA 2.5

Body:
Hey, I am about to rewrite the core file for my JavaScript library and I am looking for better ways of doing everything. One of these is how I make parentheses optional, for example some function calls look like this.

Spark('p').content('Hello, World');

And others like this.

Spark.browser();

So I have optional parentheses for the Spark function. Am I right in saying this would be the best way?

window.Spark = function(arg1, arg2) {
    return {
        fn: function() {
            alert('run');
        }
    };
};

for(var f in Spark())
    Spark[f] = Spark()[f];

Spark.fn();
Spark(true, false).fn();

It just seems wrong to me although it is the only method I have come up with that works.

Body:
Yes it is possible, but why would you do that? To make JavaScript look like the few other languages (like VB and Delphi) that don't need the parentheses (brackets are those square thingies) for functions?
The creators of JavaScript have decided that a function should be called with parentheses, regardless of the amount of parameters. You are actually making properties that refer to function results just to skip two characters.

I think what you are actually looking for, is a class or object. You could write this:

function MyClass(Parameter /*optional*/)
{
  // Initialization (optional)
  this.anyProperty = parameter;

  this.anyMethod = function(p)
  {
    alert(p);
  }
}

// Or declare methods like this (faster and more efficient)
MyClass.prototype.anyMethod2 = function(p)
{
  alert(p);
}

Now, you can instantiate this class and call methods:

var c = new MyClass;
c.anyMethod2('Hello world!');

This is only a small example, but you should really read about declaring and using classes, because I think that might be what you're looking for.


问:
center image in html mail
How can I center an image in a html mail that it works in outlook as well.

I tried this:

```<code><th align="center">
        <center data-parsed="" class="logo">
            <img src="[%embedded-image(1335);logo.png]" alt="" width="207" height="55" border="0"/>
        </center>
</th>
</code>```

as well tried like this

```<code><p style="text-align: center"><img src="[%embedded-image(1335);logo.png]" alt="" width="207" height="55" border="0"/></>
</code>```

In browser it looks nice. But in outlook not.

What could be a working solution?

thanks.

答:
 has been deprecated in favour of text-align: center.

Deprecated
 This feature has been removed from the Web standards. Though some browsers may still support it, it is in the
  process of being dropped. Avoid using it and update existing code if
  possible; see the compatibility table at the bottom of this page to
  guide your decision. Be aware that this feature may cease to work at
  any time.

Ref:  - HTML | MDN

Consider using:

text-align: center instead on the containing element (th) of the
img element, or

display: block; margin: auto on the nested img element

...as demonstrated in the embedded code snippet below.

Code Snippet Demonstration:

*:not(code) {
  font-family: arial;
}

code {
  background: #cccccc;
  padding: 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css">

<table style="border: 1px solid gray; width: 600px; border-collapse: collapse;">
  <tr>
    <th align="center" style="border: 1px solid gray; background: whitesmoke; padding: 10px;">
      Using <code>align="center"</code> attribute <sup><small><i class="fa fa-thumbs-o-down"></i> (deprecated)</small></sup> on containing element
    </th>
  </tr>
  <tr>
    <th align="center" style="border: 1px solid gray; padding: 10px;">
      <img src="https://placehold.it/207x55" alt="" width="207" height="55" border="0"/>
    </th>
  </tr>
</table>
<br>
<table style="border: 1px solid gray; width: 600px; border-collapse: collapse;">
  <tr>
    <th align="center" style="border: 1px solid gray; background: whitesmoke; padding: 10px;">
      Using <code>text-align:center</code> inline-style property on containing element
    </th>
  </tr>
  <tr>
    <th style="border: 1px solid gray; padding: 10px; text-align: center;">
      <img src="https://placehold.it/207x55" alt="" width="207" height="55" border="0" style="display: inline-block;"/>
    </th>
  </tr>
  <tr>
    <td style="padding: 10px;">
      <p>In most cases declaring <code>text-align: center</code> on the containing parent element is enough since <code>img</code> elements are inheritly <em>inline</em>. But to ensure that this behaviour is consistent across all email clients declare <code>display: inline-block</code> on the nested <code>img</code> as well.</p>
    </td>
  </tr>
</table>
<br>
<table style="border: 1px solid gray; width: 600px; border-collapse: collapse;">
  <tr>
    <th align="center" style="border: 1px solid gray; background: whitesmoke; padding: 10px;">
      Using <code>display: block; margin: auto;</code> inline-style properties on nested <code>img</code>
    </th>
  </tr>
  <tr>
    <th style="border: 1px solid gray; padding: 10px;">
      <img src="https://placehold.it/207x55" alt="" width="207" height="55" border="0" style="margin: auto; display: block;"/>
    </th>
  </tr>
</table></code>```

Summary:

To center align an inline element horizontally, you need to:

declare text-align: center on the containing (parent) element

To center align a block element horizontally, you need to:

declare margin: auto on the block element

ensure that it is defined as a block element (display: block)

ensure a specified width is defined (width: 207px)

Vertical & Horizontal Alignment Demonstrations:

For Reference Sake.

Horizontal Alignment (Arbitrary Elements)

Horizontal Alignment (Text Elements)

Vertical Alignment (Arbitrary Elements)

Vertical Alignment (Text Elements)

Title: center image in html mail

Body:
How can I center an image in a html mail that it works in outlook as well.

I tried this:

as well tried like this

</>

In browser it looks nice. But in outlook not.

What could be a working solution?

thanks.

Body:
<center> has been deprecated in favour of text-align: center.

Deprecated
 This feature has been removed from the Web standards. Though some browsers may still support it, it is in the
  process of being dropped. Avoid using it and update existing code if
  possible; see the compatibility table at the bottom of this page to
  guide your decision. Be aware that this feature may cease to work at
  any time.

Ref: <center> - HTML | MDN

Consider using:

text-align: center instead on the containing element (th) of the
img element, or

display: block; margin: auto on the nested img element

...as demonstrated in the embedded code snippet below.

Code Snippet Demonstration:

*:not(code) {
  font-family: arial;
}

code {
  background: #cccccc;
  padding: 3px;
}

<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css">

<table style="border: 1px solid gray; width: 600px; border-collapse: collapse;">
  <tr>
    <th align="center" style="border: 1px solid gray; background: whitesmoke; padding: 10px;">
      Using <code>align="center"</code> attribute <sup><small><i class="fa fa-thumbs-o-down"></i> (<a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th#Attributes" target="_blank">deprecated</a>)</small></sup> on containing element
    </th>
  </tr>
  <tr>
    <th align="center" style="border: 1px solid gray; padding: 10px;">
      <img src="https://placehold.it/207x55" alt="" width="207" height="55" border="0"/>
    </th>
  </tr>
</table>
<br>
<table style="border: 1px solid gray; width: 600px; border-collapse: collapse;">
  <tr>
    <th align="center" style="border: 1px solid gray; background: whitesmoke; padding: 10px;">
      Using <code>text-align:center</code> inline-style property on containing element
    </th>
  </tr>
  <tr>
    <th style="border: 1px solid gray; padding: 10px; text-align: center;">
      <img src="https://placehold.it/207x55" alt="" width="207" height="55" border="0" style="display: inline-block;"/>
    </th>
  </tr>
  <tr>
    <td style="padding: 10px;">
      <p>In most cases declaring <code>text-align: center</code> on the containing parent element is enough since <code>img</code> elements are inheritly <em>inline</em>. But to ensure that this behaviour is consistent across all email clients declare <code>display: inline-block</code> on the nested <code>img</code> as well.</p>
    </td>
  </tr>
</table>
<br>
<table style="border: 1px solid gray; width: 600px; border-collapse: collapse;">
  <tr>
    <th align="center" style="border: 1px solid gray; background: whitesmoke; padding: 10px;">
      Using <code>display: block; margin: auto;</code> inline-style properties on nested <code>img</code>
    </th>
  </tr>
  <tr>
    <th style="border: 1px solid gray; padding: 10px;">
      <img src="https://placehold.it/207x55" alt="" width="207" height="55" border="0" style="margin: auto; display: block;"/>
    </th>
  </tr>
</table>

Summary:

To center align an inline element horizontally, you need to:

declare text-align: center on the containing (parent) element

To center align a block element horizontally, you need to:

declare margin: auto on the block element

ensure that it is defined as a block element (display: block)

ensure a specified width is defined (width: 207px)

Vertical & Horizontal Alignment Demonstrations:

For Reference Sake.

Horizontal Alignment (Arbitrary Elements)

Horizontal Alignment (Text Elements)

Vertical Alignment (Arbitrary Elements)

Vertical Alignment (Text Elements)


问:
getting GMSServicesException error
Am trying to execute my project, while going to home page itself am getting this error and app is crashing

Terminating app due to uncaught exception 'GMSServicesException', reason: 'Google Maps SDK for iOS requires GoogleMaps.bundle to be part of your target under 'Copy Bundle Resources''

答: If you installed it via Cocoapods, the only solution I have found so far is removing it from the podfile, updating pods, then putting in back in the podfile and updating again.</p>

Title: getting GMSServicesException error


问:
How to find maximum value in a list of arrays
I have a very large list of arrays that looks something like this:

```<code>'apples': array([1,2,3,4]), 'pears': array([1,2,10,11]),'oranges': array([1,10,10,3])
</code>```

I want to find the maximum value out of all the arrays. In my short example above it would be 11.

I am struggling to write something that would give me the maximum value for all arrays in the list. Any thoughts would be welcome.

答:
First create a new list that contains the max values from each dictionary element then get the max of that new list</p>

```<code>dict = {"apples" : [1, 2, 8, 4], "fruits": [3,2,6]}

maxlst = [max(el) for el in dict.values()]
print(max(maxlst))
</code>```

Body:
I have a very large list of arrays that looks something like this:

'apples': array([1,2,3,4]), 'pears': array([1,2,10,11]),'oranges': array([1,10,10,3])

I want to find the maximum value out of all the arrays. In my short example above it would be 11.

I am struggling to write something that would give me the maximum value for all arrays in the list. Any thoughts would be welcome.

Body:
First create a new list that contains the max values from each dictionary element then get the max of that new list

dict = {"apples" : [1, 2, 8, 4], "fruits": [3,2,6]}

maxlst = [max(el) for el in dict.values()]
print(max(maxlst))


问:
Is there used incorrect terminology in description of a compile error as to 'for' syntax in golang?
I tried to use something like

```<code>for i := 0; i < len(bytes); ++i {
        ...
}
</code>```

It is not correct and I got an error

syntax error: unexpected ++, expecting expression

It was because of ++i is not an expression I thought.

Then I found out that i++ (it works in for loop) is not an expression as well according to the documentation.

Also I met that in some cases (now I think in all cases) a statement can not be used instead of expression.

Now if we come back to the error we see that for loop requires an expression. I was confused with that. I checked one more part of the documentation it turns out for requires a statement.

For statements with for clause

A "for" statement with a ForClause is also controlled by its
  condition, but additionally it may specify an init and a post
  statement

I started with question (which I liked more than the final question because it was about language non-acquaintance as I thought)

Is it special case for loop syntax that statement are accepted as expression or are there other cases in golang?

During writing the question and checking the documentation I end up to a questions

Is there used incorrect terminology in description of the error that should be fixed not to confuse? Or is it normally in some cases to substitute such terms as statement and expression?

答:
The Go Spec says the post statement of a for clause accepts (among other things) a IndDec statement.

The IncDec statement is defined as: IncDecStmt = Expression ( "++" | "--" ) .

The parser finds an IndDec statement but an empty expression and thus spits out the error "expecting expression".

Edit: this probably fails because the fallback node to parse for a SimplStmt is an expression. The IncDecStmt failed, so it moves on to the default. The error accurately reflects the latest error that is bubbled up.

While the error message is correct, it is a little bit misleading. However, fixing it would involve passing more context about the current tree being parsed. eg: bad ForClause: bad PostStmt: bad SimpleStmt: expected expression.

There's still the problem that the expected expression is the last error encountered. Before that, it failed to parse the IncDecStmt but that error is swallowed because it falls back on an expression. The same applies at higher levels of the tree.

Even without that problem it would be rather heavy-handed and probably even more confusing than the current error messages. You may want to ask for input from the Go folks though.

Body:
I tried to use something like

for i := 0; i < len(bytes); ++i {
        ...
}

It is not correct and I got an error

syntax error: unexpected ++, expecting expression

It was because of ++i is not an expression I thought.

Then I found out that i++ (it works in for loop) is not an expression as well according to the documentation.

Also I met that in some cases (now I think in all cases) a statement can not be used instead of expression.

Now if we come back to the error we see that for loop requires an expression. I was confused with that. I checked one more part of the documentation it turns out for requires a statement.

For statements with for clause

A "for" statement with a ForClause is also controlled by its
  condition, but additionally it may specify an init and a post
  statement

I started with question (which I liked more than the final question because it was about language non-acquaintance as I thought)

Is it special case for loop syntax that statement are accepted as expression or are there other cases in golang?

During writing the question and checking the documentation I end up to a questions

Is there used incorrect terminology in description of the error that should be fixed not to confuse? Or is it normally in some cases to substitute such terms as statement and expression?


问:
Why validation layer doesn't say me I forgot to destroy a device or a surface?
I added VK_LAYER_LUNARG_standard_validation validation layers to my instance. Next I created a debug callback and other vulkan objects. For the test case the only object I'm clearing is the instance (because validation layers should report on instance destruction). And from all of the objects I have the layer reports only about VkDebugReportCallbackEXT:

validation layer: Debug Report callbacks not removed before
  DestroyInstance

Why it doesn't say me about VkSurfaceKHR and VkDevice (they are created for sure).

答:
Some of it was fixed in head, but not yet released as SDK.

Other thing is that vkDestroyInstance related messages can only be reported through temporary debug report callback provided through pNext of vkCreateInstance. The reason is all the child objects must be destroyed before vkDestroyInstance, including your debug callback, so it is not usable during vkDestroyInstance.

So, also chain your VkDebugReportCallbackCreateInfoEXT to the pNext chain of vkCreateInstance.


问:
Matlab multiple cores
I'm running an algorithm that's taking a lot of resources, and maxes out the CPU.

The problem is that it's only using one CPU.

How can i make MATLAB multithread the computations and use more than 1 CPU ?

答:
The settings are at:

File>Preferences>General>Multithreading in R2007a or newer

Affected functions are described at:

Which MATLAB functions benefit from multithreading

Title: Matlab multiple cores


问:
CSharp skip file through loop if it contains some string
Good morning,
I am looping through many text files in a folder to get the text written inside of them.
The name of the file is automatically written by another progam in a standard like date_filename.id, so I cannot be able to filter the files basing on the file name...

I noticed that they have a file identification on the first line like ORDERR or Something else so I was thinking if there's some method to skip the file if the first line contains some string.The loop looks like this at the moment:

```<code> DirectoryInfo FilesPath = new DirectoryInfo(path);
 var Files = FilesPath.GetFiles();
 foreach (var file in Files)
        {
            List<string> lines = new List<string>();
            using (StreamReader sr = file.OpenText())
            {

                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    if (s.Contains("ORDERR"))
                    {
                        "Do something"
                    }
                    else
                    {
                        break;
                    }
                }

            }
</code>```

But when the loop reach the second line, obviusly, it will skip the rest.
What can I do?

Thank you in advance for any kind of help

(I cannot be able to find something through stackoverflow)

答:
I'm not sure if i really got your requirement. But isn't it simple as(using LINQ for readability):

```<code>var relevantFiles = new DirectoryInfo(path).EnumerateFiles()
   .Where(f => File.ReadLines(f.FullName).ElementAtOrDefault(0)?.Contains("ORDERR")==false);
</code>```

Note that i use EnumerateFiles which is more efficient because it doesn't need to load all files into memory even if you want to skip them. The same applies to File.ReadLines(as opposed to ReadAllLines). Enumerable.ElementAtOrDefault returns null if the file is empty, that's why i used the null-conditional-operator ?. So the query will skip files which first line contains ORDERR.

Body:
Good morning,
I am looping through many text files in a folder to get the text written inside of them.
The name of the file is automatically written by another progam in a standard like date_filename.id, so I cannot be able to filter the files basing on the file name...

I noticed that they have a file identification on the first line like ORDERR or Something else so I was thinking if there's some method to skip the file if the first line contains some string.The loop looks like this at the moment:

 DirectoryInfo FilesPath = new DirectoryInfo(path);
 var Files = FilesPath.GetFiles();
 foreach (var file in Files)
        {
            List<string> lines = new List<string>();
            using (StreamReader sr = file.OpenText())
            {

                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    if (s.Contains("ORDERR"))
                    {
                        "Do something"
                    }
                    else
                    {
                        break;
                    }
                }

            }

But when the loop reach the second line, obviusly, it will skip the rest.
What can I do?

Thank you in advance for any kind of help

(I cannot be able to find something through stackoverflow)

Body:
I'm not sure if i really got your requirement. But isn't it simple as(using LINQ for readability):

var relevantFiles = new DirectoryInfo(path).EnumerateFiles()
   .Where(f => File.ReadLines(f.FullName).ElementAtOrDefault(0)?.Contains("ORDERR")==false);

Note that i use EnumerateFiles which is more efficient because it doesn't need to load all files into memory even if you want to skip them. The same applies to File.ReadLines(as opposed to ReadAllLines). Enumerable.ElementAtOrDefault returns null if the file is empty, that's why i used the null-conditional-operator ?. So the query will skip files which first line contains ORDERR.


问:
Get placeId on google maps when POI is clicked
I'm using Google Maps JS V3 API on my website. I'm able to use getDetails by placeId when user searches for a place. I would like to do the same when user clicks on a POI. However, I can't seem to find a way to get this placeId when user clicks on a POI instead of using the search box.

I have done research for days, and had no luck of finding anything close.

I came across this feature request, I wonder if there is really no way of getting the placeId by POI clicking: https://code.google.com/p/gmaps-api-issues/issues/detail?id=8113&q=poi&colspec=ID%20Type%20Status%20Introduced%20Fixed%20Summary%20Stars%20ApiType%20Internal

Any help is appreciated, thanks!

答:
As of 2017-12 this is now supported. Here's the example
https://developers.google.com/maps/documentation/javascript/examples/event-poi</p>


问:
WPF XAML Combo Box IsEnabled based on previous selection
In WPF XAML I'm wanting to make a combo box enabled only when the previous combo box has something selected in it. The 'top level' combo prompts the user to make a selection - so when they select something in the list then the next combo should become enabled.

Can I use a DataTemplate / Trigger to do this or can it be done with Element Binding?

Thanks folks.

答:
you can try this:

```<code><ComboBox Name="comboBox1">
    <ComboBoxItem>Some Content</ComboBoxItem>
    <ComboBoxItem>Some More Content</ComboBoxItem>
</ComboBox>

<ComboBox Name="comboBox2">
    <ComboBoxItem>Content Here</ComboBoxItem>
        <ComboBox.Style>
            <Style TargetType="{x:Type ComboBox}">
                <Setter Property="IsEnabled" Value="True"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=SelectedItem , ElementName=comboBox1}" Value="{x:Null}">
                        <Setter Property="IsEnabled" Value="False"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
      </ComboBox.Style>
 </ComboBox>
</code>```

Body:
you can try this:

<ComboBox Name="comboBox1">
    <ComboBoxItem>Some Content</ComboBoxItem>
    <ComboBoxItem>Some More Content</ComboBoxItem>
</ComboBox>

<ComboBox Name="comboBox2">
    <ComboBoxItem>Content Here</ComboBoxItem>
        <ComboBox.Style>
            <Style TargetType="{x:Type ComboBox}">
                <Setter Property="IsEnabled" Value="True"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=SelectedItem , ElementName=comboBox1}" Value="{x:Null}">
                        <Setter Property="IsEnabled" Value="False"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
      </ComboBox.Style>
 </ComboBox>


问:
sorting a multiFASTA file by DNA length
I'm trying to sort a multiFASTA file by length. I have the alphabetical sort figured out but I can't seem to get the numerical sort. The output should be a sorted multiFASTA file. This is an option to another program. Here is the code.</p>

```<code>sub sort {
my $length;
my $key;
my $id;
my %seqs;
my $seq;
my $action = shift;
my $match = $opts{$action};
$match =~ /[l|id]/ || die "not the right parameters\n";
my $in = Bio::SeqIO->new(-file=>"$filename", -format=>'fasta');
    while(my $seqobj = $in->next_seq()){
        my $id = $seqobj->display_id();
        my $length=$seqobj->length();
        #$seq =~s/.{1,60}\K/\n/sg;
        $seqs{$id} = $seqobj, unless $match eq 'l';
        $seqs{$length}=$seqobj, unless $match eq 'id';
    }
    if($match eq 'id'){
        foreach my $id (sort keys %seqs) {
             printf ">%-9s \n%-s\n", $id, $seqs{$id}->seq;
        }
    }
    elsif($match eq 'l'){
        foreach my $length ( sort keys %seqs){
             printf "%-10s\n%-s\n",$length, $seqs{$length}->seq;
        }
    }
}
</code>```

答: You can use pyfaidx or just take a look at jim hester repos. But as @pierre said above you should ask you question on biostars for example. The answer on biostars can be found here.</p>

Title: sorting a multiFASTA file by DNA length

Body:
I'm trying to sort a multiFASTA file by length. I have the alphabetical sort figured out but I can't seem to get the numerical sort. The output should be a sorted multiFASTA file. This is an option to another program. Here is the code.

sub sort {
my $length;
my $key;
my $id;
my %seqs;
my $seq;
my $action = shift;
my $match = $opts{$action};
$match =~ /[l|id]/ || die "not the right parameters\n";
my $in = Bio::SeqIO->new(-file=>"$filename", -format=>'fasta');
    while(my $seqobj = $in->next_seq()){
        my $id = $seqobj->display_id();
        my $length=$seqobj->length();
        #$seq =~s/.{1,60}\K/\n/sg;
        $seqs{$id} = $seqobj, unless $match eq 'l';
        $seqs{$length}=$seqobj, unless $match eq 'id';
    }
    if($match eq 'id'){
        foreach my $id (sort keys %seqs) {
             printf ">%-9s \n%-s\n", $id, $seqs{$id}->seq;
        }
    }
    elsif($match eq 'l'){
        foreach my $length ( sort keys %seqs){
             printf "%-10s\n%-s\n",$length, $seqs{$length}->seq;
        }
    }
}


问:
list images from aws s3 using exif and promises in node.js
I am using aws-sdk and exif library to get image details from images in an s3 bucket.

I  have used to get exif images details of my buckets of aws s3 images in node.js. For that used aws-sdk and exif library for get
all data of my aws bucket,but i have not get result of that code.

I have used following code :

```<code>app.get('/getContents', function(req,res){
    var params = {Bucket: req.query.Bucket};

    return new Promise(function(resolve, reject) {
        s3.listObjects(params, function(err, data) {
           if (err) {
                var error = {};
                error['isError'] = true,
                error['status'] = 400,
                error['message'] = "Data Not Found",
                error['data'] = err
                resolve(error);
            }
            else {
                var result1 = [];
                var result = data.Contents;
                result.forEach(function(final){
                    var urlParams = {Bucket: req.query.Bucket, Key: final.Key};
                    s3.getSignedUrl('getObject', urlParams, function(err, url){
                        request.get(url, function (err, result, body) {
                            var path = result.request.uri.href;
                            new ExifImage(body, function (error, exifData) {
                                if (error) {
                                    result1.push(error.message);
                                }
                                else {
                                    result1.push(exifData);
                                    res.send(result1);
                                }
                            });
                        });
                    });
                });
                //res.send(result1);
            }
        });
    });
});
</code>```

but response is null in the browser.
How can find that details for this code:

答:
I found that solution in github issues .... this is solution for that
https://github.com/nathan818fr/async-loop/issues/2</p>

Body:
I am using aws-sdk and exif library to get image details from images in an s3 bucket.

I  have used to get exif images details of my buckets of aws s3 images in node.js. For that used aws-sdk and exif library for get
all data of my aws bucket,but i have not get result of that code.

I have used following code :

app.get('/getContents', function(req,res){
    var params = {Bucket: req.query.Bucket};

    return new Promise(function(resolve, reject) {
        s3.listObjects(params, function(err, data) {
           if (err) {
                var error = {};
                error['isError'] = true,
                error['status'] = 400,
                error['message'] = "Data Not Found",
                error['data'] = err
                resolve(error);
            }
            else {
                var result1 = [];
                var result = data.Contents;
                result.forEach(function(final){
                    var urlParams = {Bucket: req.query.Bucket, Key: final.Key};
                    s3.getSignedUrl('getObject', urlParams, function(err, url){
                        request.get(url, function (err, result, body) {
                            var path = result.request.uri.href;
                            new ExifImage(body, function (error, exifData) {
                                if (error) {
                                    result1.push(error.message);
                                }
                                else {
                                    result1.push(exifData);
                                    res.send(result1);
                                }
                            });
                        });
                    });
                });
                //res.send(result1);
            }
        });
    });
});

but response is null in the browser.
How can find that details for this code:


问:
How to write this for-loop using std::for_each or std::transform?
This is more of a learning question. Is there a way I can write the following for-loop using std::for_each or std::transform? If not, is there anything in boost that can help on this? The loop simply flattens a vector of vectors into one long vector.</p>

```<code>vector<vector<int> > int_vectors;

// ... fill int_vectors

vector<int> ints;

for (vector<vector<int> >::const_iterator iter = int_vectors.begin(); iter != int_vectors.end(); ++iter) {
   ints.insert(ints.end(), iter->begin(), iter->end());
}
</code>```

答:
I kno macros aren't great practice but you can do some clever things with them:

```<code>#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>

using namespace std;
#define all(v) (v).begin(), (v).end()
#define foreach(it, v) for(auto it = (v).begin(); it != (v).end(); ++it)

void main() {
    vector<int> vi;
    vector<vector<int>> vvi;

    foreach(it, vvi) {
        copy(all(*it), back_inserter(vi));
    }
}
</code>```

You can also use std::copy and back_inserter to do what you're trying to achieve.

Body:
This is more of a learning question. Is there a way I can write the following for-loop using std::for_each or std::transform? If not, is there anything in boost that can help on this? The loop simply flattens a vector of vectors into one long vector.

vector<vector<int> > int_vectors;

// ... fill int_vectors

vector<int> ints;

for (vector<vector<int> >::const_iterator iter = int_vectors.begin(); iter != int_vectors.end(); ++iter) {
   ints.insert(ints.end(), iter->begin(), iter->end());
}

Body:
I kno macros aren't great practice but you can do some clever things with them:

#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>

using namespace std;
#define all(v) (v).begin(), (v).end()
#define foreach(it, v) for(auto it = (v).begin(); it != (v).end(); ++it)

void main() {
    vector<int> vi;
    vector<vector<int>> vvi;

    foreach(it, vvi) {
        copy(all(*it), back_inserter(vi));
    }
}

You can also use std::copy and back_inserter to do what you're trying to achieve.


答:
The more pythonic way for me is to use comprehension dicts :

```<code>dictionary = {'apples': np.array([1,2,3,4]),
'pears': np.array([1,2,10,11]),'oranges': np.array([1,10,10,3])}

In [144]: { k:v.max() for k,v in dictionary.items() }
Out[144]: {'apples': 4, 'oranges': 10, 'pears': 11}
</code>```

An other easy way is to use pandas :

```<code>In [145]: pd.DataFrame(dictionary).max()
Out[145]:
apples      4
oranges    10
pears      11
dtype: int32
</code>```

Title: How to find maximum value in a list of arrays

Body:
The more pythonic way for me is to use comprehension dicts :

dictionary = {'apples': np.array([1,2,3,4]),
'pears': np.array([1,2,10,11]),'oranges': np.array([1,10,10,3])}

In [144]: { k:v.max() for k,v in dictionary.items() }
Out[144]: {'apples': 4, 'oranges': 10, 'pears': 11}

An other easy way is to use pandas :

In [145]: pd.DataFrame(dictionary).max()
Out[145]:
apples      4
oranges    10
pears      11
dtype: int32