text:
Q: "codec missing or unavailable" error when importing media file in Adobe Premiere CC When I try to import any video file (e.g. AVI files) in Adobe Premiere Pro cc in my Macbook Air, I get this error:
"codec missing or unavailable"
What to do about it?

A: AVI is just a container for a video format, and can contain videos encoded in different formats. The error you're seeing says that Adobe Premiere does not know how to process the video format that's within the AVI file.

*

*First, you would have to find out (or know) the codec used for the video within the AVI file and then download and install the appropriate codec on your system.

*To find out the codec for the file, examine it using a tool like QuickTime or VLC and see if you can use the Inspectors in these to get the video and audio codecs for your file.

*If these two don't help, you would have to use a media information tool like MediaInspector or AviInfo on OS X or GSpot on Windows. Then search and install the codec for the file.

Here's some additional explanation and information from Adobe on "Troubleshoot file formats and codecs":

Video-recording devices and video software applications encode files in a specific file format, such as AVI, QuickTime (MOV), and Windows Media (WMV). For a list of the file formats that Adobe Premiere Elements supports, search "Supported file formats in Adobe Premiere Elements " in the Adobe Knowledgebase.
Some video file formats, including AVI and MOV, are container file formats. The data inside these container files is encoded according to a particular codec. Codecs are algorithms for compressing video and audio data. Many different codecs exist.
For example, an AVI file can be encoded with the DV codec, a commercial codec (such as DivX), a Motion JPEG codec, among others. (Camcorders that record to miniDV tapes use the DV codec. Some still-image cameras use the Motion JPEG coded.)
Adobe Premiere Elements sometimes cannot decode video files that were created with a poorly designed codec or a codec that is not installed on your computer.
Knowing the format and, when applicable, the codec of the files you are working with helps you use these solutions. To gather this information, do one or more of the following tasks:

*

*Open the file in Apple QuickTime Player and choose Window > Show Movie Inspector.

*If the file is from a camcorder, camera, or other video-recording device, see the device's documentation, or locate the device's specifications on the manufacturer's website.

*Open the file in a third-party application that analyzes media files, such as MediaInfo or GSpot 2.70.

A: I encountered this recently when my Kodak digital camera recorded in .MOV, and I figured importing it should be a breeze. Nope. I kept running into a very unhelpful "File format contains no audio or video" error when dragging the .MOV file into my clip bin.
The solution was so simple it was almost ridiculous. After Googling for a bit, I found a YouTube saying all you had to do was change the filename extension from .MOV to .MP4, and boom - done. I didn't believe it at first, but sure enough - it worked like a charm! :-)
This was on Adobe Premiere Pro CC 2015, Windows 8.

A: It's very simply.
HOW TO FIX: download avid codex pack, install it (on mac -> library->QuickTime), restart and reopen Adobe Premiere.
http://avid.force.com/pkb/articles/en_US/download/Avid-QuickTime-Codecs-LE

A: All I did was add ".mov" to the file name and all is well!!!


text:
Q: android upload multipart with progress i have an rest ws and use PostMapping ...
@PostMapping(value = "/upload", consumes = {"multipart/form-data"})
public Boolean uploadFile(@ModelAttribute UploadModel model, HttpServletRequest servletRequest) {...}

and my uploadModel is :
public class UploadModel extends RestRequest implements Serializable {
    private MultipartFile[] files;

    public MultipartFile[] getFiles() {
        return files;
    }

    public void setFiles(MultipartFile[] files) {
        this.files = files;
    }}

i need to upload my images (multi file in one request) from android device with show progress ...
can anyone help me ?

A: Here is an example how to do it (Link). Also, in the end you can find a link to

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a bug with Vagrant? How exactly does one successfully use Vagrant on Mac OSX? I have pored through pages of Stack Overflow and find tons of answers that do not solve my inability to get "vagrant up" successfully...well, up on my Mac. Here is what happens:
ldco2016@DCortes-MBP-3 ~ $ vagrant init hashicorp/precise32                                                                       [ruby-2.3.0]
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.
ldco2016@DCortes-MBP-3 ~ $ vagrant up                                                                                [ruby-2.3.0]
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'hashicorp/precise32' is up to date...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
The guest machine entered an invalid state while waiting for it
to boot. Valid states are 'starting, running'. The machine is in the
'poweroff' state. Please verify everything is configured
properly and try again.

If the provider you're using has a GUI that comes with it,
it is often helpful to open that and watch the machine, since the
GUI often has more helpful error messages than Vagrant can retrieve.
For example, if you're using VirtualBox, run `vagrant up` while the
VirtualBox GUI is open.

The primary issue for this error is that the provider you're using
is not properly configured. This is very rarely a Vagrant issue.

A: Vagrant works properly on Mac OS X. The problem you described does seem to be a bug in Vagrant, nor your mistake.
Vagrant does not really perform complicated tasks related to virtual machines itself, but sets the options and runs other programs.
In this case Vagrant ordered VirtualBox to create and start a new virtual machine and then periodically checked that machine's status to connect when it got into a "running" state. Instead Vagrant was informed that the machine had been powered off:

The guest machine entered an invalid state while waiting for it
  to boot. Valid states are 'starting, running'. The machine is in the
  'poweroff' state.

This indicates a problem with your VirtualBox (installation, settings, resources) and you should look there.
First run the Oracle VM VirtualBox Manager, right-click on the machine entry and choose "Show log..."; check if you can start the machine yourself; check the memory and CPU settings in VirtualBox.

Side note: Sometimes a tweak in Vagrantfile for OS X is required (mainly for disk sharing between the guest and host), but this is not the case with hashicorp/precise32. Using the two commands you ran, the machine started properly on El Capitan, Vagrant 1.8.4, VirtualBox 5.0.16.

A: hashicorp/* are pretty old boxes (generally older than 2 years).
You would want to use ubuntu/precise32 in your case, which are the official boxed maintained by folks from hashicorp


text:
Q: Confused coordinates - How to start ship expedition? So I bought Confused Coordinates ship action/expedition.  I have it loaded onto a warship with some weapons (the thing it says is needed for the action).  How do I start the expedition?
I have tried sailing to the edge of the map, left clicking the item in my storage bay...I dont know.

A: Items in cargo slots can't be activated, only ditched into the ocean or transferred to other ship/buildings. You have to move the Coordinates item to one of your ship's 'tool' slots, then activate it.

A: Basically put the item onto your ship. If the item (Confused Coordinates) is not on the right side (last socket) then Left click it once until it is, then put whatever materials/weapons is needed for the expedition, then Left click the Confused Coordinates one last time and the ship should automatically do the expedition. I am not sure how many materials/weapons you need for the the expedition as I have have 20 or 1 material on the ship and both time I got a reward. So now I just load it up with 1.


text:
Q: How can I be sure if MongoDB is doing the balance? I have the following structure:
Two Ubuntu 14.04.2, both with MongoDB v3.0.4 instaled. Both in the same LAN. I want to make them work as a cluster.
In the first one, that I call "MC1", I run the three config server, mongos and mongod. In the second one, that I call "MC2", I run mongos and mongod.
MC1 is the shard1.
MC2 is the shard0.
I have a DB with 2.031GB size.

I have the following problem:
When I connect via Robomongo to MC1 mongos I can see all the data of every collection. If I connect to MC2 mongos I see the DB, the collections but the collections are empty.

Testing the balancer status I get the following results:
sh.getBalancerState()
true

db.getSiblingDB("config").collections.findOne({_id : "cluster.username"}).noBalance;
false

db.databases.find()
{ "_id" : "admin", "partitioned" : false, "primary" : "config" }
{ "_id" : "test", "partitioned" : false, "primary" : "shard0001" }
{ "_id" : "db", "partitioned" : false, "primary" : "shard0001" }
{ "_id" : "cluster", "partitioned" : true, "primary" : "shard0000" }

With this data I know that the balancer is active and the collections and DB have the balancer activated.
I do a sh.status() too. Here you can see that all collections have data only in the shard0, any chunk haven't been migrate to the shard1. And I only can view the data connecting to MC1 mongos.
sh.status()
--- Sharding Status ---
sharding version: {
"_id" : 1,
"minCompatibleVersion" : 5,
"currentVersion" : 6,
"clusterId" : ObjectId("55a778641066cdf8d093fe97")
}
shards:
{  "_id" : "shard0000",  "host" : "172.31.37.215:27018" } #This one is MC2#
{  "_id" : "shard0001",  "host" : "172.31.35.191:27018" }#This one is MC1#
balancer:
Currently enabled:  yes
Currently running:  no
Failed balancer rounds in last 5 attempts:  0
Migration Results for the last 24 hours:
    No recent migrations
databases:
{  "_id" : "admin",  "partitioned" : false,  "primary" : "config" }
{  "_id" : "test",  "partitioned" : false,  "primary" : "shard0001" }
{  "_id" : "db",  "partitioned" : false,  "primary" : "shard0001" }
{  "_id" : "cluster",  "partitioned" : true,  "primary" : "shard0000"     }
    cluster.fs.chunks
        shard key: { "files_id" : 1, "n" : 1 }
        chunks:
            shard0000   1
        { "files_id" : { "$minKey" : 1 }, "n" : { "$minKey" : 1 } } -->> { "files_id" : { "$maxKey" : 1 }, "n" : { "$maxKey" : 1 } } on : shard0000 Timestamp(1, 0)
    cluster.fs.files
        shard key: { "filename" : 1, "_id" : 1 }
        chunks:
            shard0000   1
        { "filename" : { "$minKey" : 1 }, "_id" : { "$minKey" : 1 } } -->> { "filename" : { "$maxKey" : 1 }, "_id" : { "$maxKey" : 1 } } on : shard0000 Timestamp(1, 0)
    cluster.licenses
        shard key: { "license" : 1 }
        chunks:
            shard0000   1
        { "license" : { "$minKey" : 1 } } -->> { "license" : { "$maxKey" : 1 } } on : shard0000 Timestamp(1, 0)
    cluster.movusers
        shard key: { "username" : 1 }
        chunks:
            shard0000   1
        { "username" : { "$minKey" : 1 } } -->> { "username" : { "$maxKey" : 1 } } on : shard0000 Timestamp(1, 0)
    cluster.roles
        shard key: { "roleId" : 1 }
        chunks:
            shard0000   1
        { "roleId" : { "$minKey" : 1 } } -->> { "roleId" : { "$maxKey" : 1 } } on : shard0000 Timestamp(1, 0)
    cluster.sessions
        shard key: { "sessionId" : 1, "_id" : 1 }
        chunks:
            shard0000   1
        { "sessionId" : { "$minKey" : 1 }, "_id" : { "$minKey" : 1 } } -->> { "sessionId" : { "$maxKey" : 1 }, "_id" : { "$maxKey" : 1 } } on : shard0000 Timestamp(1, 0)
    cluster.webusers
        shard key: { "username" : 1, "_id" : 1 }
        chunks:
            shard0000   1
        { "username" : { "$minKey" : 1 }, "_id" : { "$minKey" : 1 } } -->> { "username" : { "$maxKey" : 1 }, "_id" : { "$maxKey" : 1 } } on : shard0000 Timestamp(1, 0)

Also I check the shardDistribution:
db.fs.chunks.getShardDistribution()

Shard shard0000 at 172.31.37.215:27018
data : 0B docs : 0 chunks : 1
estimated data per chunk : 0B
estimated docs per chunk : 0

Totals
data : 0B docs : 0 chunks : 1
Shard shard0000 contains NaN% data, NaN% docs in cluster, avg obj size on shard : NaNGiB

How can I fix this?

A: Reproducing the situation :

*

*mc1 collection already created on shard0000 before sharding

*mc2 collection already created on shard0001 before sharding

Create a test-shard:
$ mongo --nodb
mongo> config={d0:{smallfiles:"",noprealloc:"",nopreallocj : ""}, d1 : {smallfiles : "", noprealloc : "", nopreallocj : "" }};
mongo> cluster = new SharingTest({shards:config});

In another terminal (shard0000 on port 30000, shard0001 on port 30001, mongos on port 30999) :
$ ps aux | grep mongo
root      9668  0.0  0.7 655804 23484 pts/1    Sl+  15:57   0:00 mongo --nodb
root      9693  0.4  2.4 344400 74108 pts/1    Sl+  15:59   0:00 mongod --port 30000 --dbpath /data/db/test0 --smallfiles --noprealloc --nopreallocj --setParameter enableTestCommands=1
root      9712  0.3  2.1 271672 62828 pts/1    Sl+  15:59   0:00 mongod --port 30001 --dbpath /data/db/test1 --smallfiles --noprealloc --nopreallocj --setParameter enableTestCommands=1
root      9732  0.2  0.5 117672 16200 pts/1    Sl+  15:59   0:01 mongos --port 30999 --configdb localhost:30000 --chunkSize 50 --setParameter enableTestCommands=1

Create mc1 on shard0000 and mc2 on shard0001 with some data:
$ mongo --port 30000
> use cluster
> for(var i=0; i<=1000; i++) {db.mc1.insert({'a':i})}
> db.mc1.createIndex({a:1})
$ mongo --port 30001
> use cluster
> for(var i=0; i<=1000; i++) {db.mc2.insert({'a':i})}
> db.mc2.createIndex({a:1})

Connect to mongos, and shard cluster db, mc1 collection and mc2 collection:
$ mongo --port 30999
mongos> show dbs
admin    (empty)
cluster  0.063GB
config   0.016GB
mongos> use cluster
switched to db cluster
mongos> show collections
mc2     #only mc2 is shown because see in sh.status => primary : shard0001
system.indexes
mongos> sh.status()
--- Sharding Status ---
  sharding version: {
    "_id" : 1,
    "minCompatibleVersion" : 5,
    "currentVersion" : 6,
    "clusterId" : ObjectId("55dacecf2c2855020c52454e")
}
  shards:
    {  "_id" : "shard0000",  "host" : "localhost:30000" }
    {  "_id" : "shard0001",  "host" : "localhost:30001" }
  balancer:
    Currently enabled:  no
    Currently running:  no
    Failed balancer rounds in last 5 attempts:  0
    Migration Results for the last 24 hours:
        No recent migrations
  databases:
    {  "_id" : "admin",  "partitioned" : false,  "primary" : "config" }
    {  "_id" : "cluster",  "partitioned" : false,  "primary" : "shard0001" }
mongos> sh.enableSharding("cluster")
{ "ok" : 1 }
mongos> sh.shardCollection("cluster.mc1", {'a':1})
{ "collectionsharded" : "cluster.mc1", "ok" : 1 }
mongos> sh.shardCollection("cluster.mc2", {'a':1})
{ "collectionsharded" : "cluster.mc2", "ok" : 1 }

Check amount of documents in the shard-distribution:
mongos> db.mc1.getShardDistribution()

Shard shard0001 at localhost:30001
 data : 0B docs : 0 chunks : 1
 estimated data per chunk : 0B
 estimated docs per chunk : 0

Totals
 data : 0B docs : 0 chunks : 1
 Shard shard0001 contains NaN% data, NaN% docs in cluster, avg obj size on shard : NaNGiB

mongos> db.mc2.getShardDistribution()

Shard shard0001 at localhost:30001
 data : 46KiB docs : 1001 chunks : 1
 estimated data per chunk : 46KiB
 estimated docs per chunk : 1001

Totals
 data : 46KiB docs : 1001 chunks : 1
 Shard shard0001 contains 100% data, 100% docs in cluster, avg obj size on shard : 48B

Problem :  No documents in mc1. See shard.status() => primary is pointing to Shard001. So only the collections in cluster-database on Shard0001 got sharded.
Solution 1:

*

*Dump mc1 collection from shard0000

*Drop mc1 collection from shard0000

*Restore mc1 collection into mongos
(!!!! make sure nobody can add more records !!!!)
$ mkdir mc1
$ mongodump --port 30000 --db=cluster --collection=mc1 --out mc1/
$ mongo --port 30000 --eval "db.mc1.drop()" cluster
$ mongorestore --port 30999 --db=cluster --collection=mc1 mc1/cluster/mc1.bson
$ mongo --port 30999
MongoDB shell version: 3.0.5
connecting to: 127.0.0.1:30999/test
Server has startup warnings:
2015-08-24T15:59:11.178+0800 I CONTROL  ** WARNING: You are running this process as the root user, which is not recommended.
2015-08-24T15:59:11.178+0800 I CONTROL
mongos> use cluster
switched to db cluster
mongos> show collections
mc1
mc2
system.indexes
mongos> sh.status()
--- Sharding Status ---
  sharding version: {
    "_id" : 1,
    "minCompatibleVersion" : 5,
    "currentVersion" : 6,
    "clusterId" : ObjectId("55dacecf2c2855020c52454e")
}
  shards:
    {  "_id" : "shard0000",  "host" : "localhost:30000" }
    {  "_id" : "shard0001",  "host" : "localhost:30001" }
  balancer:
    Currently enabled:  no
    Currently running:  no
    Failed balancer rounds in last 5 attempts:  0
    Migration Results for the last 24 hours:
        No recent migrations
  databases:
    {  "_id" : "admin",  "partitioned" : false,  "primary" : "config" }
    {  "_id" : "cluster",  "partitioned" : true,  "primary" : "shard0001" }
        cluster.mc1
            shard key: { "a" : 1 }
            chunks:
                shard0001   4
            { "a" : { "$minKey" : 1 } } -->> { "a" : 1 } on : shard0001 Timestamp(1, 1)
            { "a" : 1 } -->> { "a" : 651 } on : shard0001 Timestamp(1, 2)
            { "a" : 651 } -->> { "a" : 977 } on : shard0001 Timestamp(1, 3)
            { "a" : 977 } -->> { "a" : { "$maxKey" : 1 } } on : shard0001 Timestamp(1, 4)
        cluster.mc2
            shard key: { "a" : 1 }
            chunks:
                shard0001   1
            { "a" : { "$minKey" : 1 } } -->> { "a" : { "$maxKey" : 1 } } on : shard0001 Timestamp(1, 0)

Solution 2 (without having to dump):
(Dropping a collection or a database will remove it from the cluster configuration automatically)
Drop 'empty'-mc1 collection from cluster (test first if empty):
mongos> use cluster
switched to db cluster
mongos> db.mc1.find().count()
0
mongos> db.mc1.drop();
true

Move primary to shard0000:
mongos> use admin
switched to db admin
mongos> db.runCommand({movePrimary:"cluster", to:"shard0000"});
{ "primary " : "shard0000:localhost:30000", "ok" : 1 }

Checking the status:
mongos> use cluster
switched to db cluster
mongos> sh.status();
--- Sharding Status ---
  sharding version: {
    "_id" : 1,
    "minCompatibleVersion" : 5,
    "currentVersion" : 6,
    "clusterId" : ObjectId("55dacecf2c2855020c52454e")
}
  shards:
    {  "_id" : "shard0000",  "host" : "localhost:30000" }
    {  "_id" : "shard0001",  "host" : "localhost:30001" }
  balancer:
    Currently enabled:  no
    Currently running:  no
    Failed balancer rounds in last 5 attempts:  0
    Migration Results for the last 24 hours:
        No recent migrations
  databases:
    {  "_id" : "admin",  "partitioned" : false,  "primary" : "config" }
    {  "_id" : "cluster",  "partitioned" : true,  "primary" : "shard0000" }
        cluster.mc2
            shard key: { "a" : 1 }
            chunks:
                shard0001   1
            { "a" : { "$minKey" : 1 } } -->> { "a" : { "$maxKey" : 1 } } on : shard0001 Timestamp(1, 0)

mongos> show collections
mc1
system.indexes
mongos> db.mc1.find().count()
1001
mongos> db.mc2.find().count()
1001

Shard mc1 now into the collection:
mongos> sh.shardCollection("cluster.mc1", {'a':1});
{ "collectionsharded" : "cluster.mc1", "ok" : 1 }
mongos> db.mc1.getShardDistribution()

Shard shard0000 at localhost:30000
 data : 46KiB docs : 1001 chunks : 1
 estimated data per chunk : 46KiB
 estimated docs per chunk : 1001

Totals
 data : 46KiB docs : 1001 chunks : 1
 Shard shard0000 contains 100% data, 100% docs in cluster, avg obj size on shard : 48B

mongos> db.mc2.getShardDistribution()

Shard shard0001 at localhost:30001
 data : 46KiB docs : 1001 chunks : 1
 estimated data per chunk : 46KiB
 estimated docs per chunk : 1001

Totals
 data : 46KiB docs : 1001 chunks : 1
 Shard shard0001 contains 100% data, 100% docs in cluster, avg obj size on shard : 48B

Joy joy joy, that added it!!!
So, in your case (connect to mongos):
> use cluster
> db.fs.chunks.find().count()    #check if 0
> db.fs.chunks.drop()
> use admin
> db.runCommand({movePrimary:"cluster", to:"shard0001"});
> use cluster
> sh.shardCollection("cluster.fs.chunks", {'files_id':1,'n':1});


text:
Q: Question about the Poisson distribution I will first present the question at hand and then describe how I solved it.  Apparently my solution is incorrect and I cannot figure out why, so I was wondering if anyone here might have some insight.  (It is possible that it is correct, but someone told me it is wrong.)

Suppose $X_1, X_2, \ldots$ are independent with common distribution $\operatorname{Poisson}(\lambda)$.  For $\nu\ge1$, consider the partial sums $S_\nu = X_1 + \cdots + X_\nu$.  Given any two non-negative integers $m\le n$, evaluate ${\bf P}\{S_m=j\mid S_n=k\}$ where $0\le j\le k$.

(original screenshot)
So here is how I solved this.  I first noted that, by the stability of the Poisson distribution, $S_v \sim \text{Poisson}(v\lambda)$.  Then, I apply Bayes' rule to find that
\begin{align*}
P(S_m = j \mid S_n = k) &= P(S_n = k \mid S_m = j)\cdot \frac{P(S_m = j)}{P(S_n = k)}\\
&= P(S_{n-m} = k-j)\cdot \frac{P(S_m = j)}{P(S_n = k)}\\
&= \dfrac{((n-m)\lambda)^{(k-j)} e^{-(n-m)\lambda}}{(k-j)!} \cdot \dfrac{(\lambda m)^j e^{-\lambda m}/j!}{(\lambda n)^k e^{-\lambda n}/k!}\\
&= ((n-m)\lambda)^{(k-j)}  \cdot \dfrac{(\lambda m)^j}{(\lambda n)^k }\binom{k}{j}\\
&= \boxed{(n-m)^{(k-j)}  \cdot \dfrac{m^j}{n^k }\binom{k}{j}}
\end{align*}
However, apparently this solution is incorrect.  Can anyone provide any insight into where I went wrong?


text:
Q: CSS Table is larger than specified I'm writing some code to generate a "full screen" page with a header.  I'm using a table to do layout, with CSS specifying the dimensions and formatting.
The table has a height and width of 100% to cause it to fill the window/viewport, which at first works as intended.  The table has two rows with one cell each.  The first row's cell has a height of 20px, while the other row's cell has a height of 100% to allow it to fill the remaining space of the window.  Inside the bottom cell is an iFrame, set to 100%x100% to fill the cell.  The iFrame works as intended, however the table is not following its settings.
When the page is rendered in IE, which is specifically my target browser, the table is being stretched outside the range of the viewport.  Specifically, the table is adding 20px to its dimensions.  Even when I set the table to a fixed height, it's still adding 20px to the dimensions I'm setting.  I'd expect the code to force the table to 100% height, have a top cell of 20px, and the bottom cell specifically take up the remaining available space of the table's height, without stretching the table.  This works perfectly in Chrome, but IE keeps making the table's height 100%+20px, even with a CSS rule setting it to strictly 100% height.
Below is a simplified version of my code:

    {content header here}

    {iframe with dimensions 100% x 100% here}

The result in Chrome displays perfectly.  In IE, the containing table ends up 20px too tall and runs outside the viewport, causing the bottom 20px of the iframe to be outside the viewport.

A: That's normal. One of the table rows is with height "20px" and the other is with height "100%".
Instead of "height:100%" use "height:auto".
This will force the browser to calculate what is the left page height space from the parent element if the first row is with height 20px:
Also, "height:auto" could save you potential problems if your table has border and your elements has some padding or margins set.


text:
Q: What is the correct error handling pattern for the calling function when calling a promise? I am completely new to Promises and async/await and just reading through tutorials etc., so I expect I may be missing something fundamental.
I've see this code pattern in several places, but I'm thinking maybe it should not be trusted:
async function myFunc() {
  try {
      var result = await doSomethingAsync();
      console.log(result);
  }
  catch(error) {
      console.error(error); // hmm
  }
}

myFunc();

Consider the following scenario using the above pattern:
const doSomethingAsync = behaviour => new Promise((resolve, reject) => {
    // use setTimeout to simulate e.g. an async webapi callback func
    setTimeout(() => {
        if(behaviour === "set resolve")
            resolve("resolved");
        if(behaviour === "set reject")
            reject("rejected");
        if(behaviour === "set after timeout error")
            throw new Error("something went wrong after setTimeout returned");
    }, 500);

    if(behaviour === "set promise error")
        throw new Error("something went wrong in promise");
});

async function myFunc(behaviour) {
  try {
        // wait for promise to complete
        var result = await doSomethingAsync(behaviour);
        console.log(result);
  }
  catch(error) {
      console.error("caught:" + error); // will catch reject and promise error,
                                        // but NOT after setTimeout error
  }
}

myFunc("set promise error");  // caught:Error: something went wrong in promise
myFunc("set resolve"); // resolved
myFunc("set reject"); // caught:rejected
myFunc("set after timeout error"); // Uncaught Error: something went
                                   // wrong after setTimeout returned
                                   // UHOH!!

So the pattern seems a little misleading as it cannot catch the setTimeout error, whereas people tend to think of catch() as a catch-all.
Of course, changing the setTimeout to have an internal catch will solve the uncaught error problem:
const doSomethingAsync = behaviour => new Promise((resolve, reject) => {
    // use setTimeout to simulate e.g. an async webapi call
    setTimeout(() => {
        try { // ...
        }
        catch(e) { reject("an error"); }
    }, 500);
});

So, my questions are:

*

*As I understand it, Promises are used as a replacement for callbacks, i.e. for wrapping async calls like setTimeout. So should there always be an internal try/catch -> reject pattern implemented inside a Promise? (So that the error can be gracefully handled by the caller). Do e.g. all node libraries work in this way?
I can't see any way for the caller to deal with it by itself.

*I find the pattern misleading, wouldn't the pattern be better like this?
    async function myFunc(behaviour) {
      try {
            var result = await doSomethingAsync(behaviour);
                            .catch(e) { console.log("expected reject happened:" + e) };
      }
      catch(error) {
          console.error("something totally unexpected happened:" + error);
      }
    }


text:
Q: Heroku verify code in Google Authenticator app is gone so i've factory reset my Android phone and Google Authenticator app is automatically uninstalled because of that.
The problem is when I'm install Google Authenticator app and login with the same Google account it's all gone including my FB, Heroku, etc for verifying code. I'm glad my FB 2-FA doesn't need Google Auth code.
The point is how to recover my Heroku account if I cannot login to verify my authenticator code? please help :)


text:
Q: Problems with acessing docker container WildFly hosted application
I am using WildFly 8.2.1 to host my application on my host system with following configuration:

*

*WildFly is running on localhost:8080

*Management console is running on localhost:9990
I have my app hosted and accessible with following URL:
https://localhost:8081/MyAppRoute

I used Docker to send it over to other people but I am havin problems with accessing my application from host environment (keep getting website unreachable).
I am running docker component with following command:
docker run -d --name MyApp -p 8080:8080 -p 9990:9990 -p 8081:8081 -p 8082:8082 -p 8083:8083 MyApp

I am exposing 8080, 9990 for WildFly communication (which works fine) and other ports for myApp (doesn't work).
Any ideas what could be the problem? Thats my first app on docker so maybe I am missing something.


text:
Q: Can someone check this so I don't fry someone's gps/transponder?
I am helping someone out over at aviation stack exchange -- they want a signal led for their gps receiver to do a preflight check to make sure it is working.   They basically want to be able to press a button and see if the tx line is hot (as it should be) with a signal led.   I suggested they use a transistor so as to not draw too much current from the tx line.   Here is a link to the original post:
https://aviation.stackexchange.com/questions/42812/how-can-i-check-that-the-gps-receiver-is-sending-data-to-the-transponder/42826#42826
Here is a link to the datasheet of the PNP transistor i use:
  https://www.centralsemi.com/get_document.php?cmp=1&mergetype=pd&mergepath=pd&pdf_id=2N4402.PDF
And here is what I suggested.   Is there anything in this circuit that would damage their equipment (or any mistakes I made in the circuit)?

Your GPS puck (GlobalSat BR355) runs on 5v and the UART line idles high (it is pulled high when there is no traffic).   The first thing you need to do is find the power lines that go to the gps puck -- connect wires to these lines (5v and gnd) and run them to the spot where you want the button/led.   Then make this circuit:

The value for R1 should be 120 ohms (which will yield a little under 20ma of current through the LED, assuming your led has a voltage drop of 2.1v (which the ones in the link I provided do have))
Just wire these components up according to the picture and solder them together -- I'll leave how to mount the switch and the LED up to you but make sure once you are done you cover all the exposed wire with glue and/or electrical tape and/or liquid electrical tape so they don't accidentally short out.   Also make sure no exposed wires within the circuit are touching where they shouldn't touch (especially make sure you separate the pins of the transistor because if they accidentally touch the circuit will not work and you may damage your gps receiver -- long story short be careful in your wiring and make sure nothing is touching that shouldn't.
P.S. if you want you can move the button between 5v and LED1 if that makes it easier for you to mount; that would look something like this:

A: There was way too much to read, so I'm only responding to the first schematic.
You have roughly the right concept, but some details are wrong.
Let's check the resistor value.  The LED drops 2.1 V, and figure about 700 mV E-B drop in the transistor.  Starting from 5 V, that leaves 2.2 V across the resistor.  For 20 mA, the resistor would be (2.2 V)/(20 mA) = 110 Ω.  Your 120 Ω is therefore very close to the limit.  I'd use 150 Ω to provide some margin.  You'll barely notice the loss of brightness in the LED.
The outright wrong part is how the switch is incorporated.  When the collector of the transistor is floating, the transistor acts like a diode E-B.  The signal will still try to light the LED, but there won't be any gain from the transistor to help it.  Put the switch in-line with the base, not the collector.
A more fancy circuit would detect toggling activity, but what you show is one step better than nothing.

A: First schematic stinks.
With the button NOT pressed, when the TX line goes low, the base-emitter junction acts as a forward biassed diode, and draws enough current to light the LED from the TX pin. This is probably not what you intended.
I would use the button to connect TX to the circuit, so that there is normally no connection to the GPS signals, and perhaps use a very high value resistor (1M) from base to +5V to hold the transistor off when the button is not pressed. Other details are reasonable, Olin's comments are good (and I see he's revised his answer to cover the switch location)


text:
Q: Adding sequence numbers to SAS I am importing a table from an Access database into SAS where the sequence column became corrupted. I need to create a new sequence column in SAS. I don't want to re-create the sequence number in Access, as the source tables are replenished on a regular schedule. Is there something like an autonumber column that one can add to SAS?

A: You can do something like this:
data want;
set have;
autonumber+1;
run;

There is also _N_ which is the count of iterations through the data step loop, which in a normal data step is equal to the row number.  It is not written to the dataset but can always be accessed as a normal variable.

A: When you read in a data set in SAS, _n_ refers to the observation number. This should work for you:
data new;
 set old;
 seqno = _n_;
run;

A: A classic example of _N_ not being identical to the observation number - a DoW loop used to append the sum of a variable to every row for each value of a class variable.  Note at the end that _N_ does not return the row number, but the iteration number - in this case, the data step loop iterates once for each value of x, not once for each row, as the rows are pulled in through a do..until loop.
data have;
do x = 1 to 5;
  do y = 1 to 3;
    z=floor(7*ranuni(7));
    rownum+1;
    output;
  end;
end;
run;

data test;
 do t=1 by 1 until (last.x);
    set have;
    by x;
    sum_z+z;
 end;
 do t=1 by 1 until (last.x);
    set have;
    by x;
    output;
    put x= z= sum_z= _N_= rownum=;
 end;
 sum_z=0;
run;

Log:
x=1 z=2 sum_z=12 _N_=1 rownum=1
x=1 z=5 sum_z=12 _N_=1 rownum=2
x=1 z=5 sum_z=12 _N_=1 rownum=3
x=2 z=5 sum_z=13 _N_=2 rownum=4
x=2 z=3 sum_z=13 _N_=2 rownum=5
x=2 z=5 sum_z=13 _N_=2 rownum=6
x=3 z=5 sum_z=12 _N_=3 rownum=7
x=3 z=5 sum_z=12 _N_=3 rownum=8
x=3 z=2 sum_z=12 _N_=3 rownum=9
x=4 z=3 sum_z=12 _N_=4 rownum=10
x=4 z=5 sum_z=12 _N_=4 rownum=11
x=4 z=4 sum_z=12 _N_=4 rownum=12
x=5 z=6 sum_z=13 _N_=5 rownum=13
x=5 z=3 sum_z=13 _N_=5 rownum=14
x=5 z=4 sum_z=13 _N_=5 rownum=15


text:
Q: Symbolic Links as include folders in Visual Studio My folder structure is something like this:
.
└─ Projects
   ├─ MyProject
   |  ├─ lib
   |  ├─ src
   |  └─ include
   └─ MyOtherProject
      ├─ src
      └─ include

I need the headers from MyOtherProject in MyProject and I created a symbolic link with the following command mklink /D "Projects/MyProject/include/MyOtherProject" "Projects/MyOtherProject/include" but when using Visual Studio it doesn't recognize MyOtherProject folder in the include directory.
I have set up the Additional Include Directories variable in VS as $(ProjectDir)include which should evaluate to Projects/MyProject/include.
As to my question I think it is, does Visual Studio support using symbolic links and if so what am I doing wrong?
I'm using Windows 10 and Visual Studio 2017.

A: You are using forward slashes in mklink /D "Projects/MyProject/include/MyOtherProject" "Projects/MyOtherProject/include" - use backslashes and test created link in explorer.
When creating symbolic links, you have to think about target relative to link directory. mklink /D "Projects\MyProject\include" "..\MyOtherProject\include" or give full absolute path.
In my opinion directory junction (mklink /j "MyProject\include" "MyOtherProject\include") are easier to work with. I'm using them for redirecting directories used by Firefox, Thunderbird and other programs.
For additional includes I would use just include. You can even use ..\MyOtherProject\include directly without symlink or junction.


text:
Q: Can I use an image on a moving object within Pygame as opposed to to a color?    def star1():
        global angle
        x = int(math.cos(angle) * 100) + 800
        y = int(math.sin(angle) * 65) + 400
        pygame.draw.circle(screen, white, (x, y), 17)
        angle += 0.02

The parameters pygame gives for the .draw.circle here only allow for an RGB color to be used to color the figure. I am wondering if there is a way I can pass an image as a color, or use a different method that allows me to place an image on the object/circle. The circles move around so the image also needs to stay with the circle as it moves.

A: *

*Create a transparent pygame.Surface with the desired size

*Draw a white circle in the middle of the Surface

*Blend the image (my_image) on this Surface using the blend mode BLEND_RGBA_MIN:
size = 100
circular_image = pygame.Surface((size, size), pygame.SRCALPHA)
pygame.draw.circle(circular_image, (255, 255, 255), (size//2, size//2), size//2)
image_rect = my_image.get_rect(center = circular_image.get_rect().center)
circular_image.blit(my_image, image_rect, special_flags=pygame.BLEND_RGBA_MIN)

Minimal example:

import pygame

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

def create_circular_image(size, image):
    clip_image = pygame.Surface((size, size), pygame.SRCALPHA)
    pygame.draw.circle(clip_image, (255, 255, 255), (size//2, size//2), size//2)
    image_rect = my_image.get_rect(center = clip_image.get_rect().center)
    clip_image.blit(my_image, image_rect, special_flags=pygame.BLEND_RGBA_MIN)
    return clip_image

def create_test_image():
    image = pygame.Surface((100, 100))
    ts, w, h, c1, c2 = 25, 100, 100, (255, 64, 64), (32, 64, 255)
    [pygame.draw.rect(image, c1 if (x+y) % 2 == 0 else c2, (x*ts, y*ts, ts, ts))
        for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
    return image

my_image = create_test_image()
circular_image = create_circular_image(100, my_image)

rect = circular_image.get_rect(center = window.get_rect().center)
run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    rect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * 5
    rect.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * 5

    window.fill((64, 64, 64))
    window.blit(circular_image, rect)
    pygame.display.flip()

pygame.quit()
exit()

See also:

*

*how to make circular surface in PyGame

*How to fill only certain circular parts of the window in PyGame?

*Clipping

A: Write a function that draws an image on a given x, y and pass these x, y values used in the circle function.
Basicly it's just win.blit(image, (x,y)). Don't forget to subtruct radius value. So the image matchs with circle.


text:
Q: how to stop and remove new release My insider machine is currently running 15048 but fails to install 15055.  How can I remove the downloaded upgrade, because after a failed upgrade, I'm presented with a "A reboot is required to finalize installing 15055".  I want the computer to check upgrades, because 15061 is available, and my computer might have more luck with it.

A: Go to c:\windows\softwaredistribution and delete all the content in the folder and reboot this way you'd delete the occurring updates and it will check automatically for new ones and downalod them.
Don't worry about deleting the folder it will recreate itself after the reboot.


text:
Q: Semisimplicity of a polynomial ring Given a ring $R$ (with 1 and not necessarily commutative) when is the polynomial ring $R[x]$ semisimple?
For example if R is a Noetherian integral domain then R[x] is not semisimple. Indeed, $R[x]$ is Noetherian but then if we assume that $R[x]$ is semisimple this would imply that $R[x]$ is Artinian which is not.
Question: is there a ring $R$ (with $1$ and not necessarily commmutative) such that $R[x]$ is semisimple? or is $R[x]$ never semisimple for any ring $R$?

A: Your post already contains the answer. Polynomial rings are not Artinian, since $$(x)\supset(x^2)\supset(x^3)\supset\ldots$$
But semisimple rings are Artinian.
In fact, the Wedderburn-Artin Theorem states that all semisimple rings are direct sums of matrix rings over division algebras. Polynomial rings are certainly not of this form.

A: If we understand semisimple to mean all modules are projective then $R[X]$ is never semisimple.
Indeed, if we let $S=R[X]/(X)$, the canonical $R[X]$-linear projection map $f:R[X]\to S$ is not split: there is no $R[X]$-linear map $s:S\to R[X]$ such that $f\circ s$ is the identity of $S$. To see this notice that the element $u=f(1_R)\in S$ is an element such that $X\cdot u=0$ and that $s$ would necessarily be injective, so that we would have an element $v=s(u)\in R[X]$ such that $X\cdot v=0$.

A: Yay! Let's do all the characterizations. All semisimple rings are Von Neumann regular. But, if you choose $x\in R[x]$ then you need to be able to find a $p(x)\in R[x]$ such that $x=x^2p(x)$ but this is clearly impossible.


text:
Q: Is the adverb "yet" redundant? I mention some project and I say, "It is not finished." Is adding the adverb "yet" provide anything extra (perhaps, implying that some people are still working on it, versus it is abandoned; or perhaps it is expected to be finished sometime relatively soon, versus some indefinite time in the future), or is it redundant?

A: No, it isn't redundant.
There are many unfinished works which will never be finished for a variety of reasons. For example, Schubert's Unfinished Symphony.
Saying something is unfinished merely tells its current state but says nothing about its future.
Saying something is yet to be finished implies that it will be finished at some point in the future. "It is not finished yet" has the same meaning.


text:
Q: Using instance method in java 8 :: method reference with null Object Why when using an instance method in method reference (::) does not throw a NullPointerException if we set the Object instance to null?
  public class MethodReferenceTest {

        public static void main(String...strings){

            PredicateSample predicateSample = new PredicateSample();
            Predicate<String> predicate = predicateSample::isNotEmpty;
            // NullpointerException ???
            predicateSample = null;
            Arrays.asList("a","b","c",null)
                .stream()
                .filter(predicate)
                .forEach(System.out::println);
        }

        static class PredicateSample{
            public boolean isNotEmpty(String s){
                return ((s!=null) && (!s.isEmpty()));
            }
        }
    }

It seems like predicateSample is not invoked after constructing the Predicate?

A: The key line in the language spec is where it is discussing the runtime evaluation of method references (emphasis mine):

*

*If the form is ExpressionName :: [TypeArguments] Identifier or Primary :: [TypeArguments] Identifier ...

*

*....

*The target reference is the value of ExpressionName or Primary, as determined when the method reference expression was evaluated.

So it doesn't matter if you change the value of the target reference afterwards.

A: The method reference "remembered" the state of the predicateSample when it was initialized. It has a reference exactly to that new PredicateSample() you have created before.
After 2 lines executed, you have got two references to that new PredicateSample() - the predicateSample and the one "within" the method reference.
Changing the former makes no effect to the latter.

Let's do an interesting trick.
Here is an array to wrap up a new PredicateSample() into a predicates[0]:
PredicateSample[] predicates = new PredicateSample[1];
predicates[0] = new PredicateSample();

Within the lambda, you use a reference to the predicates[0];
Predicate<String> predicate = string -> predicates[0].isNotEmpty(string);

You update the predicates[0] to null and do the same stuff:
predicates[0] = null;
Stream.of("a","b","c").filter(predicate).forEach(System.out::println);

A: PredicateSample predicateSample = new PredicateSample();
Predicate<String> predicate = predicateSample::isNotEmpty; //it will work fine and initializing with false.
            // NullpointerException ???
predicateSample = null;
Arrays.asList("a","b","c",null).stream().filter(predicate).forEach(System.out::println);

in above code you are initializing predicateSample with null and thereafter there is no use of this object predicateSample.
in your code you have write
Predicate<String> predicate = predicateSample::isNotEmpty;
            // NullpointerException ???
predicateSample = null; // null initialize after `isNotEmpty` call. then why Null Pointer will raised ?

now no use of predicateSample further. then why NPE?

Modified code to throw NPE.

PredicateSample predicateSample = new PredicateSample()
// NullpointerException ???
    predicateSample = null;;
    Predicate<String> predicate = predicateSample::isNotEmpty; //it will not work fine and raise NPE.
              Arrays.asList("a","b","c",null).stream().filter(predicate).forEach(System.out::println);


text:
Q: What is difference between 'transfer learning' and 'domain adaptation'? Is there any difference between 'transfer learning' and 'domain adaptation'?
I don't know about context, but my understanding is that we have some dataset 1 and train on it, after which we have another dataset 2 for which we want to adapt our model without retraining from scratch, for which 'transfer learning' and 'domain adaptation' help solve this problem.
According to the field of Convolutional Neural Networks:

*

*By 'transfer learning' I mean 'finetuning' [1]

*In this case [2] it's unsupervised, but should 'domain adaptation' always be unsupervised?

A: Throughout the literature on transfer learning, there is a number of terminology inconsistencies. Phrases such as transfer learning and domain adaptation are used to refer to similar processes. Domain adaptation is the process of adapting one or more source domains for the means of transferring information to improve the performance of a target learner. The domain adaptation process attempts to alter a source domain in an attempt to bring the distribution of the source closer to that of the target. In the Domain Adaptation setting the source and target domains have different marginal distributions p(X). According to Pan's survey, Transfer Learning is a broader term that can also include the case when there is a difference in the conditional distributions p(Y|X) of the source and target domains. In contrast, Daume discriminates the two terms [1], referring that Domain Adaptation is when p(X) changes between source and target and Transfer learning is when p(Y|X) changes between source and target domains.

*

*https://nlpers.blogspot.com/2007/11/domain-adaptation-vs-transfer-learning.html

A: I think that "Transfer Learning" is a more general term, and "Domain Adaptation" is a scenario of "Transfer Learning".
[1] Transferable Attention for Domain Adaptation. http://ise.thss.tsinghua.edu.cn/~mlong/doc/transferable-attention-aaai19.pdf

A: It seems that there are some disagreement between researchers on what the difference between 'transfer learning' and 'domain adaptation' is.
From {0}:

The notion of domain adaptation is closely related to transfer learning. Transfer learning is a general term that refers to a class of machine learning problems that involve different tasks or domains. In the literature, there isn't yet a standard definition of transfer learning. In some papers it's interchangeable with domain
  adaptation.

From {1}:

References:

*

*{0} Li, Qi. "Literature survey: domain adaptation algorithms for natural language processing." Department of Computer Science The Graduate Center, The City University of New York (2012): 8-10. https://scholar.google.com/scholar?cluster=2828982016930721315&hl=en&as_sdt=0,22 ; https://pdfs.semanticscholar.org/532e/3d5b1b5807771b77cac60fe8594b506fcff9.pdf ; http://nlp.cs.rpi.edu/paper/qisurvey.pdf  (mirror)

*{1} Pan, Sinno Jialin, and Qiang Yang. "A survey on transfer learning." IEEE Transactions on knowledge and data engineering 22, no. 10 (2010): 1345-1359. https://scholar.google.com/scholar?cluster=17771403852323259019&hl=en&as_sdt=0,22 ; http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.158.4126&rep=rep1&type=pdf  (mirror) (2.6k citations)

A: From Hal Daume's article [1]:

The standard classification setting is a input distribution p(X) and a
  label distribution p(Y|X).  Domain adaptation: when p(X) changes
  between training and test.  Transfer learning: when p(Y|X) changes
  between training and test.
In other words, in DA the input distribution changes but the labels
  remain the same; in TL, the input distributions stays the same, but
  the labels change.

*

*https://nlpers.blogspot.com/2007/11/domain-adaptation-vs-transfer-learning.html  (mirror)

A: According to [1], domain adaptation is the transfer learning in NLP: "Transfer learning in the NLP domain is sometimes referred to as domain adaptation."
[1] Pan, S. J., and Q. Yang. "A Survey on Transfer Learning." IEEE Transactions on Knowledge and Data Engineering 22, no. 10 (October 2010): 1345–59. https://doi.org/10.1109/TKDE.2009.191 or https://www.cse.ust.hk/~qyang/Docs/2009/tkde_transfer_learning.pdf

A: It seems wikipedia has the most concise answer:

Domain adaptation is a subcategory of transfer learning. In domain
adaptation, the source and target domains all have the same feature
space (but different distributions); in contrast, transfer learning
includes cases where the target domain's feature space is different
from the source feature space or spaces.

Here is the source.


text:
Q: Асинхронная загрузка картинок в адаптере RecyclerView Есть RecyclerView, у каждого пункта списка есть картинка. Картинка загружается асинхронно с помощью AsyncTask внутри холдера. Проблема в том, что когда список очень большой и пользователь быстро его прокручивает, то запускается единовременно очень много экземпляров AsyncTask, что может приводить к OutOfMemoryError.
Как можно обойти это?
Знаю, что существуют Picasso и UIL, но в данном случае они не подходят.


text:
Q: How do you enable ssl debugging for a keycloak container? I'm trying to hook Keycloak up to an external openLDAP using mutual authentication ssl.  I'm having problems figuring this out because the error codes from Keycloak are very terse.
I know ssl debuging can be turned on by passing -Djavax.net.debug=ssl to Keycloak.  But I'm running Keycloak in a prebuilt container and passing it in with -e doesn't seem to do anything.  Is their an easy method to do this?
This is on Keycloak 8.0.2

A: It seems this was a user error issue.
This can be passed in several ways.
The following works
-e JAVA_OPTS=-Djavax.net.debug=ssl
Putting the following in the Dockerfile works
ENV JAVA_OPTS=-Djavax.net.debug=ssl
and of course you can change standalone.conf and have your Dockerfile copy it into the image over the original.


text:
Q: Count frequency instances in Audio (wav) Python I am working on a function that returns the ratio of audible/non-audible frequencies in a wav file using python. I am also working on another function to give a speech/non-speech ratio. I am trying to do this based on the frequencies detected. Taking the scenario of the first function, I just want to return how much of the audio is audible (20hz-20khz). For now, I was able to get the array of frequencies in the audio and check if there are non-audible parts.
from scipy.io import wavfile
import numpy as np

wav_path = '/path/to/wav/file'

rate, wav_data = wavfile.read(wav_path, 'rb')

FFT_data = np.fft.rfft(wav_data)

freq = np.fft.rfftfreq(len(wav_data), d=1./rate)

ultrasonic = (np.where(freq > 20.E3))

infrasonic = (np.where(freq < 20))

After this, I am looking at how to get the ratio of how much the ultrasonic and infrared. Could (len(ultrasonic)+len(infrasonic))/len(freq)) work? Because I am not sure that the length of the frequencies array is relevant. I am looking to have a time-domain ratio like 2s out of 5s are audible.


text:
Q: Facebook API for Android displays blank window I am using the Facebook API to post messages to Facebook from my Android app. I have tested it out on various different phones, yet on one particular phone the Facebook API just pops up a blank white dialogue window that doesn't load the FB log in page.
I have tested it on the Samsung Galaxy S, the HTC Desire, HTC Sensation and it works fine - but when I try it on the HTC Wildfire S it does not work.
There are no messages popping up in LogCat and stepping through it with the debugger does not reveal any problems.
Looking through the code provided by Facebook I can see it is just a WebView which is being created. There is a function called onPageFinished(..) which gets called but there is nothing in the WebView.
I'm not really sure what to try to fix this. I've tried clearing some settings on the phone but that did not work. Does anybody have any ideas?


text:
Q: Getting ArrayList Size on jsp page hi I am trying to get the total size of an arraylist but for some reason this is not being shown the code below is used to show the size.
    <%db.DBConnection db = new  db.DBConnection();
            ArrayList<User> myUsers =db.getAllUsers();
            %>

   Total Subscribed Users:
<% myUsers.size();%>

Thanks

A: does this work?

<%= myUsers.size()%>

I suggest that write as less java codes as possible in your jsp. You could consider to use some taglib, jstl. for example. Put all business codes on your server side.  specially  things like b.DBConnection db = new  db.DBConnection();

A: Some of this is clearly ripe for moving out of JSP, but based on how it looks like your classes and methods are defined, this should work (JSP + JSTL):
<jsp:useBean id="db" class="db.DBConnection"/>
<c:set var="myUsers" value="${db.allUsers}"/>
Total Subscribed Users:
${fn:length(myUsers)}

A:  int count = myUsers.size();
            %>

User Management

            Total Subscribed Users:
<%=count%>

A: You should do this to achieve that purpose:
Total Subscribed Users:
<%= myUsers.size(); %>

Alternatively, you can also do:
Total Subscribed Users:
<% out.print(String.valueOf(myUsers.size()));%>

The block of code you wrote in your question was a "scriplet".  By itself, a scriptlet doesn't contribute any HTML.
See this for more details.


text:
Q: How do I implement dark mode into a PWA with no framework? I'm building a PWA for iOS and Android, and I'm not using a framework (it is a very basic app and app size is a big issue). I want to implement dark mode so that when the user switches their device to dark mode, the app theme changes dark too. How do I do this?

A: I've been stuck on this for a while now and I think I've come across a good solution. Previously I've used the ionic 4 framework and their Docs contain an interesting page about adding dark mode to a PWA. Link here
It talks about a CSS selector that can detect when the user's device is running on dark mode, and change the element styles accordingly. From the docs:

The first way to enable dark mode is by using the CSS media query for the user's preferred color scheme. This media query will hook into the system setting of the user's device and apply the theme if a dark mode is enabled.

@media (prefers-color-scheme: dark) {
  :root {
    /* dark mode variables go here */
  }
}

Currently, the prefers-color-scheme media query has limited browser support, so users will not be able to benefit from having the dark mode applied using this media query in certain browsers. However, the dark mode can still be applied by using a CSS class fallback.

/* Fallback for older browsers or manual mode */
body.dark {
  /* Dark mode variables go here */
}

I've tested this in my PWA on iOS 13 and iPadOS, and they both seem to work when I change my device to dark mode. I'm not sure about android but I expect the result will be the same.
It's also worth noting that you can enable your app's dark mode settings though the app (ie. have a setting within your app, so your app can be dark even when the device isn't). The demo further down the docs page demonstrates this nicely.


text:
Q: Understanding why a $p$-value is too small I have a data set with counts of particles, and I want to test if they follow a distribution. For a certain species, I make the $\chi^2$-test, and everything seems reasonable, finding a $p$-value of $p=0.75$, which I interpret as meaning that my null hypothesis (in this case, that the data follows a Skellam distribution) is not rejected. In the plot below, the histogram is the binned data and the curve is the expected distribution.

However, when I do the same for another type of particle, I find the $p$-value of $p=2\times 10^{-13}$, but the plot suggests to me that the data does follow the Skellam distribution:

I read in some places that a large sample may cause this, but my sample size is $3\times10^4$, and as it didn't affect the first type of particles, I'm assuming that is not the problem. What am I misunderstanding here? Does it really mean that I should reject the null hypothesis?
A follow-up question: which test should I use to check the goodness-of-fit, in this case? For completeness, the statistic is $\chi^2=19.8$ and $\chi^2=220$, respectively.

A: A few general thoughts:

*

*It's very rare that real-world data follow a specific distribution exactly. This doesn't stop us from using a specific distribution as a model in order to answer questions. A model doesn't have to be perfect, but good enough for the purpose.

*With such a huge sample size, even tiny deviations from a Skellam distribution will result in very small p-values. This is just a result of the consistency of the tests. The power to detect smaller and smaller deviations increases with increasing sample size (see also here). In the second case, a p-value of $2\times 10^{-13}$ means that there is a lot of evidence against the null hypothesis that the data come from a Skellam distribution. Specifically, there are $-\log_{2}(2\times 10^{-13})\approx 42.19$ bits of information agains the test hypothesis (this is called the $S$-value).

*A failure to reject the null hypothesis does not mean that it is true. It means that there is not enough evidence to reject the notion that your data are compatible with a Skellam distribution with a high enough confidence. There may be infinitely many distributions other than the Skellam distribution that are compatible with your data.

*Histograms are suboptimal to check the agreement between the data and a specified distribution. I recommend to use Q-Q-plots instead (more information here). Another very useful visualization tool is the hanging rootogram. A good paper on this can be found here. I show how to apply a hanging rootogram to check the fit to a Poisson distribution in this answer.

In the light of the points above, here are some questions that you might find useful to ask yourself:

*

*What's your specific goal? Why do you want to show that the data are following a Skellam distribution?

*How large do the deviations from a Skellam distribution have to be in order for you to deem the model of a Skellam distribution unsuitable for the task?

Both of these questions require subject matter knowledge which I don't have.


text:
Q: Azure DevOps for ARM: Task failed while initializing. Error: Input required: ConnectedServiceName" I'm trying to deploy simple ARM, but failing. What could be wrong?
I created "AzureRmPipeline-conn" from "ARM template deployment" feature.
I get error: "##[error]Error: Task failed while initializing. Error: Input required: ConnectedServiceName"
//Example
 //https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/deployment-tutorial-
 pipeline
//YML
- task: AzureResourceGroupDeployment@2
  inputs:
    deploymentScope: 'Resource Group'
    azureResourceManagerConnection: 'AzureRmPipeline-conn'
    subscriptionId: '1111753a-501e-4e46-9aff-6120ed56333'
    action: 'Create Or Update Resource Group'
    resourceGroupName: 'KensTestRG'
    location: 'North Europe'
    templateLocation: 'Linked artifact'
    csmFile: '\ARMTemplates\CreateSQLServerARM\azuredeploy.json'
    deploymentMode: 'Incremental'

A: You need to define a service connection. Pleae take a look here and then use name of this connection in this task.
Instead of
azureResourceManagerConnection: 'AzureRmPipeline-conn'
subscriptionId: '1111753a-501e-4e46-9aff-6120ed56333'

you should use:
ConnectedServiceName: 'AzureRmPipeline-conn'
subscriptionName: '1111753a-501e-4e46-9aff-6120ed56333'

I'm not sure if values gievn in your example are correct.

A: I was having this issue because I was passing the service connection name as a pipeline variable, named azureSubscription, but keeping its value secret. It started working when I stopped hiding it. The code I am using for the deployment of an Azure Web App is the following:
- task: AzureResourceGroupDeployment@2
  inputs:
    azureSubscription: $(azureSubscription)
    action: 'Create Or Update Resource Group'
    resourceGroupName: $(resourceGroupName)
    location: $(location)
    templateLocation: 'Linked artifact'
    csmFile: 'ARM\Templates\webapp.template.json'
    csmParametersFile: 'ARM\parameters\webapp.parameters.json'
    deploymentMode: $(deploymentMode)


text:
Q: Wordpress portfolio jumps strangely in Firefox http://www.moef.dk/cases/
Anybody know why this looks so weird in Firefox, when the page looks fine in Safari and Chrome? Any help is really appreciated!
/ Soren

A: Remove float left from this class.
        .container .column, .container .columns {
             float: left;
        }


text:
Q: How to record sound of a key press on iphone? I am developing an application in which I want to record the sound of a piano key press. I'm not able to find anything relevant on the internet which helps.
Can anybody share the code or any link which shows how to record the data of the piano key press, store it somewhere in memory and then play it again?
or
If anybody knows how to get the key press event of the keyboard and record it, that would also be appreciated.
Thanks,
Mishal

A: It sounds like your particular need does not involve MIDI or capturing notes from a digital piano, if I am reading correctly. You want just the audio sound of a piano, to play back on an iPhone app?
A few questions/thoughts:
First, do you just need one note/sound? If so you should be able to easily find a sound file that is to your liking on a site that sells sound samples. I myself use sounddogs.com for various odd projects.
Next, what sort of code do you need to play the sound? What programming language are you developing the app in and how do you trigger the sound playback? These details will be helpful in giving you some ideas.
Finally, if the main obstacle is just finding and recording the sound, this question may be better moved to superuser.com since that site deals more with general computer questions, media, and technology. (StackOverflow is focused strictly on programming.)


text:
Q: How to set TabStrip on the top in Bottom tabs with drawables in android I am developing a sample application for tablets using android 4.0. This application has no title bar/action bar and have full screen mode.
In this app I used Tabwidgets and sets the tabs on the bottom. Everything is running fine.
Now I want to following thing on tabstrips:

*

*Remove the bottom tab strip from the tabs

*Add the tab strips on the top of the tabs (Upward direction)

*Want to set a drawable (small indicator) on the tab strip on top

*Want to add moving effect on this drawables from last selected tabs to current tab  smoothly.

My main.xml is :
<TabHost
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_weight="1" />

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_weight="0"/>
        </LinearLayout>
</TabHost>

My current tabs look like :

But I want to look my tabs like as:

I have tried a lot of things but did not get a proper solution. Please guide me.


text:
Q: Error plotting data from netcdf file "increasing x y values expected" I want to plot sea surface temperature data from a regular grid but can't find the proper way to do it. My data comes in nc format
and can be downloaded from http://www.nodc.noaa.gov/SatelliteData/pathfinder4km/
I use this R code to access data but the problem appears when trying to plot
library("ncdf")
download.file("ftp://ftp.nodc.noaa.gov/pub/data.nodc/pathfinder/Version5.2/2003/20030715000715-NODC-L3C_GHRSST-SSTskin-AVHRR_Pathfinder-PFV5.2_NOAA17_G_2003196_night-v02.0-fv02.0.nc", destfile="sst.nc")
data=open.ncdf("sst.nc")
x <- get.var.ncdf(data,"lon")
y <- get.var.ncdf(data,"lat")
sst=get.var.ncdf(data,"sea_surface_temperature")

filled.contour(x,y,sst, color = terrain.colors, asp = 1)

And then get this error message

Error en filled.contour(x, y, sst, color = terrain.colors, asp = 1) :
  increasing 'x' and 'y' values expected

I think the problem comes from y coordinate, latitude runs from 90 to -90. I've seen some questions on stackoverflow in creating a new grid with akima
package but it should not be necessary in this case.
Here you can find a summary of data file
http://ubuntuone.com/1mIdYVqoePn24gKQbtXy7K
Thanks in advance for your help
SOLVED
Thanks to Paul Hiemstra
The point was not read lat-lon values from data set but to know the i,j coordinates of data points in the matrix and then select the geographic area I want to plot. Following are the commands that work for me:
library("ncdf")
download.file("ftp://ftp.nodc.noaa.gov/pub/data.nodc/pathfinder/Version5.2/2003/20030715000715-NODC-L3C_GHRSST-SSTskin-AVHRR_Pathfinder-PFV5.2_NOAA17_G_2003196_night-v02.0-fv02.0.nc", destfile="sst.nc")
data=open.ncdf("sst.nc")
sst=get.var.ncdf(data,"sea_surface_temperature")
x = seq(1, 8640, length.out = nrow(sst))         # Matrix dimension 8640x4320
y = seq(1, 4320, length.out = ncol(sst))

sst1 <- sst[c(1000:1500),c(1000:1500)]           # Subsetting a region
x = seq(1, 500, length.out = nrow(sst1))
y = seq(1, 500, length.out = ncol(sst1))

png(filename="sst.png",width=800,height=600,bg="white")
filled.contour(x,y,sst1, color = terrain.colors, asp = 1)
dev.off()

Now I have to figure out how to label the plot with longtiude and latitude at x-y coordinates.

A: Although my question was solved with the help of Paul Hiemstra I've still investigated on plotting my netcdf data and found another thread in Stackoverflow that has also helped me. It uses image instead of filled.contour.
You can find the thread at The variable from a netcdf file comes out flipped
Now, this is the code I am using to plot SST data:
library("ncdf")
download.file("ftp://ftp.nodc.noaa.gov/pub/data.nodc/pathfinder/Version5.2/2000/20000107010122-NODC-L3C_GHRSST-SSTskin-AVHRR_Pathfinder-PFV5.2_NOAA14_G_2000007_night-v02.0-fv01.0.nc", destfile="sst.nc")
data=open.ncdf("sst.nc")

sst=get.var.ncdf(data,"sea_surface_temperature")
lon=get.var.ncdf(data,"lon")
lat=get.var.ncdf(data,"lat")

data$dim$lon$vals -> lon
data$dim$lat$vals -> lat
lat <- rev(lat)
sst <- sst[,ncol(sst):1]
png(filename="sst2.png",width=1215,height=607,bg="white")
image(lon, lat, sst, zlim=c(270,320), col = heat.colors(37))
library("sp", lib.loc="/usr/lib/R/site-library")
library("maptools", lib.loc="/usr/lib/R/site-library")
data(wrld_simpl)
plot(wrld_simpl, add = TRUE)
dev.off()

that leads to this image:

A: The problem is probably the following. Your x and y variables are of the same size of sst, i.e. they provide maps of x and y coordinates. What the filled_contour function needs is not these maps, but more simply the x and y coordinates associated with the rows and columns in sst with increasing x values.


text:
Q: Where to find the source code of built-in map() function in Python When I jump to definition of map() function in PyCharm, I get a code with only pass-construction in it and no code which makes something. I tried to find it in other places, but it seems like I don't have any idea of where it can be. Please, help!

A: Builtin functions are not written in Python, but rather in C. What you see in you IDE is only a placeholder, it is of course not the real implementation.
Here you can find the cPython implementation of map.
You will notice that since map is a class, its method are defined beforehand. By exemple, if you are interested in map.__next__, you look for the definition. map_next. After those method definitions, you can find the allocation of  the map type.


text:
Q: Using HTML::Template within a value attribute my question is how would I use an HTML::Template tag inside a value of form field to change that field. For example

          File:

        <input type="file" name="upload" value= style="width:400px">

          File Name:

            <input type="text" name="filename" style="width:400px" value=""  >

          Title:

            <input type="text" name="title" style="width:400px" value="" />

          Date:

            <input type="text" name="date" style="width:400px" value="" />

           <input type="button" value="Cancel">
           <input type="submit" name="action" value="Upload" />

I want the value to have a <TMPL_VAR> variable in it.

A: You use it the same way you'd use a template variable anywhere else:
<input type="text" name="date" style="width:400px" value="<TMPL_VAR NAME=date>" />

Yeah, it's ugly and it breaks your HTML validator. Which is one of the many reasons why I like Template Toolkit better.


text:
Q: What can we infer about the wave-function from the fact that the expectation value of momentum is real? The expectation value of momentum is calculated in Quantum Mechanics (QM) as follows:
$$
\langle p\rangle = \frac{\hbar}{i} \int_{-\infty}^{+\infty} \Psi^*(x,t) \frac{\partial}{\partial x} \Psi(x,t) \,dx
$$
The expectation value of momentum must be real because measured values of momentum in similarly prepared states are real and the average or expectation value of real numbers is of course real.
This means that the above definite integral must have a factor of $i$ to cancel the $i$ outside to give a real expectation value for momentum.
My question: What property of the wave function can be deduced from the fact that the integral of the product of $\Psi$ and the partial space derivative of $\Psi$ over all of space is purely imaginary?

A: It tells you nothing about wavefunctions, since the momentum operator is Hermitian. The expectation value of a Hermitian operator is always real, since
$$ \langle \psi \vert A \vert \psi\rangle^\ast = \langle \psi\vert A^\dagger  \vert\psi\rangle \overset{A=A^\dagger}{=} \langle \psi \vert A \vert \psi\rangle.$$
If you find some wavefunction for which the quantity is naively not real, then you have run into one of the subtleties of the momentum operator on the space of wavefunctions $L^2(\mathbb{R})$, e.g. that it is only densely defined and not on wavefunctions that do not vanish at infinity, since the vanishing of a boundary term is crucial for its Hermiticity.


text:
Q: Use sequelize-cli to specify multiple constraints in the model:generate command Following the documentation to generate model and migration at the same time, we can use:
npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string
This generates a model file.js with:
    User.init({
        firstName: DataTypes.STRING,
        lastName: DataTypes.STRING,
        email: DataTypes.STRING
    }

But I want to specify additional condition/properties, like:
User.init({
    user_id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,   <====
        primaryKey: true,   <====
      },
    firstName: {
      type: DataTypes.STRING,
      allowNull: false   <====
    },
    lastName: {
      type: DataTypes.STRING
    }
  }

Is there a way for me to specify additional params than just the datatype... like primaryKey, autoIncrement, or allowNull?
There is already a question here, but no working answer.
Thanks in advance


text:
Q: Which Date to use while generating Azure Bill programmatically using Billing APIs There are two types of times with the Chargeback reporting data:

*

*Processing Date: Also known as Reported date. It is the Date on
which the data is reported in the Azure system.

*Usage Start and End Date: This is the actual date when the resource was used in Azure.

E.g. You create a VM in Azure and it was up and running for 5 hours on 8th of April until midnight. Now only 2 of those hours are reported on 8th in Azure. And the remaining 3 hours are reported on 9th of April.
So in this case:

*

*For first 2 hours, the Processing or Reporting date is 8th April. And
the usage date is also 8th April.

*For the remaining 3 hours: the Processing or Reporting date is 9th April. But the usage date is still 8th April as the actual usage of those hours happened on 8th April.

Now when generating the bill there is no documentation which dates to use. I have three options and their combinations:

*

*Processing or Reported Date

*Usage Start Date

*Usage End Date

Theoretically, it makes sense to generate the bill using Usage dates. But when I pull the actual bill from https://account.windowsazure.com manually and compare the same to the one generated via APIs, it seems that the bill is being generated in Azure by Reported Date instead.
Ask: Can you please check and confirm that I should be using the Reported Date while generating the billing reports?

A: I believe the documentation is pretty explicit about this.
The request URL to fetch the data is:

_https://management.azure.com/subscriptions/{subscription-Id}/providers/Microsoft.Commerce/UsageAggregates?api-version={api-version}&reportedStartTime={dateTimeOffset-value}&reportedEndTime={dateTimeOffset-value}&aggregationGranularity={granularity-value}&showDetails={showdetail-boolean-Value}&continuationToken={token-value}

Which means when fetching the data, you should use Reported Date/Time.
Here's the response body you get:
{
    "value": [
        {
            "id": "/subscriptions/f68815e6-3c41-45ef-bbd8-5f83303c396b/providers/Microsoft.Commerce/UsageAggregates/Daily_BRSDF_20140501_0000",
            "name": "Daily_BRSDF_20140501_0000",
            "type": "Microsoft.Commerce/UsageAggregate",
            "properties": {
                "subscriptionId": "f68815e6-3c41-45ef-bbd8-5f83303c396b",
                "usageStartTime": "2015-03-03T00:00:00+00:00",
                "usageEndTime": "2015-03-04T00:00:00+00:00",
                "meterName": "Standard IO – Page Blob/Disk (GB)",
                "meterCategory": "Storage",
                "meterSubCategory": "Geo Redundant",
                "unit": "GB",
                "meterId": "0e9d0c9b-ab6d-4312-9c7e-3794e22af9c4",
                "infoFields": {
                },
                "quantity": 0.057865
            }
        },
…

Which returns you usage dates.
One thing that you need to realize is that there're some delays as to when the data is reported. So usage data for 8th could be reported on 8th, 9th, 10th or even later. Please read the Frequently Asked Questions to understand more about these dates.

A: I believe you can use Reported Date for generating the bill too. Afaik Microsoft billing generated is also based on the Reporting Date. I also tested this in my subscription for multiple months vs the data from billing API and found this to be true.


text:
Q: Run batch files according to the state of my explorer.exe in JAVA I want to run some batch files according to the explorer.exe state.That is, i want to run a batch file when the desktop is active, and i wanna run another batch file if a drive in My Computer is opened and another different batch file if a folder inside that drive is opened.I wonder if there is anyway to get information necessary to get this done?..
Thanx in advance..


text:
Q: can we initialize array by calling parameterized constructor How to initialize an array of objects by calling the parameterized constructor of the class
Example:
class a
{
    int val;

    //def
    public a()
    {
    }

    //with param
    public a(int value)
    {
        val = value;
    }
}

How to initialize a dynamic array of the above class by using its constructor
eg:
a[] dyArray = new a[size];  // how to call constructor to initialize a value
                            // other than looping each element and initialize
                            // it? say, with value 10;

Is there any other standard way to do this?

A: If you can use a generic list instead you can create the collection and initialise a value:
List<a> aList = new List<a>
{
    new a(10)
};

https://msdn.microsoft.com/en-us/library/bb384062.aspx

A: try this one:
 a[] dyArray = new a[]{
     new a(1),
     new a(2)
 };

A: The good old way is like this:
a** dyn_arr_ptr = new a*[size];
for (i = 0; i < size; ++i) {
  dyn_arr_ptr[i] = new a(10); // or it could "new a(i)" more flexibility here in parameter value per instance
}

A: How about this?
var darray = (new int[dzise]).Select(x=>new a(10)).ToArray();


text:
Q: How to get ATAPI SMART Data according to disks using C#/.NET I want to write an application that monitors the status of a disk or more disks in a system.
I found that i can manage one disk via WMI "root/wmi" and the MSStorageDriver and query these for the actual values (data and threshold), followed below link
 - http://wutils.com/wmi/root/wmi/msstoragedriver_atapismartdata/
So far, it worked well  :-)
However, I have not managed multiple disks until now. I don't know how to get SMART Data according to disks
Could anyone help me resolve this issue?
Many thanks,
Quyen

A: I tried and succeed, I would like to share the answers for this issue

*

*Get PNPDeviceID

*Get InstanceName of PNPDevice accordingly

*Get S.M.A.R.T data from InstanceName

Example code
public string   PNPDeviceID
    {
        set
        {
            this.m_PNPDeviceID = value;
            this.InstanceName = null;
            this.QueryObjATAPISmartData = null;

            SearcherPnPDeviceId = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSWmi_PnPDeviceId");
            foreach (ManagementObject queryObj in SearcherPnPDeviceId.Get())
            {
                if (queryObj["PNPDeviceID"] != null)
                {
                    if (this.PNPDeviceID.ToUpper() == queryObj.GetPropertyValue("PNPDeviceID").ToString().ToUpper())
                    {
                        if (queryObj["InstanceName"] != null)
                        {
                            this.InstanceName = queryObj["InstanceName"].ToString();
                            break;
                        }
                    }
                }
            }

            if (this.InstanceName != null)
            {

                SearcherATAPISmartData = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSStorageDriver_ATAPISmartData");
                foreach (ManagementObject queryObj in SearcherATAPISmartData.Get())
                {
                    if (queryObj["InstanceName"] != null)
                    {
                        if (this.InstanceName.ToUpper() != queryObj.GetPropertyValue("InstanceName").ToString().ToUpper())
                        {
                            continue;
                        }
                    }
                    this.QueryObjATAPISmartData  = queryObj;
                    break;
                }
      }

}
After that, you could get any properties of QueryObjATAPISmartData
Regards,
Quyen


text:
Q: Openlayers with google map layer - points zoom before the map? I'm using OpenLayers 2 to display a few points on a map. When I use a Google map layer and zoom in or out, the points zoom in/out before the map layer moves creating a strange effect.
var google_terrain = new OpenLayers.Layer.Google("Google Terrain",
    {type: google.maps.MapTypeId.TERRAIN}
);

Here is an example of the problem: jsfiddle
By contrast, a Bing map layer behaves as I would expect and when zooming in/out. The points and the map zoom at the same time. Can anyone shed any light on this for me?

A: This is common problem happening for one using OpenLayers with Google Maps.
To resolve this issue change initialization of your map with below line.
var map = new OpenLayers.Map('map', { zoomMethod:null });

adding zoomMethod:null disables zoom effect applied to your feature layer.
Please refer updated jsFiddle in which zoom is working properly.
I hope this helps you.


text:
Q: Enabling two-way communication between two classes So I have a custom view touchableView inside a ViewController.
touchableView informs ViewController of changes in its properties through a delegate protocol  (ViewController being the delegate).
What is the best method to change properties of touchableView from ViewController (so the other way around)?
Is there a way to create a two-way delegate relationship between two classes?

A: Simply:
Assuming that you are already have touchableView instance in the ViewController, you should be able to set -or get-/call its properties and methods.
For instance, assume that you have the following method in touchableView class:
class func fromNib() -> TouchableView {
    return Bundle.main.loadNibNamed(String(describing: self), owner: nil, options: nil)![0] as! TouchableView
}

You should simply be able to:
let touchableView = TouchableView.fromNib()

thus:
// for example
touchableView.myProperty = "Hello"

I assumed that TouchableView has a string property called myProperty...

Remark:
For some reason, I suggest to implement some of property observers in TouchableView:

Property observers observe and respond to changes in a property's
  value. Property observers are called every time a property's value is
  set, even if the new value is the same as the property's current
  value.

They might be -somehow- useful to be implemented in your custom class. For clarity, let's consider -for instance- that if editing the value of myProperty should be effecting the background color of the view, it might be implemented as:
var myProperty: String = "Initial Value" {
    willSet {
        print("About to set value to:  \(newValue)")
    }
    didSet {
        backgroundColor = UIColor.red
    }
}

Further Reading:
If you are looking for an advanced approach for two way bindings (Implementing MVVM), you might want to check this article.
I would also suggest to take a look at some frameworks that will be so helpful for such an approach, such as RxSwift, for a more simple framework, you might want to check ReactiveKit/Bond.


text:
Q: Input decoravel para determinada funcao Eu sempre tive essa duvida, entretanto agora necessito disso. Existe algum script free ou algum site, ou simplesmente um nome desses BOX onde podemos moldar a mensagem com negrito, links, citacoes codes etc? como esse aqui que estou usando pra digitar..

A: Sim, existem editores de texto gratuitos para utilizar em seus projetos.
Um deles é o CKeditor, um editor de texto open source e gratuito. Dê uma olhada na documentação e veja se atende às suas necessidades.


text:
Q: FAST Search JDBC Connector crawling/indexing multiple docs we configured FAST JDBC Connector with Oracle database for crawling/indexing, as far as I know that JDBC connector doesnt support documents (like PDF, Word, Excel). We have another system using this Oracle DB and store items, and we may have multiple docs in one item and now need to crawl/index in FAST.
We create a python script to do that and using getPath and into Data property, however we can only get one document not all docs. How to write the python stage in order to support it?
Thank you.

A: I would create a custom bcs connector handling that - what you are trying to do is definitely possible. See this example as a starter: http://msdn.microsoft.com/en-us/library/office/ff625800(v=office.14).aspx


text:
Q: Recursive Function that divides two integers and returns result and remainder I am trying to create a recursive function that divides two integers n and m and then displays the result and the remainder of the division.
Basicly I created two separate functions which do exactly what I want:
let rec div1 (n: int, m: int): int =
    if n<m then n else div1(n-m, m)
printfn "Remainder: %i" (div1(5,5))

let rec div2 (n: int, m: int): int =
    if n<m then 0 else 1+div2(n-m, m)
printfn "Result: %i" (div2(5,5))

The thing is, I want to do them both at once, I mean in one function like let rec div12 (n: int) (m : int): int * int = , not in two separate.
I am not sure how exactly this would work on F#.

A: A function may return more than just a number. For example, a function may return a tuple of two numbers:
let f x = (x, x+5)
f 5
> (5, 10)

Further, you can destructure return value of such a function in a similar way:
let (x, y) = f 5
x
> 5
y
> 10

Now we can use this to have our div+mod function return two results - remainder and quotient:
let rec divMod n m =
    if n < m
    then
      (n, 0)
    else
      let (remainder, quotient) = divMod (n-m) m
      (remainder, quotient + 1)

Note how this function simply combines results of your div1 and div2 in a tuple, then destructures them after the recursive call.
divMod 5 5
> (0, 1)
divMod 5 3
> (2, 1)
divMod 7 3
> (1, 2)

Also note that I'm using curried parameters divMod n m instead of tupled parameters as you do div1 (n, m). Ultimately this is a matter of taste, but as a pro tip, I'd like to point out that curried parameters turn out to be much more useful in practice.


text:
Q: Simple queries, locks after migration After database migration from self-hosted PostgreSQL instance to Amazon RDS we are encountering some weird issues with queries to 12M rows table.
Queries which were working before, now are locking with wait_event_type=LWLockTranche and wait_event=buffer_io (even the simplest queries without any JOINs). All INDEXes and Execution Plans seems to be fine. Explain Analyze didn't show anything weird except the query execution time.
Example query:
explain (verbose, buffers, analyze) SELECT * FROM "products_product" WHERE ("products_product"."category_id" = 43);

A result from self-hosted PostgreSQL:
Index Scan using products_product_b583a629 on public.products_product  (cost=0.43..5256.40 rows=5667 width=1758) (actual time=24.372..298.822 rows=29342 loops=1)
Output: id, title, description, image_path, image_source_url, website_source, date_created, date_updated, afi_url, afi_price_currency, afi_recognize_id, afi_price, afi_old_price_currency,  meta_link, afi_old_price, meta_published, meta_admin_note, afi_id, brand_id, category_id, retailer_id, afi_promotion, afi_stock, search_vector, original_category_id, search_vector_pl, title
_pl, description_pl, owner_id
Index Cond: (products_product.category_id = 43)
Buffers: shared hit=71 read=22261
I/O Timings: read=233.266
Planning time: 0.271 ms
Execution time: 310.205 ms

and result from Amazon RDS for the same query:
Index Scan using products_product_b583a629 on public.products_product  (cost=0.43..27905.30 rows=30563 width=1753) (actual time=26.084..179652.029 rows=29342 loops=1)
Output: id, title, description, image_path, image_source_url, website_source, date_created, date_updated, afi_url, afi_price_currency, afi_recognize_id, afi_price, afi_old_price_currency, meta_link, afi_old_price, meta_published, meta_admin_note, afi_id, brand_id, category_id, retailer_id, afi_promotion, afi_stock, search_vector, original_category_id, search_vector_pl, title_pl, description_pl, owner_id
Index Cond: (products_product.category_id = 43)
Buffers: shared hit=2532 read=19856
Planning time: 0.093 ms
Execution time: 179665.121 ms

RDS: CPU usage stable at 20-30% level, DB Connections 2-40, Free memory 50% (3GB), Write IOPS 1-10, Read IOPS 650-750, Free storage 100GB.
What can cause this difference? What can we check more?

A: Reference this, https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html
AWS caps the iops depends on your storage type. If it's gp2, you get 3 iops per GB of storage. If your index is a type int, with 12M records, the index size is probably at 150MB. At 700 iops, it'd take a while even with no other sessions running. If you got other sessions taking up the iops, you get buffer_io wait.


text:
Q: Flip image in jQuery I have a collection of small images (bellow "Some examples" in the left column ) I would like to flip one at the time.
I imagine that they flip and a new image is shown (like flipping a card).
Is there a jQuery plug in for this, or can I do it with ordinary jQuery?
Link to site
//Johan

A: Flip!: http://lab.smashup.it/flip/
Edit: I also really like the jQuery Cycle plugin: http://jquery.malsup.com/cycle/
It does loads of transitions so in your case it might be overkill, but just a tip if you want other cool effects.


text:
Q: How to spin up VM with transferred zfs image from bhyve on KVM? I have transferred a snapshot of a VM from bhyve and this is what I have on KVM host:
NAME USED AVAIL REFER MOUNTPOINT
zfs-pool 50.4G 10.4T 170K /zfs-pool
zfs-pool/vm-test 50.4G 10.4T 40.4G -

How can I recreate the VM with this snapshot? Should I mount the snapshot first and use it as disk? Or create a VM and rollback from this snapshot?


text:
Q: How do accumulators work in Haskell? Hello i am trying to understand how do accumulators work by creating the following method :
It receives a number and it creates a tuple of: (sum [0..nr], [0..nr]). For instance, given 4, it should return (10, [0,1,2,3,4]).
This is the code I have:
accu :: Int -> (Int, [Int])
accu 0  = (0, [0])
accu nr = go (0, []) nr where   --I do not get this line, mainly the first argument
            go (s,ls) 0  = (s, 0:ls)
            go (s,ls) nr = go (s+nr, nr:ls) (nr-1)

I do not understand how the accumulator changes its value, since it is not a function, and thus shouldn't it be immutable? Shouldn't it be like a constant in my case?

A: go is a function that is locally defined using the where keyword and then used directly in the accu function. Have a look here:
http://learnyouahaskell.com/syntax-in-functions#where
That means the accumulator does not really change, it is just a different accumulator in each recursive call to the go function. The last line will recursively call the go function with a new accumulator value.

A: Why not do it simply.
(\n -> (sum [0..n], [0..n])) 4
(10,[0,1,2,3,4])

Or this is cleaner but longer.
(\n -> (\l -> (sum l, l)) [0..n]) 5
(15,[0,1,2,3,4,5])


text:
Q: Windows 7: Using schtasks to run on a WinServer2003 I need to run several scheduled tasks remotely on a WinServer2003 machine. When my OS was WinXP-32 it worked quite fine with a command like "schtasks /run /s \\xxx.xxx.xxx.xxx /tn ScheduledTaskName".
Now I upgraded my OS to Win7-64 and I always get errors like "Host not found" while with a WinXP system the remote call still works fine.
I have the credentials for a quite powerful user on the server. I can explore its file System without a special login and the command "schtasks /query /s \\xxx.xxx.xxx.xxx" lists all the scheduled tasks on the server correctly.

A: I found a workaround for this problem. I copied an old version of schtasks.exe (Windows XP 32bit) to my System and used it for the call.
It worked. Weird. Bug or feature?


text:
Q: Custom module change `foreach` to chose what to display I have a custom module for batch order in my magento application. I have created another store view and the batch order form will need to have different products in each store.
Here is part of the code that's responsible for the tabs is my order form. The content of the tab can be set in the admin panel.
Updated:
// Gets the block data.
$groups = $this->getGroups();
$mySelectedGroups = array('2', '4'); // this is the group entity_id from database

                    <?php
                    // Loops through the groups to get their name as nav heading.
                    // The first iteration will activate the tab for the first group.
                    $navI = 1;
                    foreach ($groups as $group) :
                        if (in_array($group, $mySelectedGroups))
                        if ($group->hasProducts()) { ?>
                            <li <?php if ($navI == 1) { ?> class="active" <?php } ?>>
                                <a href="#<?php echo $group->getId(); ?>"
                                   data-toggle="tab">
                                    <?php echo $group->getName(); ?>
                                     <i style="display: none;" class="text-danger error_glyph_<?php echo $group->getId(); ?> fa fa-exclamation-circle" aria-hidden="true">

                            <?php $navI++;
                        } endforeach; ?>

It pulls all the groups of products created in the admin. Can you tell me a way of calling them here 1 by 1 instead of bulk action?
I will then be able to set them manually for each store view.
Update:
That's the getData() for $groups:

It doesn't look like a normal array...

That's what the original looks like.

Here is the back end setting for it.

A: I don't know if this is exactly what you want but if you want to set the groups manually, you have to put them in an array something like this:
$groups = array('group1', 'group2', ...);

foreach ($groups as $group) :
...

EDIT:
$groups = $this->getGroups(); // your groups
$mySelectedGroups = array('group1', 'group2', ...);

foreach($group as $group) {
    if (in_array($group, $mySelectedGroups)) {
    //...
    }
}

EDIT 2 you have an error in your code
<?php
$groups = $this->getGroups();
$mySelectedGroups = array('1403', '1404', '1405'); // this is the group entity_id from database
?>

    <?php
    $navI = 1;
    foreach ($groups as $group) :
        if (in_array($group, $mySelectedGroups)):
            if ($group->hasProducts()): ?>
                <li <?php if ($navI == 1) { ?> class="active" <?php } ?> >
                    <a href="#<?php echo $group->getId(); ?>"
                       data-toggle="tab">
                        <?php echo $group->getName(); ?>
                         <i style="display: none;" class="text-danger error_glyph_<?php echo $group->getId(); ?> fa fa-exclamation-circle" aria-hidden="true">

                <?php $navI++; ?>
            <?php endif; ?>
        <?php endif; ?>
    <?php endforeach; ?>


text:
Q: Replace import of constant/method by static import in IntelliJ Idea I have a code with some constants in format ClassName.CONSTANT_NAME. I want to quickly replace this by CONSTANT_NAME. But I have not found any efficient way of doing that.
Every time I want to static import something I have to remove class name manually then open static import tooltip which might contain several matches for constant name... It is inefficient.
Is there any quick way of converting an import to a static import? Ideally I would assign a shortcut for this.

A: Put the cursor on the constant (ClassName.CONSTANT_NAME).
Then use the shortcut for the action Show the list of available intention actions.

*

*On windows or Linux:  alt + enter

*On mac os: ⌥⏎
Then select:

*

*Add on demand static import for ....