问:
Choosing a strategy for BI module
The company I work for produces a content management system (CMS) with different various add-ons for publishing, e-commerce, online printing, etc. We are now in process of adding "reporting module" and I need to investigate which strategy should be followed. The "reporting module" is otherwise known as Business Intelligence, or BI.

The module is supposed to be able to track item downloads, executed searches and produce various reports out of it. Actually, it is not that important what kind of data is being churned as in the long term we might want to be able to push whatever we think is needed and get a report out of it.

Roughly speaking, we have two options.

Option 1 is to write a solution based on Apache Solr (specifically, using https://issues.apache.org/jira/browse/SOLR-236). Pros of this approach:

free / open source / good quality

we use Solr/Lucene elsewhere so we know the domain quite well

total flexibility over what is being indexed as we could take incoming data (in XML format), push it through XSLT and feed it to Solr

total flexibility of how to show search results. Similar to step above, we could have custom XSLT search template and show results back in any format we think is necessary

our frontend developers are proficient in XSLT so fitting this mechanism for a different customer should be relatively easy

Solr offers realtime / full text / faceted search which are absolutely necessary for us. A quick prototype (based on Solr, 1M records) was able to deliver search results in 55ms. Our estimated maximum of records is about 1bn of rows (this isn't a lot for typical BI app) and if worse comes to worse, we can always look at SolrCloud, etc.

there are companies doing very similar things using Solr (Honeycomb Lexicon, for example)

Cons of this approach:

SOLR-236 might or might not be stable, moreover, it's not yet clear when/if it will be released as a part of official release

there would possibly be some stuff we'd have to write to get some BI-specific features working. This sounds a bit like reinventing the wheel

the biggest problem is that we don't know what we might need in the future (such as integration with some piece of BI software, export to Excel, etc.)

Option 2 is to do an integration with some free or commercial piece of BI software. So far I have looked at Wabit and will have a look at QlikView, possibly others.  Pros of this approach:

no need to reinvent the wheel, software is (hopefully) tried and tested

would save us time we could spend solving problems we specialize in

Cons:

as we are a Java shop and our solution is cross-platform, we'd have to eliminate a lot of options which are in the market

I am not sure how flexible BI software can be. It would take time to go through some BI offerings to see if they can do flexible indexing, real time / full text search, fully customizable results, etc.

I was told that open source BI offers are not mature enough whereas commercial BIs (SAP, others) cost fortunes, their licenses start from tens of thousands of pounds/dollars. While I am not against commercial choice per se, it will add up to the overall price which can easily become just too big

not sure how well BI is made to work with schema-less data

I am definitely not be the best candidate to find the most approprate integration option in the market (mainly because of absence of knowledge in BI area), however a decision needs to be done fast.

Has anybody been in a similar situation and could advise on which route to take, or even better - advise on possible pros/cons of the option #2? The biggest problem here is that I don't know what I don't know ;)

答:
If you're truly in a scenario where you're not sure what you don't know i think it's best to explore an open-source tool and evaluate its usefulness before diving into your own implementation. It could very well be that using the open-source solution will help you further crystallise your own understanding and required features.

I had worked previously w/ an open-source solution called Pentaho. I seriously felt that I understood a whole lot more by learning to use Pentaho's features for my end. Of course, as is the case of working w/ most of the open-source solutions, Pentaho seemed to be a bit intimidating at first, but I managed to get a good grip of it in a month's time. We also worked with Kettle ETL tool and Mondrian cubes - which I think most of the serious BI tools these days build on top of.

Earlier, all these components were independent, but off-late i believe Pentaho took ownership of all these projects.

But once you're confident w/ what you need and what you don't, I'd suggest building some basic reporting tool of your own on top of a mondrian implementation. Customising a sophisticated open-source tool can indeed be a big issue. Besides, there are licenses to be wary of. I believe Pentaho is GPL, though you might want to check on that.

Title: Choosing a strategy for BI module


来源: stackexchange

问:
Difficulty passing arguments into function?
I'd like to pass it's value as an argument into my function

```<code>function dostuff($input) {
global $input;

    if ($input == 5) {
        $output = "Success";
    } else {
        $output = "Failure";
    }
echo $output;
}
</code>```

Why does running

```<code>dostuff(5);
</code>```

Not echo the output variable ("Success") like it's supposed to?

答:
Expanding on Jouby’s explanation:

In PHP, unlike many other languages, variables are, by default, local variables. This simplifies some aspects of writing safe functions (with fewer accidental side-effects), but does require an extra step if you really want to use global variables.

In a function definition, parameter variables are really specialised local variables. The magic part of a parameter variable is that it is assigned automatically when yo call the function.

The global keyword in PHP associates the variable name to the global variable, effectively replacing the local variable. You only need to use global if you want to use global data, which is not generally a good idea.

In your example, that’s exactly what you have done. You have clobbered your local parameter with a non-existent global variable. Just remove that statement, and things should work.

ContentLicense: CC BY-SA 3.0

Body:
I'd like to pass it's value as an argument into my function

function dostuff($input) {
global $input;

    if ($input == 5) {
        $output = "Success";
    } else {
        $output = "Failure";
    }
echo $output;
}

Why does running

dostuff(5);

Not echo the output variable ("Success") like it's supposed to?


问:
Can't access object literal property using getter in ES6 module
I was looking for a way to self-reference an object to access it's property when I discover the ES5 getter feature (see. MDN).

I'm working with NPM module and can't access the canvas property.

config.js

```<code>import path from "path";
import layout from "./layouts";

const config = {
  canvas: { width: 80, height: 80 },
  layout: {
    get base() {
      console.log(this);
      console.log(this.canvas);
      return layout.base.bottom(this.canvas);
    },
    get annotation() {
      return layout.annotation.top(this.canvas);
    }
  }
};
export default config;
</code>```

layouts.js

```<code>export default {
  annotation: {
    top: options => ({
      x: options.width / 2,
    })
  },
  base: {
    bottom: options => ({
      x: options.width / 2,
    })
  }
};
</code>```

Error

```<code>{ base: [Getter], annotation: [Getter] }
undefined
TypeError: Cannot read property 'width' of undefined
    at Object.bottom (/data/projects/hanzi-pinyin-font/src/layouts.js:13:10)
    at Object.get base [as base] (/data/projects/hanzi-pinyin-font/src/config.js:17:26)
    at generateSvg (/data/projects/hanzi-pinyin-font/index.js:15:40)
    at /data/projects/hanzi-pinyin-font/index.js:39:5
    at /data/projects/hanzi-pinyin-font/node_modules/jsonfile/index.js:46:5
</code>```

Question

Why isn't this working?

答:
As explained by @Chris, the this wasn't referencing my top object config, but the parent object layout.

Moving up the getter solve this.

```<code>const config = {
  get layout() {
    return {
      base: layout.base.bottom(this.canvas),
      annotation: layout.annotation.top(this.canvas)
    };
  }
}
</code>```

Body:
I was looking for a way to self-reference an object to access it's property when I discover the ES5 getter feature (see. MDN).

I'm working with NPM module and can't access the canvas property.

config.js

import path from "path";
import layout from "./layouts";

const config = {
  canvas: { width: 80, height: 80 },
  layout: {
    get base() {
      console.log(this);
      console.log(this.canvas);
      return layout.base.bottom(this.canvas);
    },
    get annotation() {
      return layout.annotation.top(this.canvas);
    }
  }
};
export default config;

layouts.js

export default {
  annotation: {
    top: options => ({
      x: options.width / 2,
    })
  },
  base: {
    bottom: options => ({
      x: options.width / 2,
    })
  }
};

Error

{ base: [Getter], annotation: [Getter] }
undefined
TypeError: Cannot read property 'width' of undefined
    at Object.bottom (/data/projects/hanzi-pinyin-font/src/layouts.js:13:10)
    at Object.get base [as base] (/data/projects/hanzi-pinyin-font/src/config.js:17:26)
    at generateSvg (/data/projects/hanzi-pinyin-font/index.js:15:40)
    at /data/projects/hanzi-pinyin-font/index.js:39:5
    at /data/projects/hanzi-pinyin-font/node_modules/jsonfile/index.js:46:5

Question

Why isn't this working?

Body:
As explained by @Chris, the this wasn't referencing my top object config, but the parent object layout.

Moving up the getter solve this.

const config = {
  get layout() {
    return {
      base: layout.base.bottom(this.canvas),
      annotation: layout.annotation.top(this.canvas)
    };
  }
}


问:
Why do you have to cast objects when calling particular methods of a subclass?
So, for example,

```<code>Person p = New Person()

Person z = New Adult()
</code>```

Let's say the Adult Class had it's own method called drive(), why couldn't I do:

z.drive()

I know this won't work, but what is the logic behind this not working? When you say: Person z = New Adult(), aren't you specifying it is an Adult instance?

答:
The "logic" behind it not working is because that's how Java was designed to work. Java is a statically typed language which means that every variable has a declared type at compile time. Java is also strongly typed which means that the values that can be held and the operations that are supported are limited to the declared type. This enforcement is called type safety.

The advantage of a static type checking is that the compiler will prevent you from assigning incompatible types or calling methods that are not available. Errors can be caught at compile time vs runtime.

Try a search for "strong vs. weak typing" which will give many more details, arguments, and the pros/cons of the approaches.

Body:
So, for example,

Person p = New Person()

Person z = New Adult()

Let's say the Adult Class had it's own method called drive(), why couldn't I do:

z.drive()

I know this won't work, but what is the logic behind this not working? When you say: Person z = New Adult(), aren't you specifying it is an Adult instance?


问:
Average of Rnd Num in a loop java
I'm stuck trying to calculate the average when I generate 3 random integers between 1 and 20. I have to round the average to int and repeat it 10000 times. When I test my program repeating 2 times, I am getting the output of:

```<code>Number is :18
Number is :14
Number is :2
sum is: 34
Average is: 11

Number is :13
Number is :3
Number is :6
sum is: 56
Average is: 18
</code>```

However, the average should be the average of just the 3 numbers. Here, the second loop adds the sum of the first loop to the sum of the second making the average wrong (Sum:34+22=56). I want it to be 22 so the average for that would be 7. I notice the problem might be this line,  sum += n;  , but I don't know another way to add the 3 number for each loop to get the average.

```<code>package Histogram;

import java.util.Random;

public class RandomNumbers {
    public static void main(String[] args) {
        final int N = 2;
        Random rand = new Random();
        int n;
        int average;
        int sum = 0;

        for (int a = 0; a < N; a++) {
            for (int i = 0; i < 3; i++) {
                n = rand.nextInt(20) + 1;
                System.out.println("Number is :" + n);
                sum += n;
            }
            average = sum / 3;

        System.out.println("sum is: " + sum);
        System.out.println("Average is: " + average);

        }

    }
}
</code>```

答:
If you want the total sum I suggest adding a second iterationSum variable to add up the 3 numbers. Something like:

```<code>for (int a = 0; a < N; a++) {
    int iterationSum = 0;
    for (int i = 0; i < 3; i++) {
        ...
        iterationSum += n;
    }
    average = iterationSum / 3;
    ...
}
</code>```

If you don't care about the total sum just reset you sum to 0 in each iteration:

```<code>for (int a = 0; a < N; a++) {
    sum = 0;
    ...
}
</code>```

Title: Average of Rnd Num in a loop java

Body:
I'm stuck trying to calculate the average when I generate 3 random integers between 1 and 20. I have to round the average to int and repeat it 10000 times. When I test my program repeating 2 times, I am getting the output of:

Number is :18
Number is :14
Number is :2
sum is: 34
Average is: 11

Number is :13
Number is :3
Number is :6
sum is: 56
Average is: 18

However, the average should be the average of just the 3 numbers. Here, the second loop adds the sum of the first loop to the sum of the second making the average wrong (Sum:34+22=56). I want it to be 22 so the average for that would be 7. I notice the problem might be this line,  sum += n;  , but I don't know another way to add the 3 number for each loop to get the average.

package Histogram;

import java.util.Random;

public class RandomNumbers {
    public static void main(String[] args) {
        final int N = 2;
        Random rand = new Random();
        int n;
        int average;
        int sum = 0;

        for (int a = 0; a < N; a++) {
            for (int i = 0; i < 3; i++) {
                n = rand.nextInt(20) + 1;
                System.out.println("Number is :" + n);
                sum += n;
            }
            average = sum / 3;

        System.out.println("sum is: " + sum);
        System.out.println("Average is: " + average);

        }

    }
}

Body:
If you want the total sum I suggest adding a second iterationSum variable to add up the 3 numbers. Something like:

for (int a = 0; a < N; a++) {
    int iterationSum = 0;
    for (int i = 0; i < 3; i++) {
        ...
        iterationSum += n;
    }
    average = iterationSum / 3;
    ...
}

If you don't care about the total sum just reset you sum to 0 in each iteration:

for (int a = 0; a < N; a++) {
    sum = 0;
    ...
}


问:
How do I move my local Git repository to a remote Git repository
I have various Git projects that are on my local machine. I have a server that I would like to use as my remote Git  Repository. How do I move my local Git Repositories (Projects) to my server while keeping the history intact?

Thanks!

EDIT:
Thanks for all the great answers. The response I choose makes sense to my limited GIT knowledge.

EDIT #2:
I noticed my original answer selection did not copy my tags. git push --mirror <path> does copy tags.

答:
If you have a stand-alone local working tree repository (a folder with a ".git" folder inside) that you want to add a remote to:

Create a new empty repository in the remote.

In the local repository, set the new remote as the origin:

cd localrepo

git remote add origin REMOTEURL   #(verify with git remote -v)

Push all local branches to the remote, and set each local branch to track the corresponding remote branch:

git push --all --set-upstream origin  #(verify with git branch -vv)

Push all local tags to the remote:

git push --tags origin

At this point the local repository will act just like it had been cloned from the remote.

If you have a bare local repository (a folder with a name ending in .git) that you just want to copy to a remote:

Create a new empty repository in the remote.

In the local repository, push all of its branches to the remote

cd localrepo.git

git push --all REMOTEURL

Push all local tags to the remote:

git push --tags REMOTEURL


答:
the average should be the average of just the 3 numbers. Here, the
  second loop adds the sum of the first loop to the sum of the second
  making the average wrong (Sum:34+22=56). I want it to be 22 so the
  average for that would be 7

One approach is to reset the value of sum after you've printed the sum and average to the console.

Example:

```<code>int n;
int average;
int sum = 0;

for (int a = 0; a < N; a++) {
    for (int i = 0; i < 3; i++) {
        n = rand.nextInt(20) + 1;
        System.out.println("Number is :" + n);
        sum += n;
    }
    average = sum / 3;

    System.out.println("sum is: " + sum);
    System.out.println("Average is: " + average);
    sum = 0;
}
</code>```

or to make life easier you can make the variable sum local within the loop so that at each iteration the value of sum will reset to default value:

Example:

```<code>int n;
int average = 0;
for (int a = 0; a < N; a++) {
     int sum = 0;
     for (int i = 0; i < 3; i++) {
        n = rand.nextInt(20) + 1;
        System.out.println("Number is :" + n);
        sum += n;
    }
    average = sum / 3;

    System.out.println("sum is: " + sum);
    System.out.println("Average is: " + average);
}
</code>```

Title: Average of Rnd Num in a loop java

Body:
the average should be the average of just the 3 numbers. Here, the
  second loop adds the sum of the first loop to the sum of the second
  making the average wrong (Sum:34+22=56). I want it to be 22 so the
  average for that would be 7

One approach is to reset the value of sum after you've printed the sum and average to the console.

Example:

int n;
int average;
int sum = 0;

for (int a = 0; a < N; a++) {
    for (int i = 0; i < 3; i++) {
        n = rand.nextInt(20) + 1;
        System.out.println("Number is :" + n);
        sum += n;
    }
    average = sum / 3;

    System.out.println("sum is: " + sum);
    System.out.println("Average is: " + average);
    sum = 0;
}

or to make life easier you can make the variable sum local within the loop so that at each iteration the value of sum will reset to default value:

Example:

int n;
int average = 0;
for (int a = 0; a < N; a++) {
     int sum = 0;
     for (int i = 0; i < 3; i++) {
        n = rand.nextInt(20) + 1;
        System.out.println("Number is :" + n);
        sum += n;
    }
    average = sum / 3;

    System.out.println("sum is: " + sum);
    System.out.println("Average is: " + average);
}


答:
Your sum += n; inside the second for loop keeps on incrementing the value of sum (even the older sum values from loop). Thus you need to reset the value of sum to 0 every time at the begineeing the first loop.

```<code>for (int a = 0; a < N; a++) {
   sum = 0;
   //rest of the code
</code>```

Title: Average of Rnd Num in a loop java

Body:
Your sum += n; inside the second for loop keeps on incrementing the value of sum (even the older sum values from loop). Thus you need to reset the value of sum to 0 every time at the begineeing the first loop.

for (int a = 0; a < N; a++) {
   sum = 0;
   //rest of the code


问:
javascript onclick fade div in (short code)
i'm been lookin all over the place and cannot find exactly what im after anywhere.

the html structure is basically.

```<code><ul>
   <li><a href="">link</a></li>
   <div id="us">hidden info</div>
</ul>
</code>```

the css structure is.

```<code>#us {display:none}
</code>```

I'd like it so when "link" is clicked the div "us" is changed from dipslay:none; to display:block, in a graceful fade in as little lines of code as possible, and then again when the link is clicked its toggled back to display:hidden.

I'm aware that there are lots of things that can do this, but im really lookin for that simplicity in code.

thanks for your time x

答:
You can just use .toggle() with a duration (works in all jQuery versions), like this:

```<code>$("ul li a").click(function() { $("#us").toggle("fast"); });
</code>```

Or, if you're on jQuery 1.4.4+, use .fadeToggle() like this:

```<code>$("ul li a").click(function() { $("#us").fadeToggle(); });
</code>```

Note though, a
 isn't a valid child of
, so it may render unexpectedly in several browsers...it'd be better to use proper markup.

ContentLicense: CC BY-SA 2.5

Body:
i'm been lookin all over the place and cannot find exactly what im after anywhere.

the html structure is basically.

link

hidden info

the css structure is.

#us {display:none}

I'd like it so when "link" is clicked the div "us" is changed from dipslay:none; to display:block, in a graceful fade in as little lines of code as possible, and then again when the link is clicked its toggled back to display:hidden.

I'm aware that there are lots of things that can do this, but im really lookin for that simplicity in code.

thanks for your time x

Body:
You can just use .toggle() with a duration (works in all jQuery versions), like this:

$("ul li a").click(function() { $("#us").toggle("fast"); });

Or, if you're on jQuery 1.4.4+, use .fadeToggle() like this:

$("ul li a").click(function() { $("#us").fadeToggle(); });

Note though, a <div> isn't a valid child of  <ul>, so it may render unexpectedly in several browsers...it'd be better to use proper markup.


问:
Get following sibling on android using Appium
```<code>driver.findElementByXPath("//android.widget.TextView[@text='a1492']/../following-sibling::android.view.ViewGroup").click();
</code>```

This does not work. Am I missing anything?

答: @text is looking for an attribute text. If you're actually after the text content, it's [text()='a1492'].

Body:
driver.findElementByXPath("//android.widget.TextView[@text='a1492']/../following-sibling::android.view.ViewGroup").click();

This does not work. Am I missing anything?


问:
Using JavaScript Variables in HTML code
I'm pretty new to JavaScript.

I'm trying to make a YouTube 2.0 html thing, (interesting learning experience). I want it to be so that you click on the "load video" link and it asks you the link to the actual youtube video. Then, when you paste it in, it displays the video on the page.

My code is

Youtube 2.0

Load video

```

If you have any ideas on how I can insert the JavaScript variable into my iframe src tag, please tell me. Thanks!

答:
You can't change iframe src but we can replace your iframe with new one.

Note, I have set your iframe ID as myLink, replacing the src attribute.

```<code><h1 style="background-color: red; color: white; font-family: helvetica; padding: 20px 20px 20px 20px;">Youtube 2.0</h1>
<a href="#" onclick="openVideo()">Load video</a>

<iframe width="1120" height="630" id="myLink" frameborder="0" allowfullscreen></iframe>
<script>
openVideo = function() {
  var videoLink = prompt("Video link on YouTube.com");
  var iframe=document.getElementById('myLink');

  var new_iframe = document.createElement("iframe");
        new_iframe.src=videoLink;

  let attr;
  let attributes = Array.prototype.slice.call(iframe.attributes);
  while(attr = attributes.pop()) {
    if (attr.nodeName!='src')
        new_iframe.setAttribute(attr.nodeName, attr.nodeValue);
  }

  iframe.parentNode.replaceChild(new_iframe, iframe);
}
</script>
</code>```

Make sure to embed the embed link, in this format:

```<code>https://www.youtube.com/embed/MEVYajbHmb4
</code>```

Working JS fiddle :

https://jsfiddle.net/aa0kzqsz/2/

Title: Using JavaScript Variables in HTML code

Body:
I'm pretty new to JavaScript.

I'm trying to make a YouTube 2.0 html thing, (interesting learning experience). I want it to be so that you click on the "load video" link and it asks you the link to the actual youtube video. Then, when you paste it in, it displays the video on the page.

My code is

Youtube 2.0

Load video

If you have any ideas on how I can insert the JavaScript variable into my iframe src tag, please tell me. Thanks!

Body:
You can't change iframe src but we can replace your iframe with new one.

Note, I have set your iframe ID as myLink, replacing the src attribute.

<h1 style="background-color: red; color: white; font-family: helvetica; padding: 20px 20px 20px 20px;">Youtube 2.0</h1>
<a href="#" onclick="openVideo()">Load video</a>

<iframe width="1120" height="630" id="myLink" frameborder="0" allowfullscreen></iframe>
<script>
openVideo = function() {
  var videoLink = prompt("Video link on YouTube.com");
  var iframe=document.getElementById('myLink');

  var new_iframe = document.createElement("iframe");
        new_iframe.src=videoLink;

  let attr;
  let attributes = Array.prototype.slice.call(iframe.attributes);
  while(attr = attributes.pop()) {
    if (attr.nodeName!='src')
        new_iframe.setAttribute(attr.nodeName, attr.nodeValue);
  }

  iframe.parentNode.replaceChild(new_iframe, iframe);
}
</script>

Make sure to embed the embed link, in this format:

https://www.youtube.com/embed/MEVYajbHmb4

Working JS fiddle :

https://jsfiddle.net/aa0kzqsz/2/


问:
NedB on heroku dont keep db file
i used nedb in my nodejs app , first of my code is :

```<code>var Datastore = require('nedb');
var db = new Datastore({ filename: 'users.db', autoload: true });
db.persistence.setAutocompactionInterval(5);
</code>```

everything is ok with local host , and database will save every thick in my db file . (Database saved after server restarting)
but in heroku server , database is empty !!!
i think database saved as in-memory ! (not in my db file !!) Why ?!
i want keep my database in my db file in Heroku server !

答:
Heroku dynos have an ephemeral file system, so you shouldn't be trying to save your database there. From the documentation:

During the dyno’s lifetime its running processes can use the
  filesystem as a temporary scratchpad, but no files that are written
  are visible to processes in any other dyno and any files written will
  be discarded the moment the dyno is stopped or restarted.

You'll have a better time adding a MongoDB addon and writing to that instead.

Title: NedB on heroku dont keep db file

Body:
i used nedb in my nodejs app , first of my code is :

var Datastore = require('nedb');
var db = new Datastore({ filename: 'users.db', autoload: true });
db.persistence.setAutocompactionInterval(5);

everything is ok with local host , and database will save every thick in my db file . (Database saved after server restarting)
but in heroku server , database is empty !!!
i think database saved as in-memory ! (not in my db file !!) Why ?!
i want keep my database in my db file in Heroku server !


问:
calculating the average of 10 for loop results in batch
so i've created a for loop that calculates (x mod 6) + 2 for every number from 1-10 (inclusive), with "x" representing each individual number as the loop increments. however, i'd like to calculate the average for each of the 10 results, but i actually have no idea as to how i'd format the loop to do so. i'd rather not do something like echo "1 + 2 + 3 + etc" as that seems extremely lazy and ill-constructed. i feel like this is something relatively easy, but i've tried searching it up and attempting another loop, but to no avail. any and all help is much appreciated!

here's the loop:

```<code>:ForLoop
@echo off &setlocal enabledelayedexpansion

echo This loop calculates the results for (x mod 6) + 2 with x being each number from1-10 (inclusive).
echo.
for /L %%x in (1, 1, 10) do (
    SET /a VAR=%%x %% 6+2
    set /a CAL=!VAR! %% 8
    echo %%x MOD 6 + 2 = !CAL!
)
</code>```

答:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
:ForLoop

echo This loop calculates the results for (x mod 6) + 2 with x being each number from1-10 (inclusive).
echo.
SET /a iterations=10
SET /a sum=0
for /L %%x in (1, 1, %iterations%) do (
    SET /a VAR=%%x %% 6+2
    SET /a sum+=var
    SET /a avg=sum / %%x
    echo %%x MOD 6 + 2 = !var! average so far=!avg! (from !sum! / %%x^)
)

GOTO :EOF
```

There's no need to do the %% 8 jazz - since var can only be (0..5)+2, this gives a range of 2..7.

set /a uses the run-time value of the variables, so !var! is not required - %var% would use the initial value of var.

Note that the average is truncated as batch does integer mathematics.

Body:
so i've created a for loop that calculates (x mod 6) + 2 for every number from 1-10 (inclusive), with "x" representing each individual number as the loop increments. however, i'd like to calculate the average for each of the 10 results, but i actually have no idea as to how i'd format the loop to do so. i'd rather not do something like echo "1 + 2 + 3 + etc" as that seems extremely lazy and ill-constructed. i feel like this is something relatively easy, but i've tried searching it up and attempting another loop, but to no avail. any and all help is much appreciated!

here's the loop:

:ForLoop
@echo off &setlocal enabledelayedexpansion

echo This loop calculates the results for (x mod 6) + 2 with x being each number from1-10 (inclusive).
echo.
for /L %%x in (1, 1, 10) do (
    SET /a VAR=%%x %% 6+2
    set /a CAL=!VAR! %% 8
    echo %%x MOD 6 + 2 = !CAL!
)

Body:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
:ForLoop

echo This loop calculates the results for (x mod 6) + 2 with x being each number from1-10 (inclusive).
echo.
SET /a iterations=10
SET /a sum=0
for /L %%x in (1, 1, %iterations%) do (
    SET /a VAR=%%x %% 6+2
    SET /a sum+=var
    SET /a avg=sum / %%x
    echo %%x MOD 6 + 2 = !var! average so far=!avg! (from !sum! / %%x^)
)

GOTO :EOF

There's no need to do the %% 8 jazz - since var can only be (0..5)+2, this gives a range of 2..7.

set /a uses the run-time value of the variables, so !var! is not required - %var% would use the initial value of var.

Note that the average is truncated as batch does integer mathematics.


问:
How do I serialize file type input in jquery
Previously using Prototype I could serialize the input type file, it gave me the file name of the file being uploaded but when I serialized the form in jquery I just got the input type text and others not the file how do I do it?</p>

答: At the Prototype source (referenced above) serializeElements distinguishes between "element.type != 'file'" and others. Element type "file" is not serialized.</p>


答:
```<code>public static void main(String[] args) {
    final int N = 2;
    Random rand = new Random();
    int n;
    int average;
    int sum = 0;

    for (int a = 0; a < N; a++) {
        sum=0;// this makes the trick
        for (int i = 0; i < 3; i++) {
            n = rand.nextInt(20) + 1;
            System.out.println("Number is :" + n);
            sum += n;
        }
        average = sum / 3;

    System.out.println("sum is: " + sum);
    System.out.println("Average is: " + average);

    }

}
</code>```

Title: Average of Rnd Num in a loop java


问:
pandas rolling max min mean
being new to pandas I am lost in the zillions of smooth random data generation examples.

What I have been trying to achieve is to create graphs using bokeh with rolling time window. I want x-axis to be (resampled or whatever) timestamp and 3 lines displaying max, min and mean values for let's say rolling 15 second time window for the duration field.

The joy stops before starting... I have tried to apply quite many examples without making progress or learning much.

The code below

```<code>d2 = pd.read_csv(input_file, delimiter=",")
d2["ts_send"] = pd.to_datetime(d2["ts_send"], \
format="%Y-%m-%d %H:%M:%S.%f", exact=True, utc=True)

print (d2.head())
print (d2.rolling("15s", min_periods=1).mean().head())
print (d2.rolling("15s", min_periods=1).std().head())
print (d2.rolling("15s", min_periods=1).min().head())
print (d2.rolling("15s", min_periods=1).max().head())
</code>```

produces an exception:

ValueError: window must be an integer

If I could get the rolling stuff work, I'd probably could manage the bokeh side.

Any pointers supporting to make this happen are highly appreciated!

I have this data in csv:

```
ts_send,endpoint,duration,
2017-01-19 09:03:28.600,/api/sig,1.0
2017-01-19 09:03:29.760,/api/sig,0.5
2017-01-19 09:04:51.210,/api/sig,0.508
2017-01-19 09:04:52.410,/api/sig,0.574
2017-01-19 09:09:32.854,/api/sig,1.0
2017-01-19 09:09:36.776,/api/sig,0.637
2017-01-19 09:14:14.207,/api/sig,0.672
2017-01-19 09:14:16.906,/api/sig,0.533
2017-01-19 11:49:34.939,/api/sig,1.0
2017-01-19 11:49:38.709,/api/sig,0.529
2017-01-19 12:19:01.668,/api/sig,1.0
2017-01-19 12:19:05.559,/api/item,0.169
2017-01-19 12:19:05.559,/api/item,0.102
2017-01-19 12:19:05.559,/api/item,0.44
2017-01-19 12:19:05.585,/api/item,0.173
2017-01-19 12:19:06.633,/api/sig,0.564
2017-01-19 12:27:05.712,/api/sig,0.574
2017-01-19 12:27:08.370,/api/sig,0.497
2017-01-19 12:27:43.319,/api/sig,0.561
2017-01-19 12:27:45.873,/api/sig,0.508
2017-01-19 12:46:15.454,/api/sig,1.0
2017-01-19 12:46:20.409,/api/item,0.173
2017-01-19 12:46:20.427,/api/item,0.163
2017-01-19 12:46:20.457,/api/item,0.169
2017-01-19 12:46:20.474,/api/item,0.162
2017-01-19 12:46:20.618,/api/item,0.209
2017-01-19 12:46:20.642,/api/item,0.172
2017-01-19 12:46:20.695,/api/item,0.26
2017-01-19 12:46:20.698,/api/item,0.193
2017-01-19 12:46:20.788,/api/item,0.193
2017-01-19 12:46:20.822,/api/item,0.232
2017-01-19 12:46:20.873,/api/item,0.164
2017-01-19 12:46:20.875,/api/item,0.142
2017-01-19 12:46:20.905,/api/item,0.356
2017-01-19 12:46:20.998,/api/item,0.199
```

The timestamp ts_send is millisecond precission. There are times when no events are recorded and there are times when there multiple events on a single millisecond.

答:
This will work if your time series is the index. Add this before you run your code:</p>

```<code>d2.set_index('ts_send', inplace=True)
</code>```

Title: pandas rolling max min mean

Body:
being new to pandas I am lost in the zillions of smooth random data generation examples.

What I have been trying to achieve is to create graphs using bokeh with rolling time window. I want x-axis to be (resampled or whatever) timestamp and 3 lines displaying max, min and mean values for let's say rolling 15 second time window for the duration field.

The joy stops before starting... I have tried to apply quite many examples without making progress or learning much.

The code below

d2 = pd.read_csv(input_file, delimiter=",")
d2["ts_send"] = pd.to_datetime(d2["ts_send"], \
format="%Y-%m-%d %H:%M:%S.%f", exact=True, utc=True)

print (d2.head())
print (d2.rolling("15s", min_periods=1).mean().head())
print (d2.rolling("15s", min_periods=1).std().head())
print (d2.rolling("15s", min_periods=1).min().head())
print (d2.rolling("15s", min_periods=1).max().head())

produces an exception:

ValueError: window must be an integer

If I could get the rolling stuff work, I'd probably could manage the bokeh side.

Any pointers supporting to make this happen are highly appreciated!

I have this data in csv:

ts_send,endpoint,duration,
2017-01-19 09:03:28.600,/api/sig,1.0
2017-01-19 09:03:29.760,/api/sig,0.5
2017-01-19 09:04:51.210,/api/sig,0.508
2017-01-19 09:04:52.410,/api/sig,0.574
2017-01-19 09:09:32.854,/api/sig,1.0
2017-01-19 09:09:36.776,/api/sig,0.637
2017-01-19 09:14:14.207,/api/sig,0.672
2017-01-19 09:14:16.906,/api/sig,0.533
2017-01-19 11:49:34.939,/api/sig,1.0
2017-01-19 11:49:38.709,/api/sig,0.529
2017-01-19 12:19:01.668,/api/sig,1.0
2017-01-19 12:19:05.559,/api/item,0.169
2017-01-19 12:19:05.559,/api/item,0.102
2017-01-19 12:19:05.559,/api/item,0.44
2017-01-19 12:19:05.585,/api/item,0.173
2017-01-19 12:19:06.633,/api/sig,0.564
2017-01-19 12:27:05.712,/api/sig,0.574
2017-01-19 12:27:08.370,/api/sig,0.497
2017-01-19 12:27:43.319,/api/sig,0.561
2017-01-19 12:27:45.873,/api/sig,0.508
2017-01-19 12:46:15.454,/api/sig,1.0
2017-01-19 12:46:20.409,/api/item,0.173
2017-01-19 12:46:20.427,/api/item,0.163
2017-01-19 12:46:20.457,/api/item,0.169
2017-01-19 12:46:20.474,/api/item,0.162
2017-01-19 12:46:20.618,/api/item,0.209
2017-01-19 12:46:20.642,/api/item,0.172
2017-01-19 12:46:20.695,/api/item,0.26
2017-01-19 12:46:20.698,/api/item,0.193
2017-01-19 12:46:20.788,/api/item,0.193
2017-01-19 12:46:20.822,/api/item,0.232
2017-01-19 12:46:20.873,/api/item,0.164
2017-01-19 12:46:20.875,/api/item,0.142
2017-01-19 12:46:20.905,/api/item,0.356
2017-01-19 12:46:20.998,/api/item,0.199

The timestamp ts_send is millisecond precission. There are times when no events are recorded and there are times when there multiple events on a single millisecond.

Body:
This will work if your time series is the index. Add this before you run your code:

d2.set_index('ts_send', inplace=True)


问:
What is the benefit of a concurrent garbage collection?

Does a concurrent garbage collection also suspend all threads in the application other than the one it is running on?

Let us consider a desktop application with a user interface. If a concurrent collection is also going to suspend all threads anyway, then there's no point in making it concurrent, right? What is benefit of having a concurrent garbage collection?

Also, the MSDN states two contradictions:

a. That it is good to have a concurrent collection enabled for a single-threaded GUI application, for example a desktop application; and

b. That a concurrent garbage collection causes a performance hit.

So, my next question is:

Why does the concurrent collection cause a degradation in performance? And finally,

What do I do if I want to register for notifications from the garbage collector for my desktop application? According to the MSDN page linked above, it is recommended to use a concurrent collection (the default) for UI applications. But the MSDN also says that notifications are not supported for concurrent collections; they are only supported for blocking collections.

答:
Concurrent garbage collection does not suspend other threads, but thread scheduling code suspends threads, if there are not enough CPU cores.

Having a concurrent garbage collection benefit is for UI applications, not blocked UI, a responsive UI.

If you don't have enough CPU cores, and if you have lots of threads or applications on the same machine, process scheduling and thread scheduling will decrease performance.

Garbage collector notifications are for servers not for desktops.


问:
`filterKeys` and `mapValues` get executed multiple times
When I use filterKeys or mapValues on a Map to create a new Map, the functions I've passed into these methods seems to get executed every single time I use the new Map. Shouldn't they only get executed once to generate the new Map?

In this example see how the printlns happen multiple times.

```<code>// printlns happen when creating the map
scala> val myMap = Map(1 -> 1, 2 -> 2, 3 -> 3).filterKeys { i =>
    println(s"filterKeys$i")
    i < 5
  }.mapValues { i =>
    println(s"mapValues$i")
    i + 1
  }
filterKeys1
mapValues1
filterKeys2
mapValues2
filterKeys3
mapValues3
myMap: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 2 -> 3, 3 -> 4)

// printlns happen again!
scala> myMap.toString()
filterKeys1
mapValues1
filterKeys2
mapValues2
filterKeys3
mapValues3
res29: String = Map(1 -> 2, 2 -> 3, 3 -> 4)

// and again!
scala> myMap + (4 -> 5)
filterKeys1
mapValues1
filterKeys2
mapValues2
filterKeys3
mapValues3
res30: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 2 -> 3, 3 -> 4, 4 -> 5)
</code>```

I would expect the behaviour to be the same as .map(). The function passed to map, only gets run one for each item, and is not run again when the resulting map is used in the future:

```<code>// printlns happen when creating the map
scala> val myMap = Map(1 -> 1, 2 -> 2, 3 -> 3).map { i =>
  println(s"map$i")
  i
}
map(1,1)
map(2,2)
map(3,3)
myMap: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3)

// printlns not run again :)
scala> myMap.toString
res32: String = Map(1 -> 1, 2 -> 2, 3 -> 3)
</code>```

答:
The scaladocs for mapValues and filterKeys both mention that they return a resulting map that wraps the original map without copying any elements. You can see in the source code that mapValues returns an instance of MappedValues which re-runs your function for every repeated foreach, iterator and get call.

Because this behaviour is inconsistent with .map(), there is ticket SI-4776 open to either rename the methods or change their return type to make this more obvious, however the ticket has been open for a long time, so don't expect this behaviour to change soon.

Update: Since Scala 2.13 these methods have been deprecated with plans to fix in a future version:

(Since version 2.13.0) Use .view.mapValues(f). A future version will include a strict version of this method (for now, .view.mapValues(f).toMap).

As well as the view.mapValues(f).toMap suggested, you can also get around this by using transform instead of mapValues and filter instead of filterKeys:

```<code>val myMap = Map(1 -> 1, 2 -> 2, 3 -> 3).filter { case (i, _) =>
    println(s"filterKeys$i")
    i < 5
  }.transform { (_, i) =>
    println(s"mapValues$i")
    i + 1
  }

// no printlns when the Map is used again!
myMap.toString
</code>```

Body:
When I use filterKeys or mapValues on a Map to create a new Map, the functions I've passed into these methods seems to get executed every single time I use the new Map. Shouldn't they only get executed once to generate the new Map?

In this example see how the printlns happen multiple times.

// printlns happen when creating the map
scala> val myMap = Map(1 -> 1, 2 -> 2, 3 -> 3).filterKeys { i =>
    println(s"filterKeys$i")
    i < 5
  }.mapValues { i =>
    println(s"mapValues$i")
    i + 1
  }
filterKeys1
mapValues1
filterKeys2
mapValues2
filterKeys3
mapValues3
myMap: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 2 -> 3, 3 -> 4)

// printlns happen again!
scala> myMap.toString()
filterKeys1
mapValues1
filterKeys2
mapValues2
filterKeys3
mapValues3
res29: String = Map(1 -> 2, 2 -> 3, 3 -> 4)

// and again!
scala> myMap + (4 -> 5)
filterKeys1
mapValues1
filterKeys2
mapValues2
filterKeys3
mapValues3
res30: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 2 -> 3, 3 -> 4, 4 -> 5)

I would expect the behaviour to be the same as .map(). The function passed to map, only gets run one for each item, and is not run again when the resulting map is used in the future:

// printlns happen when creating the map
scala> val myMap = Map(1 -> 1, 2 -> 2, 3 -> 3).map { i =>
  println(s"map$i")
  i
}
map(1,1)
map(2,2)
map(3,3)
myMap: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3)

// printlns not run again :)
scala> myMap.toString
res32: String = Map(1 -> 1, 2 -> 2, 3 -> 3)

Body:
The scaladocs for mapValues and filterKeys both mention that they return a resulting map that wraps the original map without copying any elements. You can see in the source code that mapValues returns an instance of MappedValues which re-runs your function for every repeated foreach, iterator and get call.

Because this behaviour is inconsistent with .map(), there is ticket SI-4776 open to either rename the methods or change their return type to make this more obvious, however the ticket has been open for a long time, so don't expect this behaviour to change soon.

Update: Since Scala 2.13 these methods have been deprecated with plans to fix in a future version:

(Since version 2.13.0) Use .view.mapValues(f). A future version will include a strict version of this method (for now, .view.mapValues(f).toMap).

As well as the view.mapValues(f).toMap suggested, you can also get around this by using transform instead of mapValues and filter instead of filterKeys:

val myMap = Map(1 -> 1, 2 -> 2, 3 -> 3).filter { case (i, _) =>
    println(s"filterKeys$i")
    i < 5
  }.transform { (_, i) =>
    println(s"mapValues$i")
    i + 1
  }

// no printlns when the Map is used again!
myMap.toString

ContentLicense: CC BY-SA 4.0


问:
During a fork, Where exactly does the child's execution start?
fork system call create the duplicate process from parent. If the child create same duplicate process from the parent's, does it start executing the same kernel code that the parent was executing? Or does it start executing in user space?

答:
That is going to depend upon the implementation. In theory, the child process could start either in kernel mode at the end of the fork exception handler or within the wrapper function after the exception handler returns to user mode.

That said, it is generally easier to implement fork such that the child process starts executing within the tail end of the fork exception handler (kernel mode).


答:
Something like this:</p>

```<code>$("#idfortheanchor").bind("click", function() {
    if ($("#us").is(":visible")) {
        $("#us").hide();
    } else {
        $("#us").show();
    }
});
</code>```

Title: javascript onclick fade div in (short code)

Body:
Something like this:

$("#idfortheanchor").bind("click", function() {
    if ($("#us").is(":visible")) {
        $("#us").hide();
    } else {
        $("#us").show();
    }
});


问:
Biopython: Cant use .count() for biopython
My goal here is to receive the amount of time 'g' appears in a DNA sequence.

I imported a DNA sequence via Biopython using list comprehension

```<code>seq = [record for record in SeqIO.parse('sequences/hiv.gbk.rtf', 'fasta')]
</code>```

I then tried using the .count() method on the newly created list comp variable

```<code>print(seq.count('g'))
</code>```

I get an error that reads

NotImplementedError: SeqRecord comparison is deliberately not
  implemented. Explicitly compare the attributes of interest.

Anyone know what the dealio is? Biopython's manual says all standard python methods should work.

答:
You are trying to apply count to a list. You would to need to apply it to the sequence of each element, e.g.

```<code>print(seq[0].seq.count('g'))
</code>```

or if you want to get the sum of all sequences

```<code>print(sum([s.seq.count('g') for s in seq]))
</code>```

Here is a minimal working example

```<code>from Bio import SeqIO

txt = """>gnl|TC-DB|O60669|2.A.1.13.5 Monocarboxylate transporter 2 - Homo sapiens (Human).
MPPMPSAPPVHPPPDGGWGWIVVGAAFISIGFSYAFPKAVTVFFKEIQQIFHTTYSEIAW
>gnl|TC-DB|O60706|3.A.1.208.23 ATP-binding cassette sub-family C member 9 OS=Homo sapiens GN=ABCC9 PE=1 SV=2
MSLSFCGNNISSYNINDGVLQNSCFVDALNLVPHVFLLFITFPILFIGWGSQSSKVQIHH
>gnl|TC-DB|O60721|3.A.1.208.23 Sodium/potassium/calcium exchanger 1 OS=Homo sapiens GN=SLC24A1 PE=1 SV=1
MGKLIRMGPQERWLLRTKRLHWSRLLFLLGMLIIGSTYQHLRRPRGLSSLWAAVSSHQPI
>gnl|TC-DB|O60779|2.A.1.13.5 Thiamine transporter 1 (THTR-1) (ThTr1) (Thiamine carrier 1) (TC1) - Homo sapiens (Human).
MDVPGPVSRRAAAAAATVLLRTARVRRECWFLPTALLCAYGFFASLRPSEPFLTPYLLGP"""

filename = 'sequences.fa'
with open(filename, 'w') as f:
    f.write(txt)

seqs = [record for record in SeqIO.parse(filename, 'fasta')]

print(sum([s.seq.count('P') for s in seqs]))
>>> 21

print(seqs[0].seq.count('P'))
>>> 9
</code>```

Body:
My goal here is to receive the amount of time 'g' appears in a DNA sequence.

I imported a DNA sequence via Biopython using list comprehension

seq = [record for record in SeqIO.parse('sequences/hiv.gbk.rtf', 'fasta')]

I then tried using the .count() method on the newly created list comp variable

print(seq.count('g'))

I get an error that reads

NotImplementedError: SeqRecord comparison is deliberately not
  implemented. Explicitly compare the attributes of interest.

Anyone know what the dealio is? Biopython's manual says all standard python methods should work.

Body:
You are trying to apply count to a list. You would to need to apply it to the sequence of each element, e.g.

print(seq[0].seq.count('g'))

or if you want to get the sum of all sequences

print(sum([s.seq.count('g') for s in seq]))

Here is a minimal working example

from Bio import SeqIO

txt = """>gnl|TC-DB|O60669|2.A.1.13.5 Monocarboxylate transporter 2 - Homo sapiens (Human).
MPPMPSAPPVHPPPDGGWGWIVVGAAFISIGFSYAFPKAVTVFFKEIQQIFHTTYSEIAW
>gnl|TC-DB|O60706|3.A.1.208.23 ATP-binding cassette sub-family C member 9 OS=Homo sapiens GN=ABCC9 PE=1 SV=2
MSLSFCGNNISSYNINDGVLQNSCFVDALNLVPHVFLLFITFPILFIGWGSQSSKVQIHH
>gnl|TC-DB|O60721|3.A.1.208.23 Sodium/potassium/calcium exchanger 1 OS=Homo sapiens GN=SLC24A1 PE=1 SV=1
MGKLIRMGPQERWLLRTKRLHWSRLLFLLGMLIIGSTYQHLRRPRGLSSLWAAVSSHQPI
>gnl|TC-DB|O60779|2.A.1.13.5 Thiamine transporter 1 (THTR-1) (ThTr1) (Thiamine carrier 1) (TC1) - Homo sapiens (Human).
MDVPGPVSRRAAAAAATVLLRTARVRRECWFLPTALLCAYGFFASLRPSEPFLTPYLLGP"""

filename = 'sequences.fa'
with open(filename, 'w') as f:
    f.write(txt)

seqs = [record for record in SeqIO.parse(filename, 'fasta')]

print(sum([s.seq.count('P') for s in seqs]))
>>> 21

print(seqs[0].seq.count('P'))
>>> 9


问:
Color a label in CSS
Is there a way of changing the Color of this?

```<code><label for="Vorname">Vorname: </label>
<input type="text" id="Vorname" >
</code>```

I'm using this as my CSS

```<code>#vorname {
position: relative;
font-family: 'Lato', sans-serif;
font-size: 150%;
color: white;
</code>```

}
For some Reason its not working D:
Hope someone can help me. Thanks a lot

答:
The # indicates that the CSS cooresponds to an ID so you should add an id to the label like this:

```<code><label id="VornameLable" for="Vorname">Vorname: </label>
<input type="text" id="VornameTextInput" >
</code>```

and the css:

```<code>#VornameLable {
position: relative;
font-family: 'Lato', sans-serif;
font-size: 150%;
color: white;
}
</code>```

JSFiddle:

https://jsfiddle.net/jr4v102u/1/

Title: Color a label in CSS

Body:
Is there a way of changing the Color of this?

Vorname:
<input type="text" id="Vorname" >

I'm using this as my CSS

#vorname {
position: relative;
font-family: 'Lato', sans-serif;
font-size: 150%;
color: white;

}
For some Reason its not working D:
Hope someone can help me. Thanks a lot

Body:
The # indicates that the CSS cooresponds to an ID so you should add an id to the label like this:

<label id="VornameLable" for="Vorname">Vorname: </label>
<input type="text" id="VornameTextInput" >

and the css:

#VornameLable {
position: relative;
font-family: 'Lato', sans-serif;
font-size: 150%;
color: white;
}

JSFiddle:

https://jsfiddle.net/jr4v102u/1/


问:
avoiding nested for loops python
I have a function which takes in expressions and replaces the variables with all the permutations of the values that I am using as inputs. This is my code that I have tested and works, however after looking through SO, people have said that nested for loops are a bad idea however I am unsure as to how to make this more efficient. Could somebody help? Thanks. </p>

```<code>def replaceVar(expression):

    eval_list = list()

    a = [1, 8, 12, 13]
    b = [1, 2, 3, 4]
    c = [5, 9, 2, 7]

    for i in expression:
        first_eval = [i.replace("a", str(j)) for j in a]
        tmp = list()
        for k in first_eval:
            snd_eval = [k.replace("b", str(l)) for l in b]
            tmp2 = list()
            for m in snd_eval:
                trd_eval = [m.replace("c", str(n)) for n in c]
                tmp2.append(trd_eval)
            tmp.append(tmp2)
        eval_list.append(tmp)
    print(eval_list)
    return eval_list

print(replaceVar(['b-16+(c-(a+11))', 'a-(c-5)+a-b-10']))
</code>```

答:
Foreword

Nested loops are not a bad thing per se. They are only bad, if there are used for problems, for which better algorithm have been found (better and bad in terms of efficiency regarding the input size). Sorting of a list of integers for example is such a problem.

Analyzing the Problem

The size

In your case above you have three lists, all of size 4. This makes 4 * 4 * 4 = 64 possible combinations of them, if a comes always before b and b before c. So you need at least 64 iterations!

Your approach

In your approach we have 4 iterations for each possible value of a, 4 iterations for each possible value of b and the same for c. So we have 4 * 4 * 4 = 64 iterations in total. So in fact your solution is quite good!
As there is no faster way of listening all combinations, your way is also the best one.

The style

Regarding the style one can say that you can improve your code by better variable names and combining some of the for loops. E.g. like that:

```<code>def replaceVar(expressions):
    """
    Takes a list of expressions and returns a list of expressions with
    evaluated variables.
    """
    evaluatedExpressions = list()

    valuesOfA = [1, 8, 12, 13]
    valuesOfB = [1, 2, 3, 4]
    valuesOfC = [5, 9, 2, 7]

    for expression in expressions:
        for valueOfA in valuesOfA:
            for valueOfB in valuesOfB:
                for valueOfC in valuesOfC:
                    newExpression = expression.\
                                    replace('a', str(valueOfA)).\
                                    replace('b', str(valueOfB)).\
                                    replace('c', str(valueOfC))
                    evaluatedExpressions.append(newExpression)

    print(evaluatedExpressions)
    return evaluatedExpressions

print(replaceVar(['b-16+(c-(a+11))', 'a-(c-5)+a-b-10']))
</code>```

Notice however that the amount of iterations remain the same!

Itertools

As Kevin noticed, you could also use itertools to generate the cartesian product. Internally it will do the same as what you did with the combined for loops:

```<code>import itertools

def replaceVar(expressions):
    """
    Takes a list of expressions and returns a list of expressions with
    evaluated variables.
    """
    evaluatedExpressions = list()

    valuesOfA = [1, 8, 12, 13]
    valuesOfB = [1, 2, 3, 4]
    valuesOfC = [5, 9, 2, 7]

    for expression in expressions:
        for values in itertools.product(valuesOfA, valuesOfB, valuesOfC):
            valueOfA = values[0]
            valueOfB = values[1]
            valueOfC = values[2]
            newExpression = expression.\
                            replace('a', str(valueOfA)).\
                            replace('b', str(valueOfB)).\
                            replace('c', str(valueOfC))
            evaluatedExpressions.append(newExpression)

    print(evaluatedExpressions)
    return evaluatedExpressions

print(replaceVar(['b-16+(c-(a+11))', 'a-(c-5)+a-b-10']))
</code>```

Title: avoiding nested for loops python

Body:
I have a function which takes in expressions and replaces the variables with all the permutations of the values that I am using as inputs. This is my code that I have tested and works, however after looking through SO, people have said that nested for loops are a bad idea however I am unsure as to how to make this more efficient. Could somebody help? Thanks.

def replaceVar(expression):

    eval_list = list()

    a = [1, 8, 12, 13]
    b = [1, 2, 3, 4]
    c = [5, 9, 2, 7]

    for i in expression:
        first_eval = [i.replace("a", str(j)) for j in a]
        tmp = list()
        for k in first_eval:
            snd_eval = [k.replace("b", str(l)) for l in b]
            tmp2 = list()
            for m in snd_eval:
                trd_eval = [m.replace("c", str(n)) for n in c]
                tmp2.append(trd_eval)
            tmp.append(tmp2)
        eval_list.append(tmp)
    print(eval_list)
    return eval_list

print(replaceVar(['b-16+(c-(a+11))', 'a-(c-5)+a-b-10']))

Body:
Foreword

Nested loops are not a bad thing per se. They are only bad, if there are used for problems, for which better algorithm have been found (better and bad in terms of efficiency regarding the input size). Sorting of a list of integers for example is such a problem.

Analyzing the Problem

The size

In your case above you have three lists, all of size 4. This makes 4 * 4 * 4 = 64 possible combinations of them, if a comes always before b and b before c. So you need at least 64 iterations!

Your approach

In your approach we have 4 iterations for each possible value of a, 4 iterations for each possible value of b and the same for c. So we have 4 * 4 * 4 = 64 iterations in total. So in fact your solution is quite good!
As there is no faster way of listening all combinations, your way is also the best one.

The style

Regarding the style one can say that you can improve your code by better variable names and combining some of the for loops. E.g. like that:

def replaceVar(expressions):
    """
    Takes a list of expressions and returns a list of expressions with
    evaluated variables.
    """
    evaluatedExpressions = list()

    valuesOfA = [1, 8, 12, 13]
    valuesOfB = [1, 2, 3, 4]
    valuesOfC = [5, 9, 2, 7]

    for expression in expressions:
        for valueOfA in valuesOfA:
            for valueOfB in valuesOfB:
                for valueOfC in valuesOfC:
                    newExpression = expression.\
                                    replace('a', str(valueOfA)).\
                                    replace('b', str(valueOfB)).\
                                    replace('c', str(valueOfC))
                    evaluatedExpressions.append(newExpression)

    print(evaluatedExpressions)
    return evaluatedExpressions

print(replaceVar(['b-16+(c-(a+11))', 'a-(c-5)+a-b-10']))

Notice however that the amount of iterations remain the same!

Itertools

As Kevin noticed, you could also use itertools to generate the cartesian product. Internally it will do the same as what you did with the combined for loops:

import itertools

def replaceVar(expressions):
    """
    Takes a list of expressions and returns a list of expressions with
    evaluated variables.
    """
    evaluatedExpressions = list()

    valuesOfA = [1, 8, 12, 13]
    valuesOfB = [1, 2, 3, 4]
    valuesOfC = [5, 9, 2, 7]

    for expression in expressions:
        for values in itertools.product(valuesOfA, valuesOfB, valuesOfC):
            valueOfA = values[0]
            valueOfB = values[1]
            valueOfC = values[2]
            newExpression = expression.\
                            replace('a', str(valueOfA)).\
                            replace('b', str(valueOfB)).\
                            replace('c', str(valueOfC))
            evaluatedExpressions.append(newExpression)

    print(evaluatedExpressions)
    return evaluatedExpressions

print(replaceVar(['b-16+(c-(a+11))', 'a-(c-5)+a-b-10']))


答: Your id is uppercase, while your css is lowercase. If you change #vorname to #Vorname in your css, it should work, however you'll have white text on a white background</p>

Title: Color a label in CSS


问:
Skobbler & Annotation animations
We are looking to see what options there are in providing additional animations to annotations on Skobbler maps.

What we are specifically looking for is an animation which cycles - e.g. a bouncing pin which you can achieve with Google maps.

Is it possible to achieve this using the 'out of the box' classes, or do I have to create some custom view?

答:
The easiest way to do this would be to use the SKAnimationSettings.</p>

```<code>SKAnnotation ska = new SKAnnotation(1);
map.addAnnotation(ska, SKAnimationSettings.ANIMATION_PIN_DROP);
</code>```

Title: Skobbler & Annotation animations

Body:
The easiest way to do this would be to use the SKAnimationSettings.

SKAnnotation ska = new SKAnnotation(1);
map.addAnnotation(ska, SKAnimationSettings.ANIMATION_PIN_DROP);


问:
Uploading file to spreadsheet requires special permissions
I'm writing a script for Google Sheets which opens a form for uploading a file, and calls server-side function to handle the uploaded file. The problem I have is that the server-side function does not get called and failure handler is invoked with error message saying that I have no permissions to do the operation.
If I call the server side function with null argument instead of passing in the form then the function successfully gets called.

Here is the script I have:

```<code>function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var csvMenuEntries = [{name: "Process bank statement file", functionName: "openUploadPaymentsDialog"}];
  ss.addMenu("AG_Menu", csvMenuEntries);
}

function openUploadPaymentsDialog(e) {
  var html = HtmlService.createHtmlOutputFromFile('UploadPaymentsDialog');
  SpreadsheetApp.getUi().showModalDialog(html, 'Upload .NDA file');
  Logger.log('dialog opened');
}

function handleFileUpload(theForm) {
  Logger.log('file uploaded');
}
</code>```

And HTML form:

```<code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <form>
      <input type="file" name="theFile"/><br/><br/>
      <input type="button" value="Submit" onclick="onSubmit(this.parentNode);"/>
    </form>
    <div id="output"/>
    <script>
      function onSubmit(theForm) {
        google.script.run
                .withSuccessHandler(onSuccess)
                .withFailureHandler(onFailure)
                .handleFileUpload(theForm);
//if I call handleFileUpload with null as argument then call succeeds
      }

      function onFailure(error){
        var div = document.getElementById('output');
        div.innerHTML = "ERROR: " + error.message;
      }

      function onSuccess(f){
        google.script.host.close();
      }
    </script>

  </body>
</html>
</code>```

The script is bound to the spreadsheet and I'm not the owner of the spreadsheet, but I have permissions to edit. I'm running the script from my user (not owner).

Is it so that only owner can upload files? Why is that?

答: I found out that it is probably some problem with browser I'm using. It is Google Chromium under Debian Linux. I have just tried it with Firefox and it works OK.</p>

Body:
I'm writing a script for Google Sheets which opens a form for uploading a file, and calls server-side function to handle the uploaded file. The problem I have is that the server-side function does not get called and failure handler is invoked with error message saying that I have no permissions to do the operation.
If I call the server side function with null argument instead of passing in the form then the function successfully gets called.

Here is the script I have:

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var csvMenuEntries = [{name: "Process bank statement file", functionName: "openUploadPaymentsDialog"}];
  ss.addMenu("AG_Menu", csvMenuEntries);
}

function openUploadPaymentsDialog(e) {
  var html = HtmlService.createHtmlOutputFromFile('UploadPaymentsDialog');
  SpreadsheetApp.getUi().showModalDialog(html, 'Upload .NDA file');
  Logger.log('dialog opened');
}

function handleFileUpload(theForm) {
  Logger.log('file uploaded');
}

And HTML form:

<!DOCTYPE html>

    <base target="_top">

    <form>
      <input type="file" name="theFile"/>

      <input type="button" value="Submit" onclick="onSubmit(this.parentNode);"/>
    </form>

The script is bound to the spreadsheet and I'm not the owner of the spreadsheet, but I have permissions to edit. I'm running the script from my user (not owner).

Is it so that only owner can upload files? Why is that?


问:
Displaying images
Hi I am developing a application where I need to display number of images with some conditions. The images should display one by one on the screen when next button is clicked.Here the size of all images is 360x480.When the image is display then all other fields like next and previous buttons should be added to the screen.How to paint those images.Can anybody please help me in this regard.</p>

答:
You can display images with the BitmapField.  Use the setBitmap() method to change the image.

Edit: Ok, so you would want to do something like this, put the names of all your bitmaps in an array, have the button's listeners increment or decrement the array index and display that bitmap.  So your next button might look like this:

```<code>ButtonField nextButton = new ButtonField("Next");
nextButton.setChangeListener(new FieldChangeListener(){
    public void fieldChanged(Field field, int context)
    {
        if(arrayIndex + 1 >= bitmapArray.length)
        {
            return;
        }
        arrayIndex++;
        Bitmap image = Bitmap.getBitmapResource(bitmapArray[arrayIndex])
        myBitmapField.setBitmap(image);
    }

});
</code>```

This assumes that your images are preloaded with your app and are stored in the 'res' directory, if you're downloading them from online or they're stored on the filesystem the way you load the bitmap will be somewhat different.  I haven't compiled this code so it may have some bugs but this is roughly what you want to do.

Title: Displaying images

Body:
You can display images with the BitmapField.  Use the setBitmap() method to change the image.

Edit: Ok, so you would want to do something like this, put the names of all your bitmaps in an array, have the button's listeners increment or decrement the array index and display that bitmap.  So your next button might look like this:

ButtonField nextButton = new ButtonField("Next");
nextButton.setChangeListener(new FieldChangeListener(){
    public void fieldChanged(Field field, int context)
    {
        if(arrayIndex + 1 >= bitmapArray.length)
        {
            return;
        }
        arrayIndex++;
        Bitmap image = Bitmap.getBitmapResource(bitmapArray[arrayIndex])
        myBitmapField.setBitmap(image);
    }

});

This assumes that your images are preloaded with your app and are stored in the 'res' directory, if you're downloading them from online or they're stored on the filesystem the way you load the bitmap will be somewhat different.  I haven't compiled this code so it may have some bugs but this is roughly what you want to do.


问:
JS: why do i need brackets to call a method on number?
```<code>function func2method(f){
    return function(y) {
        return f(this, y);
    };
}

Number.prototype.add = func2method(function(x, y){return x+y});
</code>```

Why do I have to use brackets to call this method on a number?

For example, 3.add(4) won't work while (3).add(4) works perfectly fine.

答:
Because 3.0 is not the same as (3)['0']

Literals are interpreted differently. The point . represents a decimal point on a numeric literal, but the point . on an object represents a property accessor (translated to square bracket notation above)

Body:
function func2method(f){
    return function(y) {
        return f(this, y);
    };
}

Number.prototype.add = func2method(function(x, y){return x+y});

Why do I have to use brackets to call this method on a number?

For example, 3.add(4) won't work while (3).add(4) works perfectly fine.


问:
C# selenium web driver how do while loop on element
This is my code in C# I press the delete button and open a pop up where I select the amount of deletions that I want to delete and press again on delete it will delete.
Perhaps it is more correct to ask how I do while this delete element

```<code>PropertiesCollections.driver.FindElement (By.LinkText ("Delete")). Click ();
</code>```

As long as it appear true that it will perform the deletion steps and if it does not continue the test

```<code>PropertiesCollections.driver.FindElement(By.LinkText("Delete")).Click();
new SelectElement(PropertiesCollections.driver.FindElement(By.Id("remove_shares"))).SelectByText("1");
PropertiesCollections.driver.FindElement(By.XPath("(//button[@type='button'])[2]")).Click();
</code>```

I want to make a loop if the delete button appear, it will do all the steps of the deletion, and if it does not continue for the other test

im try with this code

```<code>   var links =   PropertiesCollections.driver.FindElement(By.LinkText("Delete")).Click();
             while (links = true)
              {
               PropertiesCollections.driver.FindElement(By.LinkText("Delete")).Click();
               PropertiesCollections.driver.FindElement(By.Id("remove_shares"));
               PropertiesCollections.driver.FindElement(By.XPath("(//button[@type='button'])[2]")).Click();
             }
</code>```

but i get error
Error   1   Cannot assign void to an implicitly-typed local variable

答:
The first line of code is assigning the return of .Click() to the variable links but .Click() returns void (nothing).

The logic for what you want to do is:

Check to see if the Delete link exists

If it does, click on it

Do stuff

Repeat 1-3

```<code>IReadOnlyCollection<IWebElement> links = PropertiesCollections.driver.FindElements(By.LinkText("Delete")); // gets a collection of elements with Delete as a link
while (links.Any()) // if the collection is not empty, this evaluates to `true`
{
    links.ElementAt(0).Click(); // click the first (and probably only?) element
    // do stuff
    PropertiesCollections.driver.FindElement(By.Id("remove_shares"));
    PropertiesCollections.driver.FindElement(By.XPath("(//button[@type='button'])[2]")).Click();
    // get the Delete links again so we can return to the start of the `while` and see if it's still not empty
    links = PropertiesCollections.driver.FindElements(By.LinkText("Delete"));
}
</code>```

Body:
This is my code in C# I press the delete button and open a pop up where I select the amount of deletions that I want to delete and press again on delete it will delete.
Perhaps it is more correct to ask how I do while this delete element

PropertiesCollections.driver.FindElement (By.LinkText ("Delete")). Click ();

As long as it appear true that it will perform the deletion steps and if it does not continue the test

PropertiesCollections.driver.FindElement(By.LinkText("Delete")).Click();
new SelectElement(PropertiesCollections.driver.FindElement(By.Id("remove_shares"))).SelectByText("1");
PropertiesCollections.driver.FindElement(By.XPath("(//button[@type='button'])[2]")).Click();

I want to make a loop if the delete button appear, it will do all the steps of the deletion, and if it does not continue for the other test

im try with this code

   var links =   PropertiesCollections.driver.FindElement(By.LinkText("Delete")).Click();
             while (links = true)
              {
               PropertiesCollections.driver.FindElement(By.LinkText("Delete")).Click();
               PropertiesCollections.driver.FindElement(By.Id("remove_shares"));
               PropertiesCollections.driver.FindElement(By.XPath("(//button[@type='button'])[2]")).Click();
             }

but i get error
Error   1   Cannot assign void to an implicitly-typed local variable

Body:
The first line of code is assigning the return of .Click() to the variable links but .Click() returns void (nothing).

The logic for what you want to do is:

Check to see if the Delete link exists

If it does, click on it

Do stuff

Repeat 1-3

IReadOnlyCollection<IWebElement> links = PropertiesCollections.driver.FindElements(By.LinkText("Delete")); // gets a collection of elements with Delete as a link
while (links.Any()) // if the collection is not empty, this evaluates to `true`
{
    links.ElementAt(0).Click(); // click the first (and probably only?) element
    // do stuff
    PropertiesCollections.driver.FindElement(By.Id("remove_shares"));
    PropertiesCollections.driver.FindElement(By.XPath("(//button[@type='button'])[2]")).Click();
    // get the Delete links again so we can return to the start of the `while` and see if it's still not empty
    links = PropertiesCollections.driver.FindElements(By.LinkText("Delete"));
}


问:
Where to find documentation on Android Studio external libraries?
I apologize if this question is too broad. I am looking to implement the external library Floating Action Button for my Android Studio project, but I am unable to find the documentation for the methods in Java that I should be using to implement its functionality, such as expanding the FAB into several other FABs, as shown in the Screenshot portion of the link.

I have already added the dependency to my gradle and com.github.clans.fab.FloatingActionButton header to my XML layout file.

The reason I am asking is because I've come across several libraries on Github that have minimal descriptions and no documentation. How does someone learn the methods and classes for external libraries like this without them? There must be something I am misunderstanding here.

答:
How does someone learn the methods and classes for external libraries like this without them?

Review the source code of the sample app.

Or, review the source code of the library.

Or, search for com.github.clans.fab on your favorite search engine to see if anyone has a blog post or other sort of article on the library.


问:
javascript onclick fade div in (short code)
i'm been lookin all over the place and cannot find exactly what im after anywhere.

the html structure is basically.

```<code><ul>
   <li><a href="">link</a></li>
   <div id="us">hidden info</div>
</ul>
</code>```

the css structure is.

```<code>#us {display:none}
</code>```

I'd like it so when "link" is clicked the div "us" is changed from dipslay:none; to display:block, in a graceful fade in as little lines of code as possible, and then again when the link is clicked its toggled back to display:hidden.

I'm aware that there are lots of things that can do this, but im really lookin for that simplicity in code.

thanks for your time x

答:
As there is no fade-toggle in the jQuery core, I'd use:</p>

```<code>$('a').toggle(
    function() { $('#us').fadeIn(); },
    function() { $('#us').fadeOut(); }
);
</code>```

Body:
i'm been lookin all over the place and cannot find exactly what im after anywhere.

the html structure is basically.

link

hidden info

the css structure is.

#us {display:none}

I'd like it so when "link" is clicked the div "us" is changed from dipslay:none; to display:block, in a graceful fade in as little lines of code as possible, and then again when the link is clicked its toggled back to display:hidden.

I'm aware that there are lots of things that can do this, but im really lookin for that simplicity in code.

thanks for your time x

Body:
As there is no fade-toggle in the jQuery core, I'd use:

$('a').toggle(
    function() { $('#us').fadeIn(); },
    function() { $('#us').fadeOut(); }
);


问:
Using a SAT solver from Scala class
I need to invoke a generic SAT solver from an application written in Scala. I was looking into SAT4J since it can be easily imported as a jar file however am finding it difficult to actually use it. Is there a way I can fire the SAT4j jar file to compute my SAT problem from within my Scala code?

If SAT4J is not the right approach, are there any SAT libraries I can use directly instead of launching an external SAT solver?

答:
Sat4j is pure Java so you can directly use it within scala as long as the jar is available on Scala classpath.

Sat4j has a scala binding:
https://gitlab.ow2.org/sat4j/sat4j/tree/master/org.sat4j.scala

You can build it from source, or grab it from continuous integration:
https://gitlab.ow2.org/sat4j/sat4j/pipelines/95/builds

Title: Using a SAT solver from Scala class


问:
Average of Rnd Num in a loop java
I'm stuck trying to calculate the average when I generate 3 random integers between 1 and 20. I have to round the average to int and repeat it 10000 times. When I test my program repeating 2 times, I am getting the output of:

```<code>Number is :18
Number is :14
Number is :2
sum is: 34
Average is: 11

Number is :13
Number is :3
Number is :6
sum is: 56
Average is: 18
</code>```

However, the average should be the average of just the 3 numbers. Here, the second loop adds the sum of the first loop to the sum of the second making the average wrong (Sum:34+22=56). I want it to be 22 so the average for that would be 7. I notice the problem might be this line,  sum += n;  , but I don't know another way to add the 3 number for each loop to get the average.

```<code>package Histogram;

import java.util.Random;

public class RandomNumbers {
    public static void main(String[] args) {
        final int N = 2;
        Random rand = new Random();
        int n;
        int average;
        int sum = 0;

        for (int a = 0; a < N; a++) {
            for (int i = 0; i < 3; i++) {
                n = rand.nextInt(20) + 1;
                System.out.println("Number is :" + n);
                sum += n;
            }
            average = sum / 3;

        System.out.println("sum is: " + sum);
        System.out.println("Average is: " + average);

        }

    }
}
</code>```

答:
You must clean the sum variable after the first loop:

```<code>//..
int sum;

for (int a = 0; a < N; a++) {
    sum = 0; // -------> Here it is necessary to be clean for the next iteration
    for (int i = 0; i < 3; i++) {
        n = rand.nextInt(20) + 1;
        System.out.println("Number is :" + n);
        sum += n;
    }
//...
}
</code>```

Title: Average of Rnd Num in a loop java

Body:
I'm stuck trying to calculate the average when I generate 3 random integers between 1 and 20. I have to round the average to int and repeat it 10000 times. When I test my program repeating 2 times, I am getting the output of:

Number is :18
Number is :14
Number is :2
sum is: 34
Average is: 11

Number is :13
Number is :3
Number is :6
sum is: 56
Average is: 18

However, the average should be the average of just the 3 numbers. Here, the second loop adds the sum of the first loop to the sum of the second making the average wrong (Sum:34+22=56). I want it to be 22 so the average for that would be 7. I notice the problem might be this line,  sum += n;  , but I don't know another way to add the 3 number for each loop to get the average.

package Histogram;

import java.util.Random;

public class RandomNumbers {
    public static void main(String[] args) {
        final int N = 2;
        Random rand = new Random();
        int n;
        int average;
        int sum = 0;

        for (int a = 0; a < N; a++) {
            for (int i = 0; i < 3; i++) {
                n = rand.nextInt(20) + 1;
                System.out.println("Number is :" + n);
                sum += n;
            }
            average = sum / 3;

        System.out.println("sum is: " + sum);
        System.out.println("Average is: " + average);

        }

    }
}

Body:
You must clean the sum variable after the first loop:

//..
int sum;

for (int a = 0; a < N; a++) {
    sum = 0; // -------> Here it is necessary to be clean for the next iteration
    for (int i = 0; i < 3; i++) {
        n = rand.nextInt(20) + 1;
        System.out.println("Number is :" + n);
        sum += n;
    }
//...
}


问:
Replace words keeping original case
I am making a program that replaces words in an MS Word document. I want to keep the original case of the words.

Let's say, there's an expression: "Broken Glass". I want to modify it to "Cristal Roto".

I have two textboxes, Input and Output.

Input is where the term to replace goes, and output is the word with which the input term will be replaced.

For this example, I would put "Broken Glass" in the (Input) textbox, and "Cristal Roto" in the (Output) textbox.

The result in the Word document will be "Cristal roto". The second word's first letter gets lowercased.

Dim rng As Word.Range
rng = objWordS.ActiveDocument.Content
    With rng.Find
        .ClearFormatting()
        .Execute(FindText:=Input.Text, _
          ReplaceWith:=Output.Text, _
          MatchWholeWord:=True, _
          Replace:=Word.WdReplace.wdReplaceAll)
    End With
```
<p>I only care about the original case of the first letter of each word.</p>
<p><strong>EDIT</strong><br />
The reason "Broken Glass" ended up "Cristal roto" was that I missed adding this:</p>
```.Replacement.ClearFormatting()
```

Which I added just between .ClearFormatting and .Execute.

Now the text in the Word File is replaced with the case I use in the Output textbox.

Still, I would like to know if there is a way to detect the case of the original word in the Word File, to automatically adapt the Output Textbox's text without using Proper Case. So:

To Replace: "Broken Glass" - Replace text: "cristal roto" - Desired result: "Cristal Roto".

答:
Try parsing Output.Text to ProperCase while executing the search. Something like this should work:

ReplaceWith:=StrConv(Output.Text, vbProperCase)

Shorter and cleaner. But you still have to use ProperCase,  don't know if this fits your needs

Title: Replace words keeping original case

Body:
I am making a program that replaces words in an MS Word document. I want to keep the original case of the words.

Let's say, there's an expression: "Broken Glass". I want to modify it to "Cristal Roto".

I have two textboxes, Input and Output.

Input is where the term to replace goes, and output is the word with which the input term will be replaced.

For this example, I would put "Broken Glass" in the (Input) textbox, and "Cristal Roto" in the (Output) textbox.

The result in the Word document will be "Cristal roto". The second word's first letter gets lowercased.

Dim rng As Word.Range
rng = objWordS.ActiveDocument.Content
    With rng.Find
        .ClearFormatting()
        .Execute(FindText:=Input.Text, _
          ReplaceWith:=Output.Text, _
          MatchWholeWord:=True, _
          Replace:=Word.WdReplace.wdReplaceAll)
    End With

I only care about the original case of the first letter of each word.

EDIT

The reason "Broken Glass" ended up "Cristal roto" was that I missed adding this:

.Replacement.ClearFormatting()

Which I added just between .ClearFormatting and .Execute.

Now the text in the Word File is replaced with the case I use in the Output textbox.

Still, I would like to know if there is a way to detect the case of the original word in the Word File, to automatically adapt the Output Textbox's text without using Proper Case. So:

To Replace: "Broken Glass" - Replace text: "cristal roto" - Desired result: "Cristal Roto".


问:
design practice: is it good to hide/unhide controls at runtime
I have always had a bias against controls appearing/disappearing at runtime. I think that I read this somewhere but google is not forthcoming and I've not been successful in finding anything to support my bias in any of the hard-copies that I have. We're having an internal debate as to the validity of this approach and I wonder if anyone can point me to any reference that discusses the topic.

Thanks!

Bo

答:
It probably depends on the situation. In general, controls that magically appear and disappear are probably bad. If they are always present but disabled, the use will know that they can enable them somehow, and they'll look it up int he manual. If the controls are hidden, the user won't even know they're there to look them up. On the other hand, if the UI is already pretty complicated and getting cluttered, and these controls are only used in a very specific context, then it is probably OK to make then appear when necessary, because the user has already started some action which would require them.

The other option to hiding might be to have the controls in floating tool palettes/windows that appear when necessary.

I can't remember an actual refernce to cite though, sorry.


问:
Javascript Class missing ; before statement
I am trying to create a class and add several settings/const's.

I keep getting this error and I don't know what I'm doing wrong.

Error: SyntaxError: missing ; before statement[Learn More]  index.html:18:31

Here's the code:

```<code>class myClass {
 constructor() {
  this.settings: {
    age: 25,
    favAnimal: 'dog'
  }
 }
 myFunction() {
   console.log("say something");
 }
}

var aClass = new myClass("hello");
aClass.myFunction();
</code>```

What am I doing wrong?

答:
Use = instead of :, since you are assigning an object to a variable.

class myClass {
  constructor() {
    this.settings = {
      age: 25,
      favAnimal: 'dog'
    }
  }
  myFunction() {
    console.log("say something");
  }
}

var aClass = new myClass("hello");
aClass.myFunction();```

Body:
I am trying to create a class and add several settings/const's.

I keep getting this error and I don't know what I'm doing wrong.

Error: SyntaxError: missing ; before statement[Learn More]  index.html:18:31

Here's the code:

class myClass {
 constructor() {
  this.settings: {
    age: 25,
    favAnimal: 'dog'
  }
 }
 myFunction() {
   console.log("say something");
 }
}

var aClass = new myClass("hello");
aClass.myFunction();

What am I doing wrong?


问:
What precisely is the "silence" value in the SDL audio API?
In SDL, when you set up your audio output device, you and SDL have to agree on an audio format - e.g. 44.1KHz stereo 16-bit signed little-endian. That's fine. But along with the final agreed format, you also get a computed "silence" value which doesn't seem well documented.

A silent sound sample obviously consist of the same sample value repeated over and over again, and you want that to be at the "zero" level. In a sense any constant value will do, but you have to agree a value (so you don't get pops when switching to a different sound), and in a sane world you want to choose a value bang in the centre of your sample-value range.

So if you happen to use an unsigned format for your sample value range for 0..whatever, your silence value will be (whatever/2).

EDIT - inserted "unsigned" below to avoid confusion.

That's all fine. But the silence value you get given is an unsigned 8-bit integer. That doesn't work very well if you want unsigned 16 bit samples - the logical silence value of 0x8000 requires two different byte values and it requires them to be in the correct endian order.

So the silence value you get from SDL doesn't seem to make much sense. You can't use it to wipe your buffers, for instance, without dealing with extra complications and making inferences which pretty much make the precalculated silence value pointless anyway.

Which means, of course, that I've misunderstood the point.

So - if this isn't how the silence value is meant to be used, how should it be used?

答:
I have no evidence to back this up but I think the assumption here is that "silence" could be interpreted as "silence for common soundcard formats".  Those being:

Unsigned 8-bit integers

Signed 16-bit integers

Signed 32-bit integers (for 24-bit audio data)

Normalized 32-bit floating point

Normalized 64-bit floating point.

In all the cases except for unsigned 8-bit,  zero (0) is the "zero amplitude" value.  So the returned unsigned 8-bit integer contains all the possible values of "zero amplitude" for these formats.


问:
Searching a nested json from Node.js applictaion by id
My JSON file is as follows and my router
router.get('/books/:bookid', ctrlbooks.booksReadOne);
returns the following JSON which is as expected but if I want to return just the title for say for api of this kind with given id
router.get('/books/:bookid/titles/:titleid', ctrlbooks.titlesReadOne);
it wont work am i missing something?

```<code>[
  {
    "_id": "58dd21c3cb77090b930b6063",
    "bookAuthor": "George Orwell",
    "titles": [
      {
        "title": "Animal Farm",
        "_id": "58dd3f2701cc081056135dae",
        "reviews": [
          {
            "author": "Lisa",
            "rating": 4,
            "reviewText": "this is a review",
            "_id": "58dd8e13876c0f16b17cd7dc",
            "createdOn": "2017-03-30T23:00:35.662Z"
          }
        ],
        "favouredBy": [
          "bb, aa, cc"
        ]
      },
      {
        "title": "1984",
        "_id": "58dd42a59f12f110d1756f08",
        "reviews": [
          {
            "author": "jessy",
            "rating": 5,
            "reviewText": "REVIEW FOR SECOND TITLE",
            "_id": "58dd8ef46d4aaa16e4545c76",
            "createdOn": "2017-03-30T23:04:20.609Z"
          }
        ],
        "favouredBy": [
          "all"
        ]
      }
    ]
  }
]
</code>```

my controller for router
router.get('/books/:bookid', ctrlbooks.booksReadOne);
is

```<code>    module.exports.booksReadOne = function(req, res) {
        console.log('Finding book details', req.params);
        if (req.params && req.params.bookid) {
            Bok
                .findById(req.params.bookid)
                .exec(function(err, book) {
                    if (!book) {
                        sendJSONresponse(res, 404, {
                            "message": "bookid not found"
                        });
                        return;
                    } else if (err) {
                        console.log(err);
                        sendJSONresponse(res, 404, err);
                        return;
                    }
                    console.log(book);
                    sendJSONresponse(res, 200, book);
                });
        } else {
            console.log('No bookid specified');
            sendJSONresponse(res, 404, {
                "message": "No bookid in request"
            });
        }
    };
</code>```

and this is what I tried to return only the title with a given title id provided but this doesn't work when I tested it using postman

```<code>    module.exports.tilesReadOne = function(req, res) {
        console.log('Finding book details', req.params);
        if (req.params && req.params.titleid) {
            Bok
                .findById(req.params.titleid)
                .exec(function(err, book) {
                    if (!book) {
                        sendJSONresponse(res, 404, {
                            "message": "title not found"
                        });
                        return;
                    } else if (err) {
                        console.log(err);
                        sendJSONresponse(res, 404, err);
                        return;
                    }
                    console.log(book);
                    sendJSONresponse(res, 200, book);
                });
        } else {
            console.log('No title specified');
            sendJSONresponse(res, 404, {
                "message": "No title in request"
            });
        }
    };
</code>```

答:
Alternatively to aggregation, you can filter titles on application level:</p>

```<code>    Bok
        .findById(req.params.bookid)
        .exec(function(err, book) {
            if (book) {
                var matchingTitles = book.titles.filter(function(title){
                    return title._id == req.params.bookid
                })
                // return titles, if any
            }
        })
</code>```

Body:
My JSON file is as follows and my router
router.get('/books/:bookid', ctrlbooks.booksReadOne);
returns the following JSON which is as expected but if I want to return just the title for say for api of this kind with given id
router.get('/books/:bookid/titles/:titleid', ctrlbooks.titlesReadOne);
it wont work am i missing something?

[
  {
    "_id": "58dd21c3cb77090b930b6063",
    "bookAuthor": "George Orwell",
    "titles": [
      {
        "title": "Animal Farm",
        "_id": "58dd3f2701cc081056135dae",
        "reviews": [
          {
            "author": "Lisa",
            "rating": 4,
            "reviewText": "this is a review",
            "_id": "58dd8e13876c0f16b17cd7dc",
            "createdOn": "2017-03-30T23:00:35.662Z"
          }
        ],
        "favouredBy": [
          "bb, aa, cc"
        ]
      },
      {
        "title": "1984",
        "_id": "58dd42a59f12f110d1756f08",
        "reviews": [
          {
            "author": "jessy",
            "rating": 5,
            "reviewText": "REVIEW FOR SECOND TITLE",
            "_id": "58dd8ef46d4aaa16e4545c76",
            "createdOn": "2017-03-30T23:04:20.609Z"
          }
        ],
        "favouredBy": [
          "all"
        ]
      }
    ]
  }
]

my controller for router
router.get('/books/:bookid', ctrlbooks.booksReadOne);
is

    module.exports.booksReadOne = function(req, res) {
        console.log('Finding book details', req.params);
        if (req.params && req.params.bookid) {
            Bok
                .findById(req.params.bookid)
                .exec(function(err, book) {
                    if (!book) {
                        sendJSONresponse(res, 404, {
                            "message": "bookid not found"
                        });
                        return;
                    } else if (err) {
                        console.log(err);
                        sendJSONresponse(res, 404, err);
                        return;
                    }
                    console.log(book);
                    sendJSONresponse(res, 200, book);
                });
        } else {
            console.log('No bookid specified');
            sendJSONresponse(res, 404, {
                "message": "No bookid in request"
            });
        }
    };

and this is what I tried to return only the title with a given title id provided but this doesn't work when I tested it using postman

    module.exports.tilesReadOne = function(req, res) {
        console.log('Finding book details', req.params);
        if (req.params && req.params.titleid) {
            Bok
                .findById(req.params.titleid)
                .exec(function(err, book) {
                    if (!book) {
                        sendJSONresponse(res, 404, {
                            "message": "title not found"
                        });
                        return;
                    } else if (err) {
                        console.log(err);
                        sendJSONresponse(res, 404, err);
                        return;
                    }
                    console.log(book);
                    sendJSONresponse(res, 200, book);
                });
        } else {
            console.log('No title specified');
            sendJSONresponse(res, 404, {
                "message": "No title in request"
            });
        }
    };

Body:
Alternatively to aggregation, you can filter titles on application level:

    Bok
        .findById(req.params.bookid)
        .exec(function(err, book) {
            if (book) {
                var matchingTitles = book.titles.filter(function(title){
                    return title._id == req.params.bookid
                })
                // return titles, if any
            }
        })


问:
YouTubeAPI searchResult wrong
This is my API request with a randmon YT Channel:
https://www.googleapis.com/youtube/v3/search?key=XXXXXXXXXXXXXXXXX&channelId=UCqwoHjwau6Js8wOq6LSmCxQ&part=snippet,id&order=date&maxResults=50

"totalResults": 3889

But there are only 9 pages with maxResults=50 (instead of 78 pages!). Many videos are not in the list...for example this one:

nnw6VP1VvLw

What am I doing wrong?

Thanks for your help

答:
The search query has a call cap ( as well as a high quota count ). If you are wanting to list all videos from a selected channel, then use the PlayListItems instead.

Still has a max of 50 per call, but you can get all if you use nextPageToken and loop.

Title: YouTubeAPI searchResult wrong


问:
How to restart Azure Web App programmatically
Is any way to restart the Azure Web App programmatically, i.e. Kudu or some another kind?

I'v found that it is possible using Management Libraries, but it is not applicable for me since I can't create application in AD.

答:
Powershell:

```<code>Restart-AzureRmWebApp -ResourceGroupName xxx -Name xxx
</code>```

or using the provider operation:

```<code>Invoke-AzureRmResourceAction -ResourceGroupName xxx -ResourceType 'Microsoft.Web/sites' -ResourceName xxx `
  -ApiVersion '2015-08-01' -Action 'Restart' -Force
</code>```

Azure Cli (nodejs, depreciated):

```<code>azure webapp restart --resource-group xxx --name xxx
</code>```

Azure Cli (python):

```<code>az appservice web restart --resource-group xxx --name xxx
</code>```

or you can use Rest Api

Body:
Powershell:

Restart-AzureRmWebApp -ResourceGroupName xxx -Name xxx

or using the provider operation:

Invoke-AzureRmResourceAction -ResourceGroupName xxx -ResourceType 'Microsoft.Web/sites' -ResourceName xxx `
  -ApiVersion '2015-08-01' -Action 'Restart' -Force

Azure Cli (nodejs, depreciated):

azure webapp restart --resource-group xxx --name xxx

Azure Cli (python):

az appservice web restart --resource-group xxx --name xxx

or you can use Rest Api