问:
resume video play javascript
I'm trying to create a script to do autoplay video (done), to loop video (done), pause video when leave the window (switch to another tab on Chrome, for example, DONE). Now I want to resume playback when I switch back to the tab where the video was paused.

Here's what I got so far:

```<code><!DOCTYPE html>
<html>
<body>

<video id="myVideo" width="320" height="176" controls autoplay loop">
<!--<video id="myVideo" width="320" height="176" controls loop>-->
  <source src="myVideo.mp4" type="video/mp4">
  Your browser does not support HTML5 video.
</video>

<!--Script para fazer três coisas: carregar vídeo automaticamente, pausar quando trocar de aba e voltar quando clicar de volta e também para fazer loop do vídeo após o término-->
<script>
var vid = document.getElementById("myVideo");
function enableAutoplay() {
    vid.autoplay = true;
    vid.load();
}

function disableAutoplay() {
    vid.autoplay = false;
    vid.load();
}

function checkAutoplay() {
    alert(vid.autoplay);
}
</script>
<script>
document.addEventListener("visibilitychange", onchange);
function onchange (evt) {
   document.getElementById("myVideo").pause();
}
</script>
<!--Script para fazer três coisas: carregar vídeo automaticamente, pausar quando trocar de aba e voltar quando clicar de volta e também para fazer loop do vídeo após o término -->
<script>
window.addEventListener("visibilitychange", onchange);
function onchange (evt) {
    document.getElementByID("myVideo").onfocus = play();
}
</script>
</body>
</html>
</code>```

答:
this is working for me, with onfocus and onblur, tested in Chrome, Safari and Firefox:</p>

```<code><!DOCTYPE html>
<html>
<body>

<video id="myVideo" width="320" height="176" controls autoplay loop">
<!--<video id="myVideo" width="320" height="176" controls loop>-->
  <source src="myVideo.mp4" type="video/mp4">
  Your browser does not support HTML5 video.
</video>

<!--Script para fazer três coisas: carregar vídeo automaticamente, pausar quando trocar de aba e voltar quando clicar de volta e também para fazer loop do vídeo após o término-->
<script>
var vid = document.getElementById("myVideo");
function enableAutoplay() {
    vid.autoplay = true;
    vid.load();
}

function disableAutoplay() {
    vid.autoplay = false;
    vid.load();
}

function checkAutoplay() {
    //alert(vid.autoplay);
    console.log("checkAutoplay");
}

</script>
<script>
// called when the window/tab is shown
window.onfocus = function () {
    var date1 = new Date();
    console.log("onfocus " + date1 + " play ");
    document.getElementById("myVideo").play();
};
// called when the window/tab is hidden
window.onblur = function () {
    var date1 = new Date();
    console.log("onblur " + date1 + " pause ");
    document.getElementById("myVideo").pause();
};
</script>
</body>
</html>
</code>```

Title: resume video play javascript

Body:
I'm trying to create a script to do autoplay video (done), to loop video (done), pause video when leave the window (switch to another tab on Chrome, for example, DONE). Now I want to resume playback when I switch back to the tab where the video was paused.

Here's what I got so far:

<!DOCTYPE html>

<video id="myVideo" width="320" height="176" controls autoplay loop">

  <source src="myVideo.mp4" type="video/mp4">
  Your browser does not support HTML5 video.
</video>

Body:
this is working for me, with onfocus and onblur, tested in Chrome, Safari and Firefox:

<!DOCTYPE html>
<html>
<body>

<video id="myVideo" width="320" height="176" controls autoplay loop">
<!--<video id="myVideo" width="320" height="176" controls loop>-->
  <source src="myVideo.mp4" type="video/mp4">
  Your browser does not support HTML5 video.
</video>

<!--Script para fazer três coisas: carregar vídeo automaticamente, pausar quando trocar de aba e voltar quando clicar de volta e também para fazer loop do vídeo após o término-->
<script>
var vid = document.getElementById("myVideo");
function enableAutoplay() {
    vid.autoplay = true;
    vid.load();
}

function disableAutoplay() {
    vid.autoplay = false;
    vid.load();
}

function checkAutoplay() {
    //alert(vid.autoplay);
    console.log("checkAutoplay");
}

</script>
<script>
// called when the window/tab is shown
window.onfocus = function () {
    var date1 = new Date();
    console.log("onfocus " + date1 + " play ");
    document.getElementById("myVideo").play();
};
// called when the window/tab is hidden
window.onblur = function () {
    var date1 = new Date();
    console.log("onblur " + date1 + " pause ");
    document.getElementById("myVideo").pause();
};
</script>
</body>
</html>


来源: stackexchange

问:
Angular2 callback vs Promise/Observable
Context:

I have AWS cognito working on an Angular 2 app. The AWS demo uses callbacks to handle asynchronous requests.

```<code>public getSession(callback: CognitoCallback) {
let cognitoUser: CognitoUser = this.getCurrentUser();
let cognitoUtil = this;
cognitoUser.getSession(function (err, session) {
  if (err) {
    let error = new CognitoError(err.name, err.message);
    callback.cognitoCallback(error, null);
    return;
  }
  if (!session.isValid()) {
    let error = new CognitoError("SessionInvalid", "Session is not valid");
    callback.cognitoCallback(error, session);
    return;
  }
  callback.cognitoCallback(null, session);
  cognitoUtil.setCurrentUser(cognitoUser);
  return;
});
</code>```

}

Is it possible to implement the same functionality with Promise or Observable?

Thanks in advance.

答:
If you use bluebird, you can do this</p>

```<code>let getSession = Promise.promisify(cognitoUser.getSession);

getSession.then(function (session) {
// session is valid
}, function (err) {
// error getting session
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Angular2 callback vs Promise/Observable

Body:
Context:

I have AWS cognito working on an Angular 2 app. The AWS demo uses callbacks to handle asynchronous requests.

public getSession(callback: CognitoCallback) {
let cognitoUser: CognitoUser = this.getCurrentUser();
let cognitoUtil = this;
cognitoUser.getSession(function (err, session) {
  if (err) {
    let error = new CognitoError(err.name, err.message);
    callback.cognitoCallback(error, null);
    return;
  }
  if (!session.isValid()) {
    let error = new CognitoError("SessionInvalid", "Session is not valid");
    callback.cognitoCallback(error, session);
    return;
  }
  callback.cognitoCallback(null, session);
  cognitoUtil.setCurrentUser(cognitoUser);
  return;
});

}

Is it possible to implement the same functionality with Promise or Observable?

Thanks in advance.

Body:
If you use bluebird, you can do this

let getSession = Promise.promisify(cognitoUser.getSession);

getSession.then(function (session) {
// session is valid
}, function (err) {
// error getting session
});


问:
Difference between timezones America/Los_Angeles and US/Pacific and PST8PDT?
I need to convert a bunch of dates in a MySQL database from Pacific time (America/Los_Angeles) to UTC. I found a great SO answer on how to do this.

During my tests and preparation, I'm finding that I'm getting the same time conversions when using any of the following time zone names:

America/Los_Angeles

US/Pacific

PST8PDT

So my questions are the following:

Are these all just aliases to the same thing? Or are there actual differences between them at some point in time?

If I want to provide a list of timezones to users on a website, would it be better to give them selections from the America group of names, or the US group of names?

答:
US/Pacific and PST8PDT both belong to the "other" timezones, which come with this warning:

Please do not use any of the timezones listed here (besides UTC), they only exist for backward compatible reasons.

They should all refer to the same timezone, compare:

http://www.travelmath.com/time-zone/PST8PDT

http://www.travelmath.com/time-zone/US/Pacific

http://www.travelmath.com/time-zone/America/Los_Angeles

As such, you should use America/Los_Angeles, which incidentally should also be a pretty "natural" and easy thing to select for users.

ContentLicense: CC BY-SA 2.5


问:
How to count the number of zeros at the start of a string
I have a string:

```<code>"0011HelloWor00ld001"
</code>```

How do I count the number of zeros in the starting of the string?
For example, the above string should return 2.

I tried .match(/^[0]+/).size but it doesn't work.

答:
You could also simply use the index method of String like

```<code>str = '0011HelloWor00ld001'
# as noted by @steenslag if the full string is zeros index will return nil
# solve by returning full string length
str.index(/[^0]/) || str.length
#=> 2
</code>```

Body:
I have a string:

"0011HelloWor00ld001"

How do I count the number of zeros in the starting of the string?
For example, the above string should return 2.

I tried .match(/^[0]+/).size but it doesn't work.

Body:
You could also simply use the index method of String like

str = '0011HelloWor00ld001'
# as noted by @steenslag if the full string is zeros index will return nil
# solve by returning full string length
str.index(/[^0]/) || str.length
#=> 2


问:
PHP Upload File
I'm trying to upload file to server with php script. I'm Using MAMP with PHP7.0.8

I have HTML form:

```<code><form enctype="multipart/form-data" action="hi" method="POST">
  <input type="hidden" name="MAX_FILE_SIZE" value="300000" />
    Send File: <input name="userfile" type="file" />
  <input type="submit" value="Send File" />
</form>
</code>```

And simple php:

```<code>  <?php

$uploaddir = 'img/';
print_r($uploadfile = $uploaddir.basename($_FILES['userfile']['name']));

  echo '```';
  if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
      echo "File is valid, and was successfully uploaded.\n";
  } else {
      echo "Possible file upload attack!\n";
  }

  echo 'info:';
  print_r($_FILES);
  echo "
";
  print_r($_FILES['userfile']['error']);
  print "```";

?>
</code>```

My result is:

Possible file upload attack!

```<code>info:Array
(
    [userfile] => Array
        (
            [name] => high-school-icon.png
            [type] => image/png
            [tmp_name] => /Applications/MAMP/tmp/php/phpoaPmYv
            [error] => 0
            [size] => 1807
        )

)
</code>```

答:
Form action documentation

Error:
action="hi"

Change it to: action="simple.php"

```<code><form enctype="multipart/form-data" action="simple.php" method="POST">
  <input type="hidden" name="MAX_FILE_SIZE" value="300000" />
    Send File: <input name="userfile" type="file" />
  <input type="submit" value="Send File" />
</form>
</code>```

Title: PHP Upload File

Body:
I'm trying to upload file to server with php script. I'm Using MAMP with PHP7.0.8

I have HTML form:

<form enctype="multipart/form-data" action="hi" method="POST">
  <input type="hidden" name="MAX_FILE_SIZE" value="300000" />
    Send File: <input name="userfile" type="file" />
  <input type="submit" value="Send File" />
</form>

And simple php:

  <?php

$uploaddir = 'img/';
print_r($uploadfile = $uploaddir.basename($_FILES['userfile']['name']));

  echo '
';
  if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
      echo "File is valid, and was successfully uploaded.\n";
  } else {
      echo "Possible file upload attack!\n";
  }

  echo 'info:';
  print_r($_FILES);
  echo "
";
  print_r($_FILES['userfile']['error']);
  print "
";

?>

My result is:

Possible file upload attack!

info:Array
(
    [userfile] => Array
        (
            [name] => high-school-icon.png
            [type] => image/png
            [tmp_name] => /Applications/MAMP/tmp/php/phpoaPmYv
            [error] => 0
            [size] => 1807
        )

)

Body:
Form action documentation

Error:
action="hi"

Change it to: action="simple.php"

<form enctype="multipart/form-data" action="simple.php" method="POST">
  <input type="hidden" name="MAX_FILE_SIZE" value="300000" />
    Send File: <input name="userfile" type="file" />
  <input type="submit" value="Send File" />
</form>


问:
Add 'Currency' filter in custom filer - Angular JS
i want to add builtin filter - currency to my custom filter.  Trying to do in angular js</p>

```<code> (function(angular) {
    'use strict';
    angular
        .module('testApp')
        .filter('amount', function() {
            return function(amount) {
                if (!amount) {
                    return 'Invalid Amount';
                } else {
                    //Here i want to add CURRENCY filter "| currency"
                    return amount;
                }
            }
        })
})();
</code>```

答:
You can use number filter. Try it please

```<code>.filter('amount', function($filter) {
            return function(amount) {
                if (!amount) {
                    return 'Invalid Amount';
                } else {
                    //Here i want to add CURRENCY filter "| currency"
                    var newAmount = $filter('number')(amount, 2);
                    return "$"+ newAmount;
                }
            }
  })
</code>```

or this like

```<code>return $filter('currency')(amount, "$", 2);
</code>```

Body:
i want to add builtin filter - currency to my custom filter.  Trying to do in angular js

 (function(angular) {
    'use strict';
    angular
        .module('testApp')
        .filter('amount', function() {
            return function(amount) {
                if (!amount) {
                    return 'Invalid Amount';
                } else {
                    //Here i want to add CURRENCY filter "| currency"
                    return amount;
                }
            }
        })
})();

Body:
You can use number filter. Try it please

.filter('amount', function($filter) {
            return function(amount) {
                if (!amount) {
                    return 'Invalid Amount';
                } else {
                    //Here i want to add CURRENCY filter "| currency"
                    var newAmount = $filter('number')(amount, 2);
                    return "$"+ newAmount;
                }
            }
  })

or this like

return $filter('currency')(amount, "$", 2);


问:
JAVA installation error on Yocto build
I'm having a lot of trouble installing Java on my Poky Linux system. I'm building my system using Yocto with the following configuration:

local.conf

```<code>MACHINE ??= "intel-corei7-64"

DISTRO ?= "poky"

PACKAGE_CLASSES ?= "package_rpm"

SDKMACHINE ?= "x86_64"

EXTRA_IMAGE_FEATURES ?= "debug-tweaks"

USER_CLASSES ?= "buildstats image-mklibs image-prelink"

PATCHRESOLVE = "noop"

BB_DISKMON_DIRS = "\
    STOPTASKS,${TMPDIR},1G,100K \
    STOPTASKS,${DL_DIR},1G,100K \
    STOPTASKS,${SSTATE_DIR},1G,100K \
    STOPTASKS,/tmp,100M,100K \
    ABORT,${TMPDIR},100M,1K \
    ABORT,${DL_DIR},100M,1K \
    ABORT,${SSTATE_DIR},100M,1K \
    ABORT,/tmp,10M,1K"

PACKAGECONFIG_append_pn-qemu-native = " sdl"
PACKAGECONFIG_append_pn-nativesdk-qemu = " sdl"

CONF_VERSION = "1"

BB_NUMBER_THREADS = '12'
PARALLEL_MAKE = '-j 12'

# Java installation
CORE_IMAGE_EXTRA_INSTALL += "gtkperf libxslt"
IMAGE_INSTALL_append = " openjdk-7-jre "

LICENSE_FLAGS_WHITELIST += "oracle_java"
PREFERRED_PROVIDER_virtual/java-initial-native = "cacao-initial-native"
PREFERRED_PROVIDER_virtual/java-native = "jamvm-native"
PREFERRED_PROVIDER_virtual/javac-native = "ecj-bootstrap-native"

PREFERRED_VERSION_xserver-nodm-init = "1.0"

# OpenCV installation
CORE_IMAGE_EXTRA_INSTALL += "opencv opencv-samples libopencv-core-dev libopencv-highgui-dev libopencv-imgproc-dev libopencv-objdetect-dev libopencv-ml-dev"
</code>```

bblayers.conf

```<code># POKY_BBLAYERS_CONF_VERSION is increased each time build/conf/bblayers.conf
# changes incompatibly
POKY_BBLAYERS_CONF_VERSION = "2"

BBPATH = "${TOPDIR}"
BBFILES ?= ""

BBLAYERS ?= " \
  $HOME/poky/meta \
  $HOME/poky/meta-poky \
  $HOME/poky/meta-yocto-bsp \
  $HOME/poky/meta-intel \
  $HOME/poky/meta-openembedded/meta-oe \
  $HOME/poky/meta-intel-realsense \
  $HOME/poky/meta-java \
  $HOME/poky/meta-oracle-java \
  "
</code>```

I need to use morty branch since I'm using Intel Realsense layer which is only compatible with 4.8 kernel

```<code>Build Configuration:
BB_VERSION        = "1.32.0"
BUILD_SYS         = "x86_64-linux"
NATIVELSBSTRING   = "CentOSLinux-7.3.1611"
TARGET_SYS        = "x86_64-poky-linux"
MACHINE           = "intel-corei7-64"
DISTRO            = "poky"
DISTRO_VERSION    = "2.2.1"
TUNE_FEATURES     = "m64 corei7"
TARGET_FPU        = ""
meta
meta-poky
meta-yocto-bsp    = "morty:924e576b8930fd2268d85f0b151e5f68a3c2afce"
meta-intel        = "morty:6add41510412ca196efb3e4f949d403a8b6f35d7"
meta-oe           = "morty:fe5c83312de11e80b85680ef237f8acb04b4b26e"
meta-intel-realsense = "morty:2c0dfe9690d2871214fba9c1c32980a5eb89a421"
meta-java         = "master:67e48693501bddb80745b9735b7b3d4d28dce9a1"
meta-oracle-java  = "morty:f44365f02b283c3fb362dc99e2e996d3f11e356e"
</code>```

I get the following error:

```<code>ERROR: openjdk-7-jre-99b00-2.6.5-r6.1 do_compile: oe_runmake failed
ERROR: openjdk-7-jre-99b00-2.6.5-r6.1 do_compile: Function failed: do_compile (log file is located at /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/temp/log.do_compile.3780)
ERROR: Logfile of failure stored in: /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/temp/log.do_compile.3780
Log data follows:
</code>```

and then several hundreds lines of error log.
Any help is appreciated.

EDIT: From the log.do_compile file

```<code>ERROR: oe_runmake failed
In file included from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/oops/constantPoolOop.hpp:29:0,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/oops/methodOop.hpp:33,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/runtime/frame.hpp:29,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/prims/jvmtiExport.hpp:33,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/runtime/thread.hpp:32,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/os/linux/vm/thread_linux.inline.hpp:30,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/memory/resourceArea.hpp:30,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/classfile/classFileParser.hpp:29,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/classfile/classLoader.hpp:28,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/classfile/systemDictionary.hpp:29,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/ci/ciEnv.hpp:30,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/ci/ciUtilities.hpp:28,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/ci/ciNullObject.hpp:30,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/ci/ciConstant.hpp:29,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/precompiled/precompiled.hpp:36:
/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/oops/cpCacheOop.hpp: At global scope:
/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/oops/cpCacheOop.hpp:189:42: error: left operand of shift expression '(-1 << 28)' is negative [-fpermissive]
     option_bits_mask           = ~(((-1) << tos_state_shift) | (field_index_mask | parameter_size_mask))
                                    ~~~~~~^~~~~~~~~~~~~~~~~~~
/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/oops/cpCacheOop.hpp:189:104: error: enumerator value for 'option_bits_mask' is not an integer constant
     option_bits_mask           = ~(((-1) << tos_state_shift) | (field_index_mask | parameter_size_mask))
                                                                                ^
In file included from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/ci/ciEnv.hpp:32:0,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/ci/ciUtilities.hpp:28,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/ci/ciNullObject.hpp:30,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/ci/ciConstant.hpp:29,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/precompiled/precompiled.hpp:36:
/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/code/dependencies.hpp:169:59: error: left operand of shift expression '(-1 << 1)' is negative [-fpermissive]
     all_types           = ((1 << TYPE_LIMIT) - 1) & ((-1) << FIRST_TYPE),
                                                     ~~~~~~^~~~~~~~~~~~~~
/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/code/dependencies.hpp:169:72: error: enumerator value for 'all_types' is not an integer constant
     all_types           = ((1 << TYPE_LIMIT) - 1) & ((-1) << FIRST_TYPE),
                                                                        ^
gmake[7]: *** [precompiled.hpp.gch] Error 1
gmake[7]: Leaving directory `/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk.build/hotspot/outputdir/linux_amd64_zero/product'
gmake[6]: *** [the_vm] Error 2
gmake[6]: Leaving directory `/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk.build/hotspot/outputdir/linux_amd64_zero/product'
gmake[5]: *** [productzero] Error 2
gmake[5]: Leaving directory `/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk.build/hotspot/outputdir'
gmake[4]: *** [generic_buildzero] Error 2
gmake[4]: Leaving directory `/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/make'
gmake[3]: *** [productzero] Error 2
gmake[3]: Leaving directory `/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/make'
gmake[2]: *** [hotspot-build] Error 2
gmake[2]: Leaving directory `/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk'
gmake[1]: *** [build_product_image] Error 2
gmake[1]: Leaving directory `/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk'
make: *** [Makefile:2451: stamps/icedtea.stamp] Error 2
ERROR: Function failed: do_compile (log file is located at /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/temp/log.do_compile.3780)
</code>```

答:
I manually patched the files generating those error and builded the image. It gave a new error but successfully wrote the image. Java in installed:

```<code>root@intel-corei7-64:~# java -version
java version "1.7.0_99"
OpenJDK Runtime Environment (IcedTea 2.6.5) (99b00-2.6.5)
OpenJDK 64-Bit Zero VM (build 24.95-b01, interpreted mode)
</code>```

The solution is either:

Manually patch openjdk following
this

Use a newer version of openjdk. This can be achived using a more
    recent commit for the meta-java repository or setting a newer
    preferred version in the local.conf.

EDIT: Added guide link.

Guide

Since I'm using this image in an OpenSource project I made a little guide on how to overcome the problems I had during the building process.
The guide can be found here.

UPDATE: I upgraded the JRE and JDK version. The new guide can be found here. For the bravest among you there's also an installer script.

Title: JAVA installation error on Yocto build

Body:
I'm having a lot of trouble installing Java on my Poky Linux system. I'm building my system using Yocto with the following configuration:

local.conf

MACHINE ??= "intel-corei7-64"

DISTRO ?= "poky"

PACKAGE_CLASSES ?= "package_rpm"

SDKMACHINE ?= "x86_64"

EXTRA_IMAGE_FEATURES ?= "debug-tweaks"

USER_CLASSES ?= "buildstats image-mklibs image-prelink"

PATCHRESOLVE = "noop"

BB_DISKMON_DIRS = "\
    STOPTASKS,${TMPDIR},1G,100K \
    STOPTASKS,${DL_DIR},1G,100K \
    STOPTASKS,${SSTATE_DIR},1G,100K \
    STOPTASKS,/tmp,100M,100K \
    ABORT,${TMPDIR},100M,1K \
    ABORT,${DL_DIR},100M,1K \
    ABORT,${SSTATE_DIR},100M,1K \
    ABORT,/tmp,10M,1K"

PACKAGECONFIG_append_pn-qemu-native = " sdl"
PACKAGECONFIG_append_pn-nativesdk-qemu = " sdl"

CONF_VERSION = "1"

BB_NUMBER_THREADS = '12'
PARALLEL_MAKE = '-j 12'

# Java installation
CORE_IMAGE_EXTRA_INSTALL += "gtkperf libxslt"
IMAGE_INSTALL_append = " openjdk-7-jre "

LICENSE_FLAGS_WHITELIST += "oracle_java"
PREFERRED_PROVIDER_virtual/java-initial-native = "cacao-initial-native"
PREFERRED_PROVIDER_virtual/java-native = "jamvm-native"
PREFERRED_PROVIDER_virtual/javac-native = "ecj-bootstrap-native"

PREFERRED_VERSION_xserver-nodm-init = "1.0"

# OpenCV installation
CORE_IMAGE_EXTRA_INSTALL += "opencv opencv-samples libopencv-core-dev libopencv-highgui-dev libopencv-imgproc-dev libopencv-objdetect-dev libopencv-ml-dev"

bblayers.conf

# POKY_BBLAYERS_CONF_VERSION is increased each time build/conf/bblayers.conf
# changes incompatibly
POKY_BBLAYERS_CONF_VERSION = "2"

BBPATH = "${TOPDIR}"
BBFILES ?= ""

BBLAYERS ?= " \
  $HOME/poky/meta \
  $HOME/poky/meta-poky \
  $HOME/poky/meta-yocto-bsp \
  $HOME/poky/meta-intel \
  $HOME/poky/meta-openembedded/meta-oe \
  $HOME/poky/meta-intel-realsense \
  $HOME/poky/meta-java \
  $HOME/poky/meta-oracle-java \
  "

I need to use morty branch since I'm using Intel Realsense layer which is only compatible with 4.8 kernel

Build Configuration:
BB_VERSION        = "1.32.0"
BUILD_SYS         = "x86_64-linux"
NATIVELSBSTRING   = "CentOSLinux-7.3.1611"
TARGET_SYS        = "x86_64-poky-linux"
MACHINE           = "intel-corei7-64"
DISTRO            = "poky"
DISTRO_VERSION    = "2.2.1"
TUNE_FEATURES     = "m64 corei7"
TARGET_FPU        = ""
meta
meta-poky
meta-yocto-bsp    = "morty:924e576b8930fd2268d85f0b151e5f68a3c2afce"
meta-intel        = "morty:6add41510412ca196efb3e4f949d403a8b6f35d7"
meta-oe           = "morty:fe5c83312de11e80b85680ef237f8acb04b4b26e"
meta-intel-realsense = "morty:2c0dfe9690d2871214fba9c1c32980a5eb89a421"
meta-java         = "master:67e48693501bddb80745b9735b7b3d4d28dce9a1"
meta-oracle-java  = "morty:f44365f02b283c3fb362dc99e2e996d3f11e356e"

I get the following error:

ERROR: openjdk-7-jre-99b00-2.6.5-r6.1 do_compile: oe_runmake failed
ERROR: openjdk-7-jre-99b00-2.6.5-r6.1 do_compile: Function failed: do_compile (log file is located at /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/temp/log.do_compile.3780)
ERROR: Logfile of failure stored in: /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/temp/log.do_compile.3780
Log data follows:

and then several hundreds lines of error log.
Any help is appreciated.

EDIT: From the log.do_compile file

ERROR: oe_runmake failed
In file included from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/oops/constantPoolOop.hpp:29:0,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/oops/methodOop.hpp:33,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/runtime/frame.hpp:29,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/prims/jvmtiExport.hpp:33,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/runtime/thread.hpp:32,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/os/linux/vm/thread_linux.inline.hpp:30,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/memory/resourceArea.hpp:30,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/classfile/classFileParser.hpp:29,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/classfile/classLoader.hpp:28,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/classfile/systemDictionary.hpp:29,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/ci/ciEnv.hpp:30,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/ci/ciUtilities.hpp:28,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/ci/ciNullObject.hpp:30,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/ci/ciConstant.hpp:29,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/precompiled/precompiled.hpp:36:
/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/oops/cpCacheOop.hpp: At global scope:
/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/oops/cpCacheOop.hpp:189:42: error: left operand of shift expression '(-1 << 28)' is negative [-fpermissive]
     option_bits_mask           = ~(((-1) << tos_state_shift) | (field_index_mask | parameter_size_mask))
                                    ~~~~~~^~~~~~~~~~~~~~~~~~~
/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/oops/cpCacheOop.hpp:189:104: error: enumerator value for 'option_bits_mask' is not an integer constant
     option_bits_mask           = ~(((-1) << tos_state_shift) | (field_index_mask | parameter_size_mask))
                                                                                ^
In file included from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/ci/ciEnv.hpp:32:0,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/ci/ciUtilities.hpp:28,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/ci/ciNullObject.hpp:30,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/ci/ciConstant.hpp:29,
                 from /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/precompiled/precompiled.hpp:36:
/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/code/dependencies.hpp:169:59: error: left operand of shift expression '(-1 << 1)' is negative [-fpermissive]
     all_types           = ((1 << TYPE_LIMIT) - 1) & ((-1) << FIRST_TYPE),
                                                     ~~~~~~^~~~~~~~~~~~~~
/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/src/share/vm/code/dependencies.hpp:169:72: error: enumerator value for 'all_types' is not an integer constant
     all_types           = ((1 << TYPE_LIMIT) - 1) & ((-1) << FIRST_TYPE),
                                                                        ^
gmake[7]: *** [precompiled.hpp.gch] Error 1
gmake[7]: Leaving directory `/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk.build/hotspot/outputdir/linux_amd64_zero/product'
gmake[6]: *** [the_vm] Error 2
gmake[6]: Leaving directory `/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk.build/hotspot/outputdir/linux_amd64_zero/product'
gmake[5]: *** [productzero] Error 2
gmake[5]: Leaving directory `/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk.build/hotspot/outputdir'
gmake[4]: *** [generic_buildzero] Error 2
gmake[4]: Leaving directory `/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/make'
gmake[3]: *** [productzero] Error 2
gmake[3]: Leaving directory `/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk/hotspot/make'
gmake[2]: *** [hotspot-build] Error 2
gmake[2]: Leaving directory `/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk'
gmake[1]: *** [build_product_image] Error 2
gmake[1]: Leaving directory `/home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/icedtea-2.6.5/build/openjdk'
make: *** [Makefile:2451: stamps/icedtea.stamp] Error 2
ERROR: Function failed: do_compile (log file is located at /home/dalben/NewBuild/poky/filec/tmp/work/corei7-64-poky-linux/openjdk-7-jre/99b00-2.6.5-r6.1/temp/log.do_compile.3780)

Body:
I manually patched the files generating those error and builded the image. It gave a new error but successfully wrote the image. Java in installed:

root@intel-corei7-64:~# java -version
java version "1.7.0_99"
OpenJDK Runtime Environment (IcedTea 2.6.5) (99b00-2.6.5)
OpenJDK 64-Bit Zero VM (build 24.95-b01, interpreted mode)

The solution is either:

Manually patch openjdk following
this

Use a newer version of openjdk. This can be achived using a more
    recent commit for the meta-java repository or setting a newer
    preferred version in the local.conf.

EDIT: Added guide link.

Guide

Since I'm using this image in an OpenSource project I made a little guide on how to overcome the problems I had during the building process.
The guide can be found here.

UPDATE: I upgraded the JRE and JDK version. The new guide can be found here. For the bravest among you there's also an installer script.


问:
Container killed by the ApplicationMaster Exit code is 143
I've been getting the following error in several cases:

```<code>2017-03-23 11:55:10,794 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.TaskAttemptImpl: Diagnostics report from attempt_1490079327128_0048_r_000003_0: Container killed by the ApplicationMaster.

Container killed on request. Exit code is 143
Container exited with a non-zero exit code 143
</code>```

I noticed it happens one large sorts but when i change the "Sort Allocation Memory" it does not help.

I tried changing other memory properties but yet, the solution eludes me.
Is there a good explanation to how Mapreduce works and what's the interaction between the different components?
What should I change? where do I locate the Java error leading to this?

答:
I found out I mixed up two separate things.
The 143 exit code is from the metrics collector which is down.
The Jobs are killed, as far as I understand, due to no memory issues.
The problem is with large window functions that cant reduce the data till the last one which contains all the data.

Although, the place in the logs where it gives the reason why the job was killed, still eludes me.

Body:
I've been getting the following error in several cases:

2017-03-23 11:55:10,794 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.TaskAttemptImpl: Diagnostics report from attempt_1490079327128_0048_r_000003_0: Container killed by the ApplicationMaster.

Container killed on request. Exit code is 143
Container exited with a non-zero exit code 143

I noticed it happens one large sorts but when i change the "Sort Allocation Memory" it does not help.

I tried changing other memory properties but yet, the solution eludes me.
Is there a good explanation to how Mapreduce works and what's the interaction between the different components?
What should I change? where do I locate the Java error leading to this?


问:
Azure Data Factory - copy resources between subscriptions
I have 25 pipelines and numerous datasets defined in Azure data factory. What is the best way to copy/replicate (not move) these pipelines/datasets/linkes services from one subscription to another? Appreciate your help!</p>

答:
The best way would be to use a Visual Studio project.

The copy wizard in the portal is handy and the 'Author and Deploy' blade is nice. But best practice would be to develop and deploy your ADF solutions in Visual Studio first. Plus source control them of course! You can then build and publish from Visual Studio to any Azure subscriptions you have access to. The publish wizard is really nice and gives you the option to choose different configuration files for different environments. Eg. Live, Test, Dev.

I've written a blog post on using ADF config files if your interested in that approach. Here: https://www.purplefrogsystems.com/paul/2017/01/using-azure-data-factory-configuration-files/

Next best way. If you don't have a VS project yet, it's possible to reverse engineer one from an existing Azure Data Factory using the Cloud Explorer panel. See below.

But be warned it won't bring down authentication values and keys for your linked services. You'll need to recreate them. Just the same as you see the JSON attribute values masked in the portal. Eg "authorization": "**********",

Side note; You'll need to use Visual Studio 2015. Currently ADF projects aren't supported in Visual Studio 2017.

The worst way would be to copy and paste all of the JSON via notepad. You need to do it in order. Linked Services > Datasets > Pipelines > Activities.

ContentLicense: CC BY-SA 4.0


问:
building library variants with scons
I have an existing C library that's built with scons (the library has it's own
SConscript). This code now contains two variations controlled by #ifdefs. How
do I tell scons to build two variants of this library that can live side by
side (so applications can link against the appropriate variation)?

Conceptually, it's something like this:

```<code>driver_sources = [ ... ]
env.Library('drivers', driver_sources)

env.Library('drivers_withflag', driver_sources,
            CPPDEFINES += ['FLAG'])
</code>```

SCons (understandably) doesn't like using the same source list for different
outputs with different environments because the intermediate object names
conflict.

I'm not sure whether to approach this problem by somehow deriving a new
Builder for drivers_withflag objects, or whether I should include my library's
SConscript twice with some parameter to specify the #defines (and I could put
each variant in its own build directory). Any advice?

答:
Here's a link to some relevant documentation: http://www.scons.org/doc/1.1.0/HTML/scons-user/x1392.html

I think it would go something like this

```<code>driver_sources = [ ... ]

env.Library('libdrivers', driver_sources)

env_flag = env.Clone()

env_flag.Append(CPPDEFINES = ['FLAG'])

flag_objects = [os.path.splitext(src)[0] + '_flag' +
  env['OBJSUFFIX'] for src in driver_sources]

d_wf = [env_flag.Object(tgt, src) for tgt,src in
  zip(flag_objects, driver_sources)]

env_flag.Library(d_wf)
</code>```

This would go directly inside your current SConscript file, however you could also take a look at this question: here

You could use the steps outlined there in whatever file calls your library's SConscript file to setup two environments, then just call the SConscript twice with each one.

Hope that helps.

Title: building library variants with scons

Body:
I have an existing C library that's built with scons (the library has it's own
SConscript). This code now contains two variations controlled by #ifdefs. How
do I tell scons to build two variants of this library that can live side by
side (so applications can link against the appropriate variation)?

Conceptually, it's something like this:

driver_sources = [ ... ]
env.Library('drivers', driver_sources)

env.Library('drivers_withflag', driver_sources,
            CPPDEFINES += ['FLAG'])

SCons (understandably) doesn't like using the same source list for different
outputs with different environments because the intermediate object names
conflict.

I'm not sure whether to approach this problem by somehow deriving a new
Builder for drivers_withflag objects, or whether I should include my library's
SConscript twice with some parameter to specify the #defines (and I could put
each variant in its own build directory). Any advice?

Body:
Here's a link to some relevant documentation: http://www.scons.org/doc/1.1.0/HTML/scons-user/x1392.html

I think it would go something like this

driver_sources = [ ... ]

env.Library('libdrivers', driver_sources)

env_flag = env.Clone()

env_flag.Append(CPPDEFINES = ['FLAG'])

flag_objects = [os.path.splitext(src)[0] + '_flag' +
  env['OBJSUFFIX'] for src in driver_sources]

d_wf = [env_flag.Object(tgt, src) for tgt,src in
  zip(flag_objects, driver_sources)]

env_flag.Library(d_wf)

This would go directly inside your current SConscript file, however you could also take a look at this question: here

You could use the steps outlined there in whatever file calls your library's SConscript file to setup two environments, then just call the SConscript twice with each one.

Hope that helps.


问:
Height 100% and css issue with footer
I am currently working on a script and in some pages there isn't enough content.In this case I want the page to cover 100% of the browser and put the footer at the bottom.I tried many codes and nothing seems to work I ended up by having a code like this:

```<code><div class="container">
<div id=nav>
NAV
</div>
<div id=core>
    <div id=content>
        <div id=tophea>
           TOP Content
        </div>
        <div id=msgs>
       MSG Content
        </div>
    </div>
    <div id="footer">
    Footer
    </div>
    </div>
</div>
</code>```

and css like this :

```<code>#container{
  height:100%
}
#nav{
  height:55px;
}
#core{
  height:100%
}
#content{
  height:100%;
  background:red;
}
</code>```

Here is my jsfiddle : https://jsfiddle.net/k8k7o36b/

Any help will be appreciate. I'll be more than thankful if you add small explanation so I can understand what were I doing wrong.
Thanks

答:
#container{
  height:100%
}
#nav{
  height:55px;
}
#core{
  height:100%
}
#content{
  height:100%;
  background:red;
}
#footer {
    background-color: orange;
    position: absolute;
    left: 0;
    bottom: 0;
    height: 100px;
    width: 100%;
    overflow:hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div id=nav>
    NAV
    </div>
    <div id=core>
        <div id=content>
            <div id=tophea>
               TOP Content
            </div>
            <div id=msgs>
           MSG Content
            </div>
        </div>
        <footer id="footer">
        Footer
        </footer>
      </div>
</div></code>```

This should do it. I changed div to a footer and added some styling to the #footer id so that it has a position: absolute; and bottom: 0;. You can look into what position: absolute does here.

Edit: Obviously, you can adjust the height of the footer however you want, I just set it to 100px and background-color orange so that we can see it better.

Title: Height 100% and css issue with footer

Body:
I am currently working on a script and in some pages there isn't enough content.In this case I want the page to cover 100% of the browser and put the footer at the bottom.I tried many codes and nothing seems to work I ended up by having a code like this:

NAV

           TOP Content

       MSG Content

    Footer

and css like this :

#container{
  height:100%
}
#nav{
  height:55px;
}
#core{
  height:100%
}
#content{
  height:100%;
  background:red;
}

Here is my jsfiddle : https://jsfiddle.net/k8k7o36b/

Any help will be appreciate. I'll be more than thankful if you add small explanation so I can understand what were I doing wrong.
Thanks

Body:
#container{
  height:100%
}
#nav{
  height:55px;
}
#core{
  height:100%
}
#content{
  height:100%;
  background:red;
}
#footer {
    background-color: orange;
    position: absolute;
    left: 0;
    bottom: 0;
    height: 100px;
    width: 100%;
    overflow:hidden;
}

<div class="container">
    <div id=nav>
    NAV
    </div>
    <div id=core>
        <div id=content>
            <div id=tophea>
               TOP Content
            </div>
            <div id=msgs>
           MSG Content
            </div>
        </div>
        <footer id="footer">
        Footer
        </footer>
      </div>
</div>

This should do it. I changed div to a footer and added some styling to the #footer id so that it has a position: absolute; and bottom: 0;. You can look into what position: absolute does here.

Edit: Obviously, you can adjust the height of the footer however you want, I just set it to 100px and background-color orange so that we can see it better.


问:
BigQuery except double nested column
Hi need to exclude the column hits.latencyTracking.userTimingLabel from my table and select all the other columns. How can I do this in Standard Sql?
I found already a question on a similar problem (BigQuery select * except nested column) but in my case I have a double nested column and I am not able do adapt the code.
thanks

答:
If hits is an array and latencyTracking is a struct, then:

```<code>SELECT ARRAY(SELECT (SELECT AS STRUCT latencyTracking.* EXCEPT(userTimingLabel)) AS latencyTracking FROM UNNEST(hits)) AS hits
FROM YourTable;
</code>```

Title: BigQuery except double nested column

Body:
If hits is an array and latencyTracking is a struct, then:

SELECT ARRAY(SELECT (SELECT AS STRUCT latencyTracking.* EXCEPT(userTimingLabel)) AS latencyTracking FROM UNNEST(hits)) AS hits
FROM YourTable;


问:
Continuation token - CreateDocumentQuery ExecuteNextAsync function not exist
I develop in c# in azure documentDB platform .
I try to implement paging architecture in my application .
My code :

```<code>var userQuery = _client.CreateDocumentQuery<User>(
                _uriUsersCollection, queryStr, options).AsDocumentQuery();
</code>```

my code show error on the  AsDocumentQuery() function (it's not recognize as part of the IQueryable methods (I see several example in the internet that the function is recognize ).So when I try to activate the query.ExecuteNextAsync it is not exist.
I work with Microsoft.Azure.Documents.Client dll version 1.11.0.0.
Thanks for your help
MAK

答:
Please include Microsoft.Azure.Documents.Linq namespace in your code as AsDocumentQuery is an extension method defined there.

```<code>using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;//Add this line
</code>```

Body:
I develop in c# in azure documentDB platform .
I try to implement paging architecture in my application .
My code :

var userQuery = _client.CreateDocumentQuery<User>(
                _uriUsersCollection, queryStr, options).AsDocumentQuery();

my code show error on the  AsDocumentQuery() function (it's not recognize as part of the IQueryable methods (I see several example in the internet that the function is recognize ).So when I try to activate the query.ExecuteNextAsync it is not exist.
I work with Microsoft.Azure.Documents.Client dll version 1.11.0.0.
Thanks for your help
MAK

Body:
Please include Microsoft.Azure.Documents.Linq namespace in your code as AsDocumentQuery is an extension method defined there.

using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;//Add this line


问:
Alert dialogue title and message are not shown
i created alert dialogue but title and message are not shown here is my code for alert dialogue

```<code>holder.add.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);
            } else {
                builder = new AlertDialog.Builder(context);
            }
            builder.setTitle("Alert");
            builder.setMessage("Are you sure")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // User cancelled the dialog
                        }
                    });
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    });
</code>```

this is the screenshot of it

答:
You have to pass theme as well in AlertBuilder.

```<code>AlertDialog.Builder myAlert = new AlertDialog.Builder(getContext(), R.style.AppCompatAlertDialogStyle);
deleteAlert.setTitle(title);
deleteAlert.setMessage(message);
deleteAlert.setPositiveButton(android.R.string.ok, clickListener);
deleteAlert.setNegativeButton(android.R.string.cancel, clickListener);
deleteAlert.show();
</code>```

No need to call the create() method if you have called show(). Because internally the show() method calls create().

Note:
I can clearly say the issue from my experience. I missed to pass theme.

```<code>R.style.AppCompatAlertDialogStyle
</code>```

DOES NOT WORK:

```<code>AlertDialog.Builder myAlert = new AlertDialog.Builder(getContext());
</code>```

WORKS SUCCESFULLY:

```<code>AlertDialog.Builder myAlert = new AlertDialog.Builder(getContext(),  R.style.AppCompatAlertDialogStyle);
</code>```

Body:
i created alert dialogue but title and message are not shown here is my code for alert dialogue

holder.add.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);
            } else {
                builder = new AlertDialog.Builder(context);
            }
            builder.setTitle("Alert");
            builder.setMessage("Are you sure")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // User cancelled the dialog
                        }
                    });
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    });

this is the screenshot of it

Body:
You have to pass theme as well in AlertBuilder.

AlertDialog.Builder myAlert = new AlertDialog.Builder(getContext(), R.style.AppCompatAlertDialogStyle);
deleteAlert.setTitle(title);
deleteAlert.setMessage(message);
deleteAlert.setPositiveButton(android.R.string.ok, clickListener);
deleteAlert.setNegativeButton(android.R.string.cancel, clickListener);
deleteAlert.show();

No need to call the create() method if you have called show(). Because internally the show() method calls create().

Note:
I can clearly say the issue from my experience. I missed to pass theme.

R.style.AppCompatAlertDialogStyle

DOES NOT WORK:

AlertDialog.Builder myAlert = new AlertDialog.Builder(getContext());

WORKS SUCCESFULLY:

AlertDialog.Builder myAlert = new AlertDialog.Builder(getContext(),  R.style.AppCompatAlertDialogStyle);


问:
android app is not working in samsung device
when i'm trying to run my android app on Samsung device its always showing an error like:

app has been unfortunately stopped

and also showing xml inflating error and drawable resources not found even i renamed existing apk and installed again either installed support library in android studio but error remain same.
but in redmi 3s device its working fine. what should i do please suggest something.
this is my error in console:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
              android.content.res.Resources$NotFoundException: Resource ID #0x7f020157
                  at android.content.res.Resources.getValue(Resources.java:1884)
                  at android.support.v7.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:330)
                  at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:195)
                  at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:188)
                  at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100)
                  at android.support.v7.view.menu.MenuItemImpl.getIcon(MenuItemImpl.java:425)
                  at android.support.v7.view.menu.ActionMenuItemView.initialize(ActionMenuItemView.java:132)
                  at android.support.v7.widget.ActionMenuPresenter.bindItemView(ActionMenuPresenter.java:211)
                  at android.support.v7.view.menu.BaseMenuPresenter.getItemView(BaseMenuPresenter.java:186)
                  at android.support.v7.widget.ActionMenuPresenter.getItemView(ActionMenuPresenter.java:197)
                  at android.support.v7.widget.ActionMenuPresenter.flagActionItems(ActionMenuPresenter.java:479)
                  at android.support.v7.view.menu.MenuBuilder.flagActionItems(MenuBuilder.java:1151)
                  at android.support.v7.view.menu.BaseMenuPresenter.updateMenuView(BaseMenuPresenter.java:95)
                  at android.support.v7.widget.ActionMenuPresenter.updateMenuView(ActionMenuPresenter.java:234)
                  at android.support.v7.view.menu.MenuBuilder.dispatchPresenterUpdate(MenuBuilder.java:290)
                  at android.support.v7.view.menu.MenuBuilder.onItemsChanged(MenuBuilder.java:1042)
                  at android.support.v7.view.menu.MenuBuilder.startDispatchingItemsChanged(MenuBuilder.java:1065)
                  at android.support.v7.app.ToolbarActionBar.populateOptionsMenu(ToolbarActionBar.java:460)
                  at android.support.v7.app.ToolbarActionBar$1.run(ToolbarActionBar.java:61)
                  at android.os.Handler.handleCallback(Handler.java:615)
                  at android.os.Handler.dispatchMessage(Handler.java:92)
                  at android.os.Looper.loop(Looper.java:177)
                  at android.app.ActivityThread.main(ActivityThread.java:4947)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:511)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                  at dalvik.system.NativeStart.main(Native Method)
</code>```

D/dalvikvm: GC_CONCURRENT freed 965K, 13% free 14229K/16199K, paused 21ms+32ms, total 123ms
D/dalvikvm: GC_CONCURRENT freed 993K, 12% free 14774K/16775K, paused 12ms+3ms, total 37ms
D/dalvikvm: GC_CONCURRENT freed 1591K, 15% free 14909K/17479K, paused 12ms+14ms, total 145ms
Application terminated.

draweritemmenu.xml this is my menu file.

```<code><menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
    <item
        android:id="@+id/home"
        android:icon="@drawable/home"
        android:title="Home" />
    <item
        android:id="@+id/signin"
        android:icon="@drawable/login"
        android:title="Sign In" />
    <item android:title="Categories">
        <menu>
            <group android:checkableBehavior="single">
                <item
                    android:id="@+id/fruit"
                    android:icon="@drawable/fruit"
                    android:title="Fruits" />
                <item
                    android:id="@+id/food"
                    android:icon="@drawable/thali"
                    android:title="Food" />
            </group>
        </menu>
    </item>
</group>
<item android:title="Best Deals">
    <menu>
        <group android:checkableBehavior="single">
            <item
                android:id="@+id/fruitoffer"
                android:icon="@drawable/fruitoffer"
                android:title="Offer On Fruits" />
            <item
                android:id="@+id/foodoffer"
                android:icon="@drawable/offer"
                android:title="Offer On Food" />
        </group>
    </menu>
</item>
<item android:title="Communicate">
    <menu>
        <item
            android:id="@+id/aboutus"
         android:icon="@drawable/aboutus"
            android:title="About us" />
        <item
            android:id="@+id/contactus"
            android:icon="@drawable/contactus"
            android:title="Contact us" />
        <item
            android:id="@+id/faq"
            android:icon="@drawable/faq"
            android:title="FAQ" />
    </menu>
</item>
</code>```

//this is my action menu xml file

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/action_search1"
    android:title="Filter By Food Name" />
<item android:id="@+id/action_search2"
    android:title="Filter By Fruit Name"
    android:icon="@drawable/foodbyname" />
<item android:id="@+id/action_search3"
    android:title="Filter By Food Price" />
<item android:id="@+id/action_search4"
    android:title="Filter By Fruit Price" />
</code>```

答:
It seems that one (or more) of your drawable (android:icon="@drawable/xxx") not found.
In my case, I put the picture into drawable-v21(folder) mistakenly (my devices' API=19). When I move it into drawable(folder), it's ok.</p>

Body:
when i'm trying to run my android app on Samsung device its always showing an error like:

app has been unfortunately stopped

and also showing xml inflating error and drawable resources not found even i renamed existing apk and installed again either installed support library in android studio but error remain same.
but in redmi 3s device its working fine. what should i do please suggest something.
this is my error in console:

E/AndroidRuntime: FATAL EXCEPTION: main
              android.content.res.Resources$NotFoundException: Resource ID #0x7f020157
                  at android.content.res.Resources.getValue(Resources.java:1884)
                  at android.support.v7.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:330)
                  at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:195)
                  at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:188)
                  at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100)
                  at android.support.v7.view.menu.MenuItemImpl.getIcon(MenuItemImpl.java:425)
                  at android.support.v7.view.menu.ActionMenuItemView.initialize(ActionMenuItemView.java:132)
                  at android.support.v7.widget.ActionMenuPresenter.bindItemView(ActionMenuPresenter.java:211)
                  at android.support.v7.view.menu.BaseMenuPresenter.getItemView(BaseMenuPresenter.java:186)
                  at android.support.v7.widget.ActionMenuPresenter.getItemView(ActionMenuPresenter.java:197)
                  at android.support.v7.widget.ActionMenuPresenter.flagActionItems(ActionMenuPresenter.java:479)
                  at android.support.v7.view.menu.MenuBuilder.flagActionItems(MenuBuilder.java:1151)
                  at android.support.v7.view.menu.BaseMenuPresenter.updateMenuView(BaseMenuPresenter.java:95)
                  at android.support.v7.widget.ActionMenuPresenter.updateMenuView(ActionMenuPresenter.java:234)
                  at android.support.v7.view.menu.MenuBuilder.dispatchPresenterUpdate(MenuBuilder.java:290)
                  at android.support.v7.view.menu.MenuBuilder.onItemsChanged(MenuBuilder.java:1042)
                  at android.support.v7.view.menu.MenuBuilder.startDispatchingItemsChanged(MenuBuilder.java:1065)
                  at android.support.v7.app.ToolbarActionBar.populateOptionsMenu(ToolbarActionBar.java:460)
                  at android.support.v7.app.ToolbarActionBar$1.run(ToolbarActionBar.java:61)
                  at android.os.Handler.handleCallback(Handler.java:615)
                  at android.os.Handler.dispatchMessage(Handler.java:92)
                  at android.os.Looper.loop(Looper.java:177)
                  at android.app.ActivityThread.main(ActivityThread.java:4947)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:511)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                  at dalvik.system.NativeStart.main(Native Method)

D/dalvikvm: GC_CONCURRENT freed 965K, 13% free 14229K/16199K, paused 21ms+32ms, total 123ms
D/dalvikvm: GC_CONCURRENT freed 993K, 12% free 14774K/16775K, paused 12ms+3ms, total 37ms
D/dalvikvm: GC_CONCURRENT freed 1591K, 15% free 14909K/17479K, paused 12ms+14ms, total 145ms
Application terminated.

draweritemmenu.xml this is my menu file.

<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
    <item
        android:id="@+id/home"
        android:icon="@drawable/home"
        android:title="Home" />
    <item
        android:id="@+id/signin"
        android:icon="@drawable/login"
        android:title="Sign In" />
    <item android:title="Categories">
        <menu>
            <group android:checkableBehavior="single">
                <item
                    android:id="@+id/fruit"
                    android:icon="@drawable/fruit"
                    android:title="Fruits" />
                <item
                    android:id="@+id/food"
                    android:icon="@drawable/thali"
                    android:title="Food" />
            </group>
        </menu>
    </item>
</group>
<item android:title="Best Deals">
    <menu>
        <group android:checkableBehavior="single">
            <item
                android:id="@+id/fruitoffer"
                android:icon="@drawable/fruitoffer"
                android:title="Offer On Fruits" />
            <item
                android:id="@+id/foodoffer"
                android:icon="@drawable/offer"
                android:title="Offer On Food" />
        </group>
    </menu>
</item>
<item android:title="Communicate">
    <menu>
        <item
            android:id="@+id/aboutus"
         android:icon="@drawable/aboutus"
            android:title="About us" />
        <item
            android:id="@+id/contactus"
            android:icon="@drawable/contactus"
            android:title="Contact us" />
        <item
            android:id="@+id/faq"
            android:icon="@drawable/faq"
            android:title="FAQ" />
    </menu>
</item>

//this is my action menu xml file

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/action_search1"
    android:title="Filter By Food Name" />
<item android:id="@+id/action_search2"
    android:title="Filter By Fruit Name"
    android:icon="@drawable/foodbyname" />
<item android:id="@+id/action_search3"
    android:title="Filter By Food Price" />
<item android:id="@+id/action_search4"
    android:title="Filter By Fruit Price" />


问:
Is it possible to combine this javascript function into JQuery?
I have a function written in javascript and I'd like to know how, if it's possible, to use it in my JQuery file. I'm using the following function and my selector id is '#comments'.

Again, all I want to do is just consolidate this function which now resides in another file, into my main JQuery file. Is this possible?

```<code>onkeydown="textCounter(this.form.notes, this.form.remLen,240); "onkeyup="textCounter(this.form.notes, this.form.remLen, 240);"
</code>```

The selector id is #comments.

```<code>function textCounter( field, countfield, maxlimit ){
if ( field.value.length > maxlimit )    {
    field.value = field.value.substring( 0, maxlimit );
}else{
    countfield.value = maxlimit - field.value.length;
}
</code>```

答:
yes inside the function textCounnter, add the function of the Jquery, triggering a function w/ in a function? but why do tou want the textCounter in javascript anyway?

why not do this

$(#comments){
 ..textcounter ideas inside
}

Body:
I have a function written in javascript and I'd like to know how, if it's possible, to use it in my JQuery file. I'm using the following function and my selector id is '#comments'.

Again, all I want to do is just consolidate this function which now resides in another file, into my main JQuery file. Is this possible?

onkeydown="textCounter(this.form.notes, this.form.remLen,240); "onkeyup="textCounter(this.form.notes, this.form.remLen, 240);"

The selector id is #comments.

function textCounter( field, countfield, maxlimit ){
if ( field.value.length > maxlimit )    {
    field.value = field.value.substring( 0, maxlimit );
}else{
    countfield.value = maxlimit - field.value.length;
}


问:
DAX code to count number of orders with n total units
I've got a list of order lines (first table of the screenshot attached). I'd like to know how many orders have 1 unit, how many 2 units, etc.

I usually do this with 2 pivot tables (as shown in the screenshot attached). The problem is that I have to create an intermediate table and if I have more than 1million orders I couldn't have this approach due to excel's number of rows limit.

I've tried using CALCULATE in several ways, but I can't find the correct way to do it...

Here is the screenshot:

Thanks in advance!

Jorge

EDIT: I use MS Excel 2017, not Power BI

答:
This solution involves using the SUMMARIZECOLUMNS function, which seems to be only available in Power BI, Analysis Services 2016, or Excel 2016.

SUMMARIZECOLUMNS is a much more efficient way to build summary table.

The two summary tables are rebuilt using the expression as follows in Power BI:

```<code>Order Summary =
SUMMARIZECOLUMNS(
    Orders[OrderNo],
    "Sum of Units", SUM(Orders[Units])
)
</code>```

-

```<code>Unit Summary =
SUMMARIZECOLUMNS(
    'Order Summary'[Sum of Units],
    "Number of Orders", COUNTROWS('Order Summary')
)
</code>```

The result will be as expected:

Body:
This solution involves using the SUMMARIZECOLUMNS function, which seems to be only available in Power BI, Analysis Services 2016, or Excel 2016.

SUMMARIZECOLUMNS is a much more efficient way to build summary table.

The two summary tables are rebuilt using the expression as follows in Power BI:

Order Summary =
SUMMARIZECOLUMNS(
    Orders[OrderNo],
    "Sum of Units", SUM(Orders[Units])
)

-

Unit Summary =
SUMMARIZECOLUMNS(
    'Order Summary'[Sum of Units],
    "Number of Orders", COUNTROWS('Order Summary')
)

The result will be as expected:


答:
The difference between select * except nested column and your question, is due to the fact that hits is an ARRAY. Here is how you can exclude columns from array of structs:

```<code>SELECT * REPLACE
 (ARRAY(SELECT AS STRUCT * EXCEPT(page) FROM UNNEST(hits) h) AS hits)
FROM `google.com:analytics-bigquery.LondonCycleHelmet.ga_sessions_20130910`
</code>```

Title: BigQuery except double nested column

Body:
Hi need to exclude the column hits.latencyTracking.userTimingLabel from my table and select all the other columns. How can I do this in Standard Sql?
I found already a question on a similar problem (BigQuery select * except nested column) but in my case I have a double nested column and I am not able do adapt the code.
thanks

Body:
The difference between select * except nested column and your question, is due to the fact that hits is an ARRAY. Here is how you can exclude columns from array of structs:

SELECT * REPLACE
 (ARRAY(SELECT AS STRUCT * EXCEPT(page) FROM UNNEST(hits) h) AS hits)
FROM `google.com:analytics-bigquery.LondonCycleHelmet.ga_sessions_20130910`


问:
Regex help: how can I match all characters but leave one white space in between strings?
I want to be able to match each row as one group capturing all characters while leaving one space separating the words/strings.

This is what I have so far, I can't seem to get past the 2nd column -

https://regex101.com/r/IXMVci/3

答:
You cannot capture a whole string, exclude some characters in between, and continue the match with the following characters in the same group. What you can do, is match the parts individually:

```<code>([0-9]+|[A-Za-z0-9]+(?:[ -_][A-Za-z]+)+|[A-Za-z0-9]+|-)
</code>```

This should select every column in your sample data. By using a sub-group I made sure a white space will not be matched in the end of a column.

However, after some columns are separated by only 1 white space, I limited a part of the column after a potential whitespace to only characters (no numbers).

To separate the first column (which only is followed by 1 regex), I added the first alternative

Body:
You cannot capture a whole string, exclude some characters in between, and continue the match with the following characters in the same group. What you can do, is match the parts individually:

([0-9]+|[A-Za-z0-9]+(?:[ -_][A-Za-z]+)+|[A-Za-z0-9]+|-)

This should select every column in your sample data. By using a sub-group I made sure a white space will not be matched in the end of a column.

However, after some columns are separated by only 1 white space, I limited a part of the column after a potential whitespace to only characters (no numbers).

To separate the first column (which only is followed by 1 regex), I added the first alternative


问:
Debugging non-responsive python/PyQt application in PyCharm
How do you go about debugging a non-responsive python/PyQt application in PyCharm?

I am an experienced programmer, but new to all thing python.  I have been given a large application (36,000 lines), which works under Windows, to port to Linux.

Having made just a handful of changes for OS-specific stuff, when I run the application it comes up with its main window.  But then after a few seconds it becomes dimmed, and when I close the window I am asked to confirm to end "the window is not responding".

(Aside: On a whim I decided to try running the app via sudo, and surprisingly it works fine.  I have tried doing strace running as root versus non-root, but I'm fairly sure there is nothing obvious in the way of file accesses/permissions etc. that differs.  This may be a clue, but just as likely to be a red-herring, e.g. if it's an "uninitialized variable".)

If I debug it inside PyCharm, at that point I expect to click the "Pause Program" button, so that I can get a trace back and begin to see where it is in the code, and start stepping or whatever.  However, that button does nothing at this stage?  Maybe it only "works" when on "a python instruction"?

If I force a core dump (from the keyboard) and examine with gdb, I can see that the stack frame shows it is way down inside libQtCore/libQtGui, in processEvents on a call to read.

So how do I begin to go about debugging why it is (presumably) busy doing something at this point, or at least not responding?  Any tips would be welcome.  I do hope this question will not fall foul of SO's "too general" policy, any tips to get someone going on debugging a "non-responsive" program would be welcome.

答:
To answer my own question, since no responses seem to be forthcoming.

In this case, the problem turned out to lie in a file which is imported into other files, named pyperclip.py.  That had code outside of any function, and in a path through the source executed under Linux but I think not under Windows, which included:

```<code>app = PyQt4.QtGui.QApplication([])
cb = PyQt4.QtGui.QApplication.clipboard()
</code>```

Clearly some attempt to gain a clipboard object.  For whatever reason, this appears to work when run as su, but when run as the logged on user it causes the whole application to "hang".  Removing those two lines solved the unresponsiveness.

In terms of what I learnt from this for debugging unresponsive applications: you need to debug not from the entry point of the program, as I would have expected, but rather right from the start of each file, and actually step into each import line just in case it is executing some initial code.  Horrible!

Body:
To answer my own question, since no responses seem to be forthcoming.

In this case, the problem turned out to lie in a file which is imported into other files, named pyperclip.py.  That had code outside of any function, and in a path through the source executed under Linux but I think not under Windows, which included:

app = PyQt4.QtGui.QApplication([])
cb = PyQt4.QtGui.QApplication.clipboard()

Clearly some attempt to gain a clipboard object.  For whatever reason, this appears to work when run as su, but when run as the logged on user it causes the whole application to "hang".  Removing those two lines solved the unresponsiveness.

In terms of what I learnt from this for debugging unresponsive applications: you need to debug not from the entry point of the program, as I would have expected, but rather right from the start of each file, and actually step into each import line just in case it is executing some initial code.  Horrible!


问:
Why it compiles whether or not "extern" is used?
In a.cpp:

```<code>int t()
{
  //definition goes here
  ...
}
</code>```

b.cpp:

```<code>#include "a.h"

int main()
{
  t();
}
</code>```

finally a.h:

```<code>extern int t();
//int t();
</code>```

Both forms of a.h works,why?

答: Because function are extern by default, so the extern keyword is redundant. Some people like to explicitly add the extern when they want to hint other developers that the definition of the function are not to be found in the .cpp file with same name than this .h file, then they add a comment to point where the function is declared. But to the compiler's perspective, it does not affect anything.

Body:
In a.cpp:

int t()
{
  //definition goes here
  ...
}

b.cpp:

#include "a.h"

int main()
{
  t();
}

finally a.h:

extern int t();
//int t();

Both forms of a.h works,why?


问:
Create a variable to hold objects of different types C++
I have 3 different objects A, B and C. Depending on the the parameter given, I would like to choose among these different objects. In programming,

```<code>class A {
  public:
    void printHello() { cout << "HELLO A" << endl; }
};

class B {
  public:
    void printHello() { cout << "HELLO B" << endl; }
};

class C {
   public:
     void printHello() { cout << "HELLO C" << endl; }
};

int main () {
    string key = "c";
    A a;
    B b;
    C c;
    Object obj; // I don't know how to declare Object.

    if (key == "a") obj = a;
    else if (key == "b") obj = b;
    else obj = c;
    obj.printHello(); // print Hello C.
    return 0;
}
</code>```

I have thought about templates and struct objects. But none of them work so far.

```<code>template<typename T1, T2, T3>
T1 getType(string key, T1 t1, T2 t2, T3 t3) { // this is problem coz return types are different.
    if (key == "a") return t1;
    else if (key == "b") return t2;
    else return t3;
}
</code>```

It is easy to create Object o; in JAVA because every object in Java is subclass of Object class. But how do I achieve this in C++?

Edit.
I can't change class A, B and C. I was given these classes to work with and my goal is to implement main method. So, inheritance was out of the question for me. Sorry for any confusion.

Any help is appreciated.

答:
you could do something like </p>

```<code>if (key == "a") obj=new A();
else if (key == "b")  obj=new B();
</code>```

Body:
I have 3 different objects A, B and C. Depending on the the parameter given, I would like to choose among these different objects. In programming,

class A {
  public:
    void printHello() { cout << "HELLO A" << endl; }
};

class B {
  public:
    void printHello() { cout << "HELLO B" << endl; }
};

class C {
   public:
     void printHello() { cout << "HELLO C" << endl; }
};

int main () {
    string key = "c";
    A a;
    B b;
    C c;
    Object obj; // I don't know how to declare Object.

    if (key == "a") obj = a;
    else if (key == "b") obj = b;
    else obj = c;
    obj.printHello(); // print Hello C.
    return 0;
}

I have thought about templates and struct objects. But none of them work so far.

template<typename T1, T2, T3>
T1 getType(string key, T1 t1, T2 t2, T3 t3) { // this is problem coz return types are different.
    if (key == "a") return t1;
    else if (key == "b") return t2;
    else return t3;
}

It is easy to create Object o; in JAVA because every object in Java is subclass of Object class. But how do I achieve this in C++?

Edit.
I can't change class A, B and C. I was given these classes to work with and my goal is to implement main method. So, inheritance was out of the question for me. Sorry for any confusion.

Any help is appreciated.

Body:
you could do something like

if (key == "a") obj=new A();
else if (key == "b")  obj=new B();


问:
How to turn redux-thunk action creator into Promise?
I have the following async action creator (using redux-thunk):

```<code>export const nextPupil = () => {
    return (dispatch, getState) => {
    const {activeSentence, sentencesList} = getState();
    //... some more code
    const nextActive = pupilList[nextIndex];

    dispatch({ type: "UPDATE_ACTIVE", payload: nextActive });
  }
};
</code>```

However, I need this action to return a promise, since I need to wait for its completion in one of my components, before doing something else (see this question for a more detailed description of my problem)

How could I turn this action into a promise and still use redux-thunk? Thanks a lot in advance.

edit:

I am aware that I am trying to save the state of the input field locally in my component, i.e., not in Redux. This because if I were to bind the value of the input field directly to the redux store, it would not be editable anymore. However, I want the user to be able to edit the input field and then, on submit, save the edited value in my redux store. If I bind things directly, the user won't be able to change values / edit.

答:
I think you are misunderstanding the data flows through redux.  I assume when you want to turn the action into a promise, you would want that promise to resolve when the redux state has been updated - this appears to be the case from your other question.  This is not generally how redux is designed to work.

When you dispatch an action, the store will be updated, and then the props in your components that come from the store will update.  All you need to do is use those props in your components, and whenever the props update, so will your component.

In your initial question your code was:

```<code>onSubmit(e) {
  e.preventDefault();
  this.props.nextSentence(); //this is async

  this.setState({ //this is not yet updating with the right values then
      inputField: this.props.activePupil.name
  });
}
</code>```

The issue you have is that activePupil is part of your redux store, yet you are trying to store it within the state of your component as well.  This is a bad idea because you no longer have a single source of truth for your state.

The better approach is to just use this.props.activePupil wherever it is needed, e.g.

```<code> render() {
     return (
        <span>{this.props.activePupil.name}</span>
     );
 }
</code>```

Now when you dispatch the action, as soon store is updated, your component will also update.  If you need to then you can add a loading property to your store, so that you can indicate to the user that something is happening, and dispatch this from your thunk before doing any async work, and then revert loading when UPDATE_ACTIVE is dispatched.

```<code>export const nextPupil = () => {
    return (dispatch, getState) => {
      dispatch({ type: "PUPIL_UPDATING });
      const {activeSentence, sentencesList} = getState();
      //... some more code
      const nextActive = pupilList[nextIndex];

      dispatch({ type: "UPDATE_ACTIVE", payload: nextActive });
  }
};
</code>```

Edit 1

It's taken a bit of thinking about the right approach to your issue below, but I think I have settled on a reasonable way to achieve it, while maintaining data integrity.  It does involve keeping form input in your store, which not everyone is a fan of, but is not a problem for me.

Anyway... we need another reducer for handling user input - it will be very simple and respond to two actions - the "UPDATE_ACTIVE" action you already have, and an "NAME_UPDATED" action:

```<code>const updatedName = (state = '', action) => {
  switch (action.type) {
    case 'UPDATE_ACTIVE':
        return action.payload.name;
    case: 'NAME_UPDATED':
        return action.payload.updatedName;
    default:
        return state;
  }
};
</code>```

Then we will need a simple action creator:

```<code>const inputChanged = updatedName => ({
     type: 'NAME_UPDATED',
     payload: { updatedName }
});
</code>```

Now within our component we will use the newly created state and action creator to manage our input (just connect them in as per usual) - lots of code missing here but there should be enough to get the idea.

```<code>class Whatever extends React.Component {
    constructor() {
        super();
        this.handleChange= this.handleChange.bind(this);
    }

    handleChange(event) {
        this.props.inputChanged(event.target.value);
    }

    render() {
        return (
            <input type="text" value={this.props.updatedName} onChange={this.handleChange} />
        );
    }
}
</code>```

I hope that makes sense!

Edit 2:

If you want to store the input on component state rather than within the redux store, then I think this approach should work.  It uses the componentWillReceiveProps lifecycle hook - to set the component state i.e. the input value when the activePupil prop changes.  This is called every time the props update, but may also be called when there aren't any prop changes, so we need some logic to decide whether to update the updatedPupilName prop.  To achieve this we are comparing our current props.activePupil.name to the nextProps.activePupil.name and only updating the state if they are different.  If you have an ID type property on your pupils this would probably be better suited for the comparison.

```<code>class Whatever extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            updatedPupilName: props.activePupil.name
        };
        this.handleChange= this.handleChange.bind(this);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.activePupil.name !== this.props.activePupil.name) {
            this.setState({
                updatedPupilName: nextProps.activePupil.name
            });
        }
    }

    handleChange(event) {
        this.setState({
            updatedPupilName: event.target.value
        });
    }

    render() {
        return (
            <input type="text" value={this.state.updatedPupilName} onChange={this.handleChange} />
        );
    }
}
</code>```

Body:
I have the following async action creator (using redux-thunk):

export const nextPupil = () => {
    return (dispatch, getState) => {
    const {activeSentence, sentencesList} = getState();
    //... some more code
    const nextActive = pupilList[nextIndex];

    dispatch({ type: "UPDATE_ACTIVE", payload: nextActive });
  }
};

However, I need this action to return a promise, since I need to wait for its completion in one of my components, before doing something else (see this question for a more detailed description of my problem)

How could I turn this action into a promise and still use redux-thunk? Thanks a lot in advance.

edit:

I am aware that I am trying to save the state of the input field locally in my component, i.e., not in Redux. This because if I were to bind the value of the input field directly to the redux store, it would not be editable anymore. However, I want the user to be able to edit the input field and then, on submit, save the edited value in my redux store. If I bind things directly, the user won't be able to change values / edit.

Body:
I think you are misunderstanding the data flows through redux.  I assume when you want to turn the action into a promise, you would want that promise to resolve when the redux state has been updated - this appears to be the case from your other question.  This is not generally how redux is designed to work.

When you dispatch an action, the store will be updated, and then the props in your components that come from the store will update.  All you need to do is use those props in your components, and whenever the props update, so will your component.

In your initial question your code was:

onSubmit(e) {
  e.preventDefault();
  this.props.nextSentence(); //this is async

  this.setState({ //this is not yet updating with the right values then
      inputField: this.props.activePupil.name
  });
}

The issue you have is that activePupil is part of your redux store, yet you are trying to store it within the state of your component as well.  This is a bad idea because you no longer have a single source of truth for your state.

The better approach is to just use this.props.activePupil wherever it is needed, e.g.

 render() {
     return (
        <span>{this.props.activePupil.name}</span>
     );
 }

Now when you dispatch the action, as soon store is updated, your component will also update.  If you need to then you can add a loading property to your store, so that you can indicate to the user that something is happening, and dispatch this from your thunk before doing any async work, and then revert loading when UPDATE_ACTIVE is dispatched.

export const nextPupil = () => {
    return (dispatch, getState) => {
      dispatch({ type: "PUPIL_UPDATING });
      const {activeSentence, sentencesList} = getState();
      //... some more code
      const nextActive = pupilList[nextIndex];

      dispatch({ type: "UPDATE_ACTIVE", payload: nextActive });
  }
};

Edit 1

It's taken a bit of thinking about the right approach to your issue below, but I think I have settled on a reasonable way to achieve it, while maintaining data integrity.  It does involve keeping form input in your store, which not everyone is a fan of, but is not a problem for me.

Anyway... we need another reducer for handling user input - it will be very simple and respond to two actions - the "UPDATE_ACTIVE" action you already have, and an "NAME_UPDATED" action:

const updatedName = (state = '', action) => {
  switch (action.type) {
    case 'UPDATE_ACTIVE':
        return action.payload.name;
    case: 'NAME_UPDATED':
        return action.payload.updatedName;
    default:
        return state;
  }
};

Then we will need a simple action creator:

const inputChanged = updatedName => ({
     type: 'NAME_UPDATED',
     payload: { updatedName }
});

Now within our component we will use the newly created state and action creator to manage our input (just connect them in as per usual) - lots of code missing here but there should be enough to get the idea.

class Whatever extends React.Component {
    constructor() {
        super();
        this.handleChange= this.handleChange.bind(this);
    }

    handleChange(event) {
        this.props.inputChanged(event.target.value);
    }

    render() {
        return (
            <input type="text" value={this.props.updatedName} onChange={this.handleChange} />
        );
    }
}

I hope that makes sense!

Edit 2:

If you want to store the input on component state rather than within the redux store, then I think this approach should work.  It uses the componentWillReceiveProps lifecycle hook - to set the component state i.e. the input value when the activePupil prop changes.  This is called every time the props update, but may also be called when there aren't any prop changes, so we need some logic to decide whether to update the updatedPupilName prop.  To achieve this we are comparing our current props.activePupil.name to the nextProps.activePupil.name and only updating the state if they are different.  If you have an ID type property on your pupils this would probably be better suited for the comparison.

class Whatever extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            updatedPupilName: props.activePupil.name
        };
        this.handleChange= this.handleChange.bind(this);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.activePupil.name !== this.props.activePupil.name) {
            this.setState({
                updatedPupilName: nextProps.activePupil.name
            });
        }
    }

    handleChange(event) {
        this.setState({
            updatedPupilName: event.target.value
        });
    }

    render() {
        return (
            <input type="text" value={this.state.updatedPupilName} onChange={this.handleChange} />
        );
    }
}


问:
Embedding Python with C++
Problem: Strange exception is thrown when embedding Python with C++.

Program:

```<code>bool embedd::execute_python(std::string location)
{
    if (std::ifstream(location))
    {
            const char* file_location = location.c_str();
            FILE* file_pointer;
            // Initialize the Python interpreter
            Py_Initialize();
            file_pointer = _Py_fopen(file_location, "r");
            // Run the Python file
            PyRun_SimpleFile(file_pointer, file_location);
            // Finalize the Python interpreter
            Py_Finalize();
        return true;
    }
    return false;
}
</code>```

What does the above code snippet should do:  The function should first check whether the passed argument is a valid location of the python file. If the file is present then it should execute the Python file.

Am I getting expected results:  yes and no.

what is going wrong:

Test file 1:

```<code>print("Hello world")
</code>```

Result : Successful execution and getting proper output

Test file 2:

```<code>from tkinter import *
root = Tk()
root.mainloop()
</code>```

Result : Exception  root = Tk() File
  "C:\Users\User\AppData\Local\Programs\Python\Python35-32\Lib\tkinter__init__.py",
  line 1863, in init baseName = os.path.basename(sys.argv[0])
  AttributeError: module 'sys' has no attribute 'argv'

Tested with some other file and found that when-ever we import modules(any) like tkinter, uuid, os etc similar exception gets thrown. on digging briefly about this the process monitor of my IDE told "Symbol file is not loaded" e.g no symbol file loaded for tk86t.dll

Python Version : 3.5.2

Links which I do have referred:
SO - 1 found the bug has been fixed from Python 2.3 here BUGS

答:
On the one hand your test file 2 imports Tk which expects a valid command line (like e.g. for windows C:\>python script.py -yourarguments) for some reasons. On the other hand you embed python and thus don't have a command line. That's what python complains ("module 'sys' has no attribute 'argv'"). You should create a fake command line directly after Py_Initialize() with something like:

```<code>Py_Initialize();
wchar_t const *dummy_args[] = {L"Python", NULL};  // const is needed because literals must not be modified
wchar_t const **argv = dummy_args;
int             argc = sizeof(dummy_args)/sizeof(dummy_args[0])-1;
PySys_SetArgv(argc, const_cast<wchar_t **>(argv)); // const_cast allowed, because PySys_SetArgv doesn't change argv
</code>```

Your test file 1 doesn't import Tk and thus doesn't expect a valid command line. That's the reason why it works without the code above.

Title: Embedding Python with C++

Body:
Problem: Strange exception is thrown when embedding Python with C++.

Program:

bool embedd::execute_python(std::string location)
{
    if (std::ifstream(location))
    {
            const char* file_location = location.c_str();
            FILE* file_pointer;
            // Initialize the Python interpreter
            Py_Initialize();
            file_pointer = _Py_fopen(file_location, "r");
            // Run the Python file
            PyRun_SimpleFile(file_pointer, file_location);
            // Finalize the Python interpreter
            Py_Finalize();
        return true;
    }
    return false;
}

What does the above code snippet should do:  The function should first check whether the passed argument is a valid location of the python file. If the file is present then it should execute the Python file.

Am I getting expected results:  yes and no.

what is going wrong:

Test file 1:

print("Hello world")

Result : Successful execution and getting proper output

Test file 2:

from tkinter import *
root = Tk()
root.mainloop()

Result : Exception  root = Tk() File
  "C:\Users\User\AppData\Local\Programs\Python\Python35-32\Lib\tkinter__init__.py",
  line 1863, in init baseName = os.path.basename(sys.argv[0])
  AttributeError: module 'sys' has no attribute 'argv'

Tested with some other file and found that when-ever we import modules(any) like tkinter, uuid, os etc similar exception gets thrown. on digging briefly about this the process monitor of my IDE told "Symbol file is not loaded" e.g no symbol file loaded for tk86t.dll

Python Version : 3.5.2

Links which I do have referred:
SO - 1 found the bug has been fixed from Python 2.3 here BUGS

Body:
On the one hand your test file 2 imports Tk which expects a valid command line (like e.g. for windows C:\>python script.py -yourarguments) for some reasons. On the other hand you embed python and thus don't have a command line. That's what python complains ("module 'sys' has no attribute 'argv'"). You should create a fake command line directly after Py_Initialize() with something like:

Py_Initialize();
wchar_t const *dummy_args[] = {L"Python", NULL};  // const is needed because literals must not be modified
wchar_t const **argv = dummy_args;
int             argc = sizeof(dummy_args)/sizeof(dummy_args[0])-1;
PySys_SetArgv(argc, const_cast<wchar_t **>(argv)); // const_cast allowed, because PySys_SetArgv doesn't change argv

Your test file 1 doesn't import Tk and thus doesn't expect a valid command line. That's the reason why it works without the code above.