text:
Q: Evaluating e using limits What algebraic operations can I use on the $RHS$ to show $RHS = LHS$
$$e=\lim_{k\to\infty}\left(\frac{2+\sqrt{3+9k^2}}{3k-1}\right)^k$$

A: Since$$\left( \frac{2+\sqrt{3+9k^2}}{3k-1} \right)^k=e^{k \log \left( \frac{2+\sqrt{3+9k^2}}{3k-1} \right)} $$
it's sufficient to show that
$$\lim_{k \to \infty} k \log \left( \frac{2+\sqrt{3+9k^2}}{3k-1} \right)=1 .$$
We can rewrite this expression as
$$\frac{\log \left(\frac{2+\sqrt{3+9k^2}}{3k-1} \right)}{\frac{1}{k}}, $$
which approaches the indeterminate form $0/0$ as $k \to \infty$. We thus apply L'hôpital's rule, and obtain the equivalent limit
$$\lim_{k \to \infty} \frac{ \frac{3k-1}{2+\sqrt{3+9k^2}} \frac{d}{dk} \left[ \frac{2+\sqrt{3+9k^2}}{3k-1} \right] }{-\frac{1}{k^2}}=\lim_{k \to \infty} -\frac{3 k^2 \left(\frac{2 k}{\sqrt{k^2+\frac{1}{3}}}+1\right)}{1-9 k^2}=1.$$

A: Note the general fact if $a_k \rightarrow a$ then
$$\left(1+\frac{a_k}{k}\right)^k \rightarrow e^a$$ as $k\rightarrow \infty$
So set $$1+\frac{a_k}{k}=\frac{2+\sqrt{3+9k^2}}{3k-1}$$
to get
$$a_k=\frac{k}{3k-1} (3+\sqrt{3+9k^2}-3k)$$
Now $$\sqrt{3+9k^2}-3k=\frac{3}{\sqrt{3+9k^2}+3k}\rightarrow 0$$
Therefore $a_k\rightarrow 1$ and we have the limit.

A: Hint
For large values of $k$, the following Taylor expansion can be built $$\frac{2+\sqrt{3+9k^2}}{3k-1}=1+\frac{1}{k}+\frac{1}{2 k^2}+\frac{1}{6 k^3}+\frac{1}{24 k^4}+\frac{1}{72
   k^5}+O\left(\left(\frac{1}{k}\right)^6\right)$$ So $$\log\Big(\frac{2+\sqrt{3+9k^2}}{3k-1}\Big)=\frac{1}{k}+\frac{1}{180 k^5}+O\left(\left(\frac{1}{k}\right)^6\right)$$


text:
Q: How compatible is CentOS in respect to hardware for desktop systems? I have been tasked with creating a promotional/sales tool for our clients and sales people, (about 8400 users).  It's expected that the tool will be used on office and home systems.
The tool will run in Linux as a live DVD.  So after use, they can go back to windows.  For business reasons this must be done in Linux on a live dvd.  Windows is not an option.
MY question is which distro should be used as the OS if hardware compatibility is the OVERWHELMING concern. in addition to general hardware compatibility, the key compatibility issues are Video cards, sound cards, and network cards.
I was pushing for Ubuntu because I assume that Canonical has focused on hardware compatibility.
I know we are going to get phone calls, but we want to minimize tech support issues and more importantly, we must provide a good experience for our users.  Or the whole project could backfire.
Our contract programmer is pushing for CentOS. Is CentOS EXTREMELY hardware compatible?  As compatible as Ubuntu?
Would you recommend another distro that we have not thought of?

A: I would say CentOS is probably not as hardware compatible as Ubuntu when it comes to recognizing a large array of hardware. Remember that CentOS derives from the Red Hat RHEL commercial product which predominately targets the server market. Ubuntu on the other hand primarily targets the Desktop market.
So I would expect better hardware support overall from Ubuntu for a larger swath of hardware than form CentOS.
Given all that you really need to come up with a minimum set of hardware that your DVD is targeted for and try and test the heck out of it. Also try and have a rough idea of the nature of what you'll be doing with the hardware prior since that will ultimately drive your selection.
For example:

*

*Need high end CPU?

*Video codecs?

*Sound/Audio support?

*Need Adobe Flash?

*Need specific video resolution(s)?

Given my experience I would expect the video to be the deal breaker in this endeavor. In general it's the most problematic thing in setting up a Linux system.

A: To echo and amplify slm if you are looking for highest likelihood of just working, Ubuntu has probably hit more varied desktop configurations than any other considering that DistroWatch's top 2 are Ubuntu and Mint (an Ubuntu derivative).
Yes, getting decent deployment statistics is like reading goat entrails, so the other is arguing from my (singular) personal experience. I've rescued a bunch of systems from "help! my Windows machine is so loaded with crapware that I don't know what to do" by carrying around Ubuntu on my keyring thumbdrive. It just works except for rare problems with old Broadcom WiFi hardware but I don't think any other mainstream distribution does any better.
I'd recommend 12.04 LTS as your base since Quetzal and Raring seem to be leaving some older hardware behind. There are a lot of services (lpr, dns, samba) which I'd take out if trying to make a turnkey demo. And of course, use the x86 architecture as there are ton of 32-bit machines still out there running XP.

A: I agree with slm. CentOS is much more like RHEL with hardware compatibility. Fedora might be a good alternative, using many of the same or similar packages and using the same package manager YUM/RPM. Fedora is also targeted for the desktop so the hardware compatibility is much better.

redpajama_set_name: RedPajamaStackExchange


text:
Q: sed command is not working in shell script when a variable is passed as parameter I have following codes in my shell script
a=$(cat php1.php | grep 'hello')
echo $a
sed -i 's/'"$a"'/world/' php1.php

The variable is getting printed correctly. However when i pass it as parameter to sed command, sed command is not working.
where am i going wrong?

A: Your command works perfectly:
sed -i 's/'"$a"'/world/' php1.php

However, your sed command can use double quotes to expand shell variables automatically. Try this instead:
sed -i "s/$a/world/" php1.php

I may not completely understand what you're trying to accomplish, but if you're trying to replace hello with world (in a rather round-a-bout-way) it looks like you may want to add the -o flag to your grep command:
a=$(grep -o "hello" php1.php)

A: Check the value of $a. I think $a contained some spacial characters.

A: It looks like the intent of your script is to replace all lines in php1.php that contain the word "hello" with the word "world". That'd just be this:
sed -i 's/.*hello.*/world/' php1.php

If you're trying to do something else, let us know what it is and we can help you.


text:
Q: Any way to prevent input via an iOS 3rd party keyboard? I noticed that in some <input> fields, using a 3rd party iOS keyboard like Swype or SwiftKey doesn't always work so well, especially when there are listen events checking for key presses. Is there some way to force the iOS keyboard to switch to the built-in default on certain <input> or <textarea> fields?
Example of something that behaves differently between the iOS keyboard and 3rd party keyboards:
http://jessepollak.github.io/card/
I'd like to point out that the problem lies in the fact that the third party keyboard doesn't trigger keyup, keypress, etc. This is why I'm looking for a way to force the iOS keyboard.

A: Even if there is a way to do this, it would be better to resolve the problem and have the code listen key presses where possible but be able to handle all sorts of input methods such as speech recognition driven input which would produce similar issues. I went through that path with my games and received nothing but complains until I fixed it. Users don't like to be restricted very often.


text:
Q: ElasticSearch : Appending object in existing array of object Field My field mapping:
"Pincode": {

    "analyzer": "standard",
    "type": "string"

},
    "Residence_address": {

        "include_in_parent": true,

           "type": "nested",
            "properties": {
                "address": {
                    "analyzer": "standard",
                    "type": "string"
                },
                "Address_type": {
                    "analyzer": "standard",
                    "type": "string"
                },
                "Pincode": {
                    "analyzer": "standard",
                    "type": "string"
                }
            }

        }

i have data :
    "Residence_address": [

        {
            "address": "safadfsdf",
            "Address_type": "Owned",
            "Pincode": "50005756768674"
        }
        ,
        {
            "address": "Collage of lkj",
            "Address_type": "Rented",
            "Pincode": "419005"
        }

    ],
"Pincode": [

    "11" ,"12"

]

when i insert pincode :
  "Pincode": ["15"]

its working fine .
For normal array fields(Not array of objects) the appending works fine.
but when I want to insert object as :
 "Residence_address": [
                    {
                     "address": "abbbbbb",
                     "Address_type": "bcccccc",
                     "Pincode": "67999999"
                  }
               ]

When i insert it using this code :
      updateRequest.script("ctx._source.Residence_address +=  ADD");
          JSONArray Address = (JSONArray) temp.get("Residence_address");
          i = 0;
          while(i < Address.size()){
                  System.out.println(Address.get(i).toString());
                  updateRequest.addScriptParam("ADD", Address.get(i++).toString());
               }

it gives me error :
org.elasticsearch.index.mapper.MapperParsingException: object mapping [Residence_address] trying to serialize a value with no field associated with it, current value [{"address":"abbbbbb","Address_type":"bcccccc","Pincode":"67999999"}]
    at org.elasticsearch.index.mapper.object.ObjectMapper.serializeValue(ObjectMapper.java:702)
    at org.elasticsearch.index.mapper.object.ObjectMapper.parse(ObjectMapper.java:497)
    at org.elasticsearch.index.mapper.object.ObjectMapper.serializeValue(ObjectMapper.java:706)
    at org.elasticsearch.index.mapper.object.ObjectMapper.serializeNonDynamicArray(ObjectMapper.java:695)
    at org.elasticsearch.index.mapper.object.ObjectMapper.serializeArray(ObjectMapper.java:604)
    at org.elasticsearch.index.mapper.object.ObjectMapper.parse(ObjectMapper.java:489)
    at org.elasticsearch.index.mapper.DocumentMapper.parse(DocumentMapper.java:544)
    at org.elasticsearch.index.mapper.DocumentMapper.parse(DocumentMapper.java:493)
    at org.elasticsearch.index.shard.IndexShard.prepareIndex(IndexShard.java:493)
    at org.elasticsearch.action.index.TransportIndexAction.shardOperationOnPrimary(TransportIndexAction.java:192)
    at org.elasticsearch.action.support.replication.TransportShardReplicationOperationAction$PrimaryPhase.performOnPrimary(TransportShardReplicationOperationAction.java:574)
    at org.elasticsearch.action.support.replication.TransportShardReplicationOperationAction$PrimaryPhase.routeRequestOrPerformLocally(TransportShardReplicationOperationAction.java:444)
    at org.elasticsearch.action.support.replication.TransportShardReplicationOperationAction$PrimaryPhase.doRun(TransportShardReplicationOperationAction.java:370)
    at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:36)
    at org.elasticsearch.action.support.replication.TransportShardReplicationOperationAction.doExecute(TransportShardReplicationOperationAction.java:112)
    at org.elasticsearch.action.index.TransportIndexAction.innerExecute(TransportIndexAction.java:136)
    at org.elasticsearch.action.index.TransportIndexAction.doExecute(TransportIndexAction.java:114)
    at org.elasticsearch.action.index.TransportIndexAction.doExecute(TransportIndexAction.java:63)
    at org.elasticsearch.action.support.TransportAction.execute(TransportAction.java:75)
    at org.elasticsearch.action.update.TransportUpdateAction.shardOperation(TransportUpdateAction.java:217)
    at org.elasticsearch.action.update.TransportUpdateAction.shardOperation(TransportUpdateAction.java:170)
    at org.elasticsearch.action.support.single.instance.TransportInstanceSingleOperationAction$AsyncSingleAction$1.run(TransportInstanceSingleOperationAction.java:187)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

help please.

A: If you have several addresses in Address, you add many parameters with the same parameter name ADD, which will not work.
Try this instead:
      String newAddrs = "";
      JSONArray Address = (JSONArray) temp.get("Residence_address");
      int i = 0;
      while(i < Address.size()){
              newAddrs += "ADD" + i + ( i < Address.size() - 1 ? "," : "");
              updateRequest.addScriptParam("ADD"+i, Address.get(i++));
      }
      updateRequest.script("ctx._source.Residence_address += ["+newAddrs+"]");

So if you have 3 addresses, you will end up with a script that looks like:
ctx._source.Residence_address += [ ADD0, ADD1, ADD2 ]

And you will have three script parameters named ADD0, ADD1, ADD2


text:
Q: using sleep(), I cannot get my values to echo I'm using a sleep function inside of a foreach loop and I'd like to echo the value inside the loop. Why isn't this working? The $test var inside the loop never changes from 0.
foreach($test as $val){
 ob_start();
 echo $test++;
 sleep(1);
 ob_end_flush();
}

A: This works:
foreach ($test as $val)
{
    ob_start();

    echo $val++;

    sleep(1);

    while (ob_get_level() > 0)
    {
        ob_end_flush();
    }

    flush();
}

A: Flush after each echo, instead of using output buffering.


text:
Q: How can I use MySQL on a MAMP set up with CodeIgniter? In my database.php file, I have
$db['default']['hostname'] = 'mylocaldomain:8889';
$db['default']['username'] = 'myusername';
$db['default']['password'] = 'mypassword';
$db['default']['database'] = 'mydb';
$db['default']['dbdriver'] = 'mysql';

I continually, get an error saying that it can't connect. Any help?

A: Try changing:
$db['default']['hostname'] = 'mylocaldomain:8889';

To:
$db['default']['hostname'] = 'localhost';

or:
$db['default']['hostname'] = '127.0.0.1';

I think you're confusing your apache server's host/port with MySQL's host


text:
Q: Need batch file to count the number of files in subdirectories I want a batch file to count the files in sub directories. and save this count to text file.
here is outline what i exactly want:
One folder contain number of folders, so i need to take all the sub-folders file count to text file.
O/p will be:
folder1: 23
folder2: 34
folder3: 12
I think you got my point. please help me.

A: Here's a slightly different method.
The below script iterates over subdirectories of the specified directory, calls DIR /A-D for each of them and extracts the file count from the summary of the DIR's output to display it along with the name of the subdirectory.
@ECHO OFF
SET "rootpath=%~1"
FOR /D %%D IN ("%rootpath%\*") DO (
  FOR /F %%K IN ('DIR /A-D "%%D" 2^>NUL ^| FIND "File(s)" ^|^| ECHO 0') DO (
    ECHO %%D: %%K
  )
)

The path to the parent directory is supposed to come from the command line.
The script only counts files located immediately in the subdirectories. However, it can easily be extended to return the counts of all files stored in the subdirectory trees, if necessary. Here's one way:
@ECHO OFF
SET "rootpath=%~1"
FOR /D %%D IN ("%rootpath%\*") DO (
  SET cnt=0
  FOR /F %%K IN ('DIR /A-D /S "%%D" 2^>NUL ^| FIND "File(s)" ^|^| ECHO 0') DO (
    SET /A cnt+=%%K
  )
  SETLOCAL EnableDelayedExpansion
  ECHO %%D: !cnt!
  ENDLOCAL
)

The modified version works almost the same as the original one, except the output of DIR may now contain multiple summaries. The script extracts the file count from every summary and adds up all the counts to get the total file count in the directory tree. When displaying the results, delayed expansion needs to be enabled in this case, because the total count is being stored in an environment variable (cnt), and environment variables are not evaluated correctly in such cases using "normal" (immediate) expansion.
One other note is that both versions display include the paths when displaying the subdirectory names. If you want names only (as you seem to do based on one of your comments to the other answer), use ECHO %%~nxD: ... instead of ECHO %%D: ....

A: EDIT
I've reworked this.  The example uses two batch files; test.cmd and filecount.cmd
test.cmd iterates directories only, and calls filecount.cmd for each one.
You only explicitly run the test.cmd file, which in turn calls filecount.cmd to count the files, and produces output that looks like the following, which is actual output from my short test just now.  If you do not want the count of the files in the main directory, just omit that line from the first batch file.
.: 7
folder1: 3
folder2: 2
folder3: 5

The example assumes the batch files are just in the same directory that you're counting files in.
test.cmd :
@echo off
setlocal

call filecount .

for /f %%f in ( 'dir /AD /b' ) do (
    call filecount %%f
)

:EOF
endlocal

filecount.cmd :
@echo off
setlocal enabledelayedexpansion

set /a i=0

for /f %%f in ( 'dir /b /A-D %1' ) do (
    set /a i=i+1
    @rem echo %%f !i!
)

echo %1: %i%

:EOF
endlocal

filecount.cmd just echoes to the screen, so you can redirect that output to a file if you want to.
This is a rough-and-ready example, and cannot recursively crawl a directory structure as it sits, but you may be able to mangle it a little bit to accomplish that.  As I said in my original (pre-edit) answer, at some point the batch language just doesn't give you enough power (probably) and you'll need to look at something like vbscript or javascript.


text:
Q: Need to change include path for clang When building with clang, it seems to be using gcc4.4.4 version of include files, while I want it to use newer ones.
[ ~ ] locate move.h
/home/apps/gcc_versions/gcc-4_8_install/include/c++/4.8.3/bits/move.h
/usr/include/c++/4.4.4/bits/move.h
/usr/local/include/c++/4.7.1/bits/move.h

gcc path :
`gcc -print-prog-name=cc1plus` -v
ignoring nonexistent directory "/apps/gcc_versions/gcc-4_8_install/lib/gcc/x86_64-unknown-linux-gnu/4.8.3/../../../../x86_64-unknown-linux-gnu/include"
#include "..." search starts here:
#include <...> search starts here:
 /apps/gcc_versions/gcc-4_8_install/lib/gcc/x86_64-unknown-linux-gnu/4.8.3/../../../../include/c++/4.8.3
 /apps/gcc_versions/gcc-4_8_install/lib/gcc/x86_64-unknown-linux-gnu/4.8.3/../../../../include/c++/4.8.3/x86_64-unknown-linux-gnu
 /apps/gcc_versions/gcc-4_8_install/lib/gcc/x86_64-unknown-linux-gnu/4.8.3/../../../../include/c++/4.8.3/backward
 /apps/gcc_versions/gcc-4_8_install/lib/gcc/x86_64-unknown-linux-gnu/4.8.3/include
 /usr/local/include
 /apps/gcc_versions/gcc-4_8_install/include
 /apps/gcc_versions/gcc-4_8_install/lib/gcc/x86_64-unknown-linux-gnu/4.8.3/include-fixed
 /usr/include
End of search list.

And gcc includes work fine
But with clang it fails
[ ~ ] clang -v
clang version 3.5 (http://llvm.org/git/clang.git 8e674ff884113429b53d23b18409caf67aaec1b7) (http://llvm.org/git/llvm.git 7add5421a686877e0aa87616b92b1f5a85c6feee)
Target: x86_64-unknown-linux-gnu
Thread model: posix
Found candidate GCC installation: /usr/lib/gcc/i686-redhat-linux/4.4.4
Found candidate GCC installation: /usr/lib/gcc/i686-redhat-linux/4.4.7
Found candidate GCC installation: /usr/lib/gcc/x86_64-redhat-linux/4.4.4
Found candidate GCC installation: /usr/lib/gcc/x86_64-redhat-linux/4.4.7
Selected GCC installation: /usr/lib/gcc/x86_64-redhat-linux/4.4.7

I am a newbie at this and please suggest if some info is missing that would help to resolve this.

A: Try compiling as following,
clang++ -isystem /SOMEPATH/gcc-4.9.2/include/c++/4.9.2 -I/SOMEPATH/gcc-4.9.2/include/c++/4.9.2/x86_64-unknown-linux-gnu a.cpp


text:
Q: My dropdown menu doesn't appear using jQuery. Any tips? I wanted to design a dropdown menu. I started to design with just css and this worked well. Then I added jQuery and it worked but a bit glitchy. The slide up animation works fine, and sometimes the slide down too. So I decided to delete the css "animation" and just want to have the jQuery part but now the menu doesn't slide down if I hover over my "Aufgaben".

@import url("https://fonts.googleapis.com/css?family=Roboto:100,300,100italic,300italic");

html, body {
    background: #1c1d26;
}

#header {
    height: 100px;
    left: 0;
    position: fixed;
    top: 0;
    width: 100%;
}

#header img {
    height: 100px;
    left: 0;
    position: absolute;
    top: 0;
    z-index: 999;
}

#header nav{
    width: 100%;
    height: 100px;
    position: absolute;
    background-color: whitesmoke;
    font-family: "Roboto", Helvetica, sans-serif;
}
#header nav ul {
    float: right;
    padding-right: 30px;
}
#header nav ul li{
    float: left;
    list-style: none;
    position: relative;
}
#header nav ul li a{
    color: black;
    display: block;
    font-size: 20px;
    padding: 20px 14px;
    text-decoration: none;
}
#header nav a:hover{
    color: red;
    transition: 0.2s;
}
#header nav ul li ul{
    display: none;
    position: absolute;
    background-color: black;
    opacity: 0.7;;
    padding: 10px;
    border-radius: 0px 0px 4px 4px;
}
#header nav ul li ul li {
    width: 150px;
}
#header nav ul li ul li a{
    padding: 3px 14px;
    color: whitesmoke;
}
<!DOCTYPE html>

    <title>Wilkommen</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
    <link rel="stylesheet" href="main.css" />

Home

                        Aufgaben

HTML Brief

Erste Website

CSS

Tabellen

JavaScript

Raster Layout

Bootstrap

About

Bericht

Kontakt

A: Your jQuery code is working but there is display:none property on #header nav ul li ul that's why it is not visible.
Given below is the correct code.
    $(document).ready(function () {
        $("#dropdown").mouseenter(function () {
            $("#dropdownchild").show().children().slideDown('fast');
        });
        $("#dropdown").mouseleave(function () {
            $("#dropdownchild").hide().children().slideUp('fast');
        });
    });</script>


text:
Q: Sort array by sub-values from JSON data {
   "queue": "RANKED_SOLO_5x5",
   "name": "Taric's Enforcers",
   "entries": [
      {
         "leaguePoints": 502,
         "isFreshBlood": false,
         "isHotStreak": true,
         "rank": "I",
         "leagueName": "Taric's Enforcers",
         "isInactive": false,
         "queueType": "RANKED_SOLO_5x5",
         "isVeteran": true,
         "tier": "CHALLENGER",
         "lastPlayed": -1,
         "playerOrTeamName": "CaliforniaTrlolz",
         "playerOrTeamId": "21059607",
         "wins": 155
      },
      {
         "leaguePoints": 478,
         "isFreshBlood": false,
         "isHotStreak": false,
         "rank": "I",
         "leagueName": "Taric's Enforcers",
         "isInactive": false,
         "queueType": "RANKED_SOLO_5x5",
         "isVeteran": false,
         "tier": "CHALLENGER",
         "lastPlayed": -1,
         "playerOrTeamName": "Knives Millions",
         "playerOrTeamId": "21088719",
         "wins": 116
      },

I have this long json data, and I need it sorted by the "leaguePoints" key value from highest to lowest. I have used json_decode set to true to place the entire json into a PHP-ready associative array, but I cannot get it sorted by the value "leaguePoints". Any help would be greatly appreciated!

A: Something like this?
$array = json_decode($json, true);
usort($array['entries'], function($a, $b) {
    return $b['leaguePoints'] - $a['leaguePoints'];
});

Demo here - http://ideone.com/RTlxc3


text:
Q: Understanding the slope of a line as a rate of change I thought I was confident about what is meant by the slope of a line and how it relates to a rate of change, but I'm having doubts and I'm hoping that someone will be able to help me clear them up.
As I understand it, intuitively the slope of a line is a number $m$ that quantifies the amount it inclines from the horizontal, and its direction. Now, if $y$ is a function of $x$, such that $y=mx+c$, then one can quantify the rate of change in $y$ as one changes $x$ via the the ratio of their coordinate differences, such that $$m=\frac{\Delta y}{\Delta x}$$ Heuristically, can one (hopefully correctly) understand this quantity as follows:
The value of the function $y$ changes by an amount of $\Delta y$ units for every $\Delta x$ units change in $x$. Therefore, the value of $y$ changes by an amount $\frac{\Delta y}{\Delta x}$ units per unit change in x, which is exactly the rate of change in $y$ with respect to $x$, since it quantifies the amount the value of $y$ changes per unit change in $x$.
Would this be a correct understanding at all?

A: Yes, your interpretation of slope is correct. In fact, some people take this interpretation as the definition of the slope of a line.


text:
Q: How to replace duplicate characters in a string - Javascript Have a basic hangman game here. Seems to be working, but I can't get duplicate character guesses to work properly. There are only two words in the bank now, "popcorn" and "apples". The first time you guess "p" for apples it fills in the first p, but won't fill in the second.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hangman!</title>

Hangman

Press a letter to guess.

A: Try
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hangman!</title>

Hangman

Press a letter to guess.

A: You have to call indexOf in a loop, using a second argument.
Example :
var word = "popcorn";
var result = word.indexOf("p");
console.log(result); // Shows "0"

You execute this again, but giving the "result" variable in second argument :
var previousResult = 0;
var word = "popcorn";
// Give as second argument the previous result increased by 1
var result = word.indexOf("p", previousResult + 1);
console.log(result); // Shows "2"

And you can do a while loop logic :
var secretWord = "popcorn";
var letter = "p";
var result = -2; // Initialize to (-1 - 1)
while ((result = secretWord.indexOf(letter, result + 1)) > -1) {
    console.log(result); // Shows "0" then "2"
    /* Do stuff */
}

A: Your current code is looking for the first matching letter exclusively. In one way or another, you'll need a loop to handle duplicate characters.
But I'd suggest another modification: rather than keeping track of the 'progress mask', you should maintain the list of all letters (good or wrong) that have been tried so far.
Having secretWord and progress is not providing enough information to detect wrong letters that have been already tried -- which is probably a feature that you eventually want to have implemented. On the other hand, you can quickly rebuild progress each time you need it by using secretWord and the list of tried letters.
Let's say that tried letters are stored in the letters string. Then progress can be computed either with an explicit loop such as:
// classic for loop
for(i = 0, progress = ''; i < secretWord.length; i++) {
  progress += letters.indexOf(secretWord[i]) == -1 ? '_' : secretWord[i]
}

or an implicit loop such as:
// functional programming
progress = secretWord.split('').map(function(letter) {
  return letters.indexOf(letter) == -1 ? '_' : letter;
}).join('');

or:
// regular expression: replace() with custom callback
progress = secretWord.replace(/./g, function(letter) {
  return letters.indexOf(letter) == -1 ? '_' : letter;
});

or:
// regular expression: replace() without callback
progress = secretWord.replace(new RegExp('[^' + letters + ']', 'g'), '_');

Below is some example code showing the game logic with this approach.

var secretWord = 'apple',
    letters    = '';

function play(letter) {
  if(letters.indexOf(letter) != -1) {
    console.log("You've already tried '" + letter + "' ...");
  }
  else {
    letters += letter;

    if(secretWord.indexOf(letter) == -1) {
      console.log(letter + ' -> wrong!');
    }
    else {
      var progress = secretWord.replace(new RegExp('[^' + letters + ']', 'g'), '_');

      console.log(letter + ' -> ' + progress);

      if(progress == secretWord) {
        console.log('Well done!');
      }
    }
  }
}

play('i');
play('e');
play('p');
play('e');
play('a');
play('l');


text:
Q: at end of list scroll to top I have a large unordered list. When the list has focus I can use the arrow keys to move up and down the list, however when I get to the last link if I press the down arrow again I need it to return focus to the first link. Also if I'm on the first link and press to up arrow I need it to focus the last link.
I have tried playing around with first child and last child, but can't work out how to do it. Any help would be most appreciated.
I have a jsFiddle to play around with.
I've tried quite a few things, here is one example:
$("ul li a:last-child:after")$(this).parents('li').find('a:first-child');

A: As mentioned, highly recommend that your check out the learn.jquery site.
As for a solution:
Building off the answer in Focus on list item on down arrow press, which already will scroll through all the items. What you need to do is check if the currently selected item is the last. jQuery has the .last() method, which, when you give it an array of elements it will return the last one. In that example, it's also putting a class of active onto the currently selected element, so you just need to check if the last item has the class "active", which you can do with:
$("li").last().hasClass("active")
Then, if that's true, you want to select the first item. jQuery also has .first() which does the opposite of what .last() does. So you want to select the first element with:
$("li").first().focus();
Keep in mind, that in the code example when an element is "focused" it gets the class "active" applied to it.
Working solution here: https://jsfiddle.net/38zR3/766/
If you want to do the opposite, when someone gets to the top automatically go to the bottom, just put the opposite code into the section of the "if key up" (which is key code 38).


text:
Q: Fast Hamming distance scoring There is a database with N fixed length strings.
There is a query string of the same length.
The problem is to fetch first k strings from the database that have the smallest Hamming distance to q.
N is small (about 400), strings are long, fixed in length. Database doesn't change, so we can pre-compute indexes. Queries vary strongly, caching and/or pre-computation is not an option. There are lots of them per second. We need always k results, even if k-1 results have match 0 (sorting on Hamming distance and take first k, so locality sensitive hashing and similar approaches won't do). kd-tree and similar space partitioning will probably perform worser than linear search (strings can be very long). BK-tree is currently best choice, but it is still slow and complicated than it needs to be.
It feels like there is an algorithm, which will build an index, which will discard most of the entries in very few steps, leaving k <= t << N entries to compute real Hamming distance.
People suggesting fuzzy string matching based on Levenstein distance - thanks, but the problem is much simpler. Generalized distance metric based approaches (like BK-trees) are good, but maybe there something utilizing the facts described above (small DB/long fixed size strings, simple Hamming distance)
Links, keywords, papers, ideas? =)

A: All hamming distances can be produced in O(K^2/D) using the python code below.
This is faster in some cases than the trivial code which is O(N*K).
Where N is the number of fixed length strings
K is the length of each string
and D is the size of the dictionary.
# DATABASE is a tuple of the strings
# eg. ('asdfjjajwi...', 'hsjsiei...', ...)

# SINGLE is the string you are matching
# eg. 'jfjdkaks...'

SIZE_OF_STRING = 5000
NUMBER_OF_STRINGS = 400
FIRST_K_REQUIRED = 100

def setup_index():
  index = []
  for x in xrange(SIZE_OF_STRING):
    index_dict = {}
    for y in xrange(NUMBER_OF_STRINGS):
      temp = index_dict.get(DATABASE[y][x], [])
      temp.append(y)
      index_dict[DATABASE[y][x]] = temp
    index.append(index_dict)
  return index

index = setup_index()

output = []
for x in xrange(NUMBER_OF_STRINGS):
  output.append([SIZE_OF_STRING, x])

for key, c in enumerate(SINGLE):
  for x in index[key][c]:
    output[x][0] -= 1

output.sort()
print output[:FIRST_K_REQUIRED]

This is a faster method only when SIZE_OF_STRING / DICTIONARY_SIZE < NUMBER_OF_STRINGS.
Hope this helps.

EDIT:
The complexity of the above code is incorrect.
The Hamming Distances can be produced in O(N*K/D) on average.
This is faster in ALL cases than the trivial code which is O(N*K).
Where N is the number of fixed length strings
K is the length of each string
and D is the size of the dictionary.

A: This seems like a task where a Vantage Point (VP tree) might work... since the hamming distance should satisfy the triangle inequality theorem, you should be able to apply it... its also good for identifying k-closest.  I've seen it in image indexing database setups... you might check section 5 of this paper as an example of what I'm talking about (albeit in a different field).

A: From my understanding, BK trees are great for finding all the strings at most K "differences" from the query string. This is a different question than finding the X closest elements. This is probably the reason for the performance problems.
My first inclination is that if speed is really important then the ultimate goal should be to construct a deterministic finite automaton (DFA) to handle this problem. Donald Knuth worked on a related problem and developed a method called Trie which simulates a DFA. This method is especially nice when you have many possible words in the starting dictionary to search through. I think your problem could be an interesting extension of this work. In his original work the goal of the DFA was to try and match an input string with words in the dictionary. I believe the same thing could be done for this problem, but instead returning the K closest items to the query. In essence we are expanding the definition of an accepting state.
Whether this is practical to do depends on the number of accepting states that need to be included. I think the key idea is that of compatible sets. For instance, imagine on a number line that we have the elements 1,2,3,4,5 and for any query want the two closest elements. The element 2 can be in two possible sets (1,2) or (2,3) but 2 can never be a set with 4 or 5. It is late so I am not sure the best way to construct such as DFA at the moment. Seems like there could be a decent paper in the answer.

A: This problem does seem strongly related to the Knuth "trie" algorithm for which there are several highly optimal special solutions - largely related to their cache coherence and CPU instruction assisted acceleration (bitwise trie).
A trie is an excellent solution for a related issue - the similarity of the beginning of the string, which of course makes it a perfect solution for finding the set of minimally unique string solutions from any point starting at the string origin.  The bitwise trie in this case has an average performance of O(1) in practice, worst case O(m) where M is the key length.  Overall its performance for search, insert and delete is the same as a hash, except it doesn't have the collision issues of a pure hashed array.
I bumped into this this question because I was searching for information on bitwise tries and realized their similarity to certain hamming algorithms, so maybe this class of algorithms would be a fruitful area of study for you.  Good luck.


text:
Q: How to get all the arrays lists defined in arrays.xml? There are various arrays defined in arrays.xml. I want to read all the arrays at once and store them. Is there any way to do this?
    <string-array name="ArtDesign">
            <item>Layers</item>
            <item>Tracing</item>
    </string-array>

    <string-array name="Beauty">
            <item>Plastic Surgery Simulation</item>
            <item>SeneStock</item>
            <item>PLASTIC SURGERY BEFORE</item>
    </string-array>

A: For example if you have string array like below:
`
<?xml version="1.0" encoding="utf-8"?>
    <resources>
      <string-array name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
    </string-array>
</resources>

`
Then you can achieve in java class like this:
Resources res = getResources();
    String[] planets = res.getStringArray(R.array.planets_array);

So in your case:
String[] artDesign = getResources.getStringArray(R.array.ArtDesign);
String[] beauty = getResources.getStringArray(R.array.Beauty);

A: You have to create two arraylists
List<String> artDdesignList = Arrays.asList(getResources().getStringArray(R.array.ArtDesign));

List<String> beautyList = Arrays.asList(getResources().getStringArray(R.array.Beauty));

A: When you create an array resource, There is a unique constant generated by android studio to represent that resource which is R.array.*. You need to use reflection to find all the constants in R.array class and retrieve the resources associated with it.

A: After much thinking I think we can read the resource file from InputStreamReader and process the text as we want. By this we can make a hashMap and store all the required values in them.
public static HashMap<String, ArrayList<String>> readRawTextFile(Context ctx, int resId)
{
    InputStream inputStream = ctx.getResources().openRawResource(resId);

    InputStreamReader inputreader = new InputStreamReader(inputStream);
    BufferedReader buffreader = new BufferedReader(inputreader);
    String line;
    StringBuilder text = new StringBuilder();
    ArrayList<String> value = new ArrayList<>();
    HashMap<String,ArrayList<String>> hashMap = new HashMap<>();

    try {
        String key;
        while (( line = buffreader.readLine()) != null) {
            if(line.indexOf("string-array")!=-1){
                key = line; // add logic to refine for the req substring
            } else if(line.indexOf("/string-array"){
                hashMap.add(key, value);
                value = new ArrayList<>();
            } else{
                value.add(line); //add logic to refine for the req string
            }
        }
    } catch (IOException e) {
        return null;
    }
    return hashMap;
}


text:
Q: Loss of precision when converting big double to long I'm trying to convert a BigDouble to a long (as written in the title).
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        double test = Math.pow(Math.sqrt(5)+1,100);
        System.out.println("Double value : " + test);
        System.out.println("Long value : " + (long)test);
        System.out.println("BigInteger value : " + BigDecimal.valueOf(test).toBigInteger());
    }
}

The double value is : 1.0040690755570702E51
The long value is : 9223372036854775807
And the BigInteger value is : 1004069075557070200000000000000000000000000000000000
Isn't there a way I can cast the double value to long without loosing that much precision? (I know the decimals will be truncated, I don't care about decimal's precision).

A: You can perform the math purely with BigDecimal.  Note that the square root of 5 is irrational and can only be approximated with Math.sqrt.
BigDecimal bd = new BigDecimal(Math.sqrt(5));
bd = bd.add(BigDecimal.ONE);
bd = bd.pow(100);
System.out.println(bd);

This will get you the value with decimals.  It eventually terminates because the binary representation of Math.sqrt(5) terminates.
1004069075557070220314035127599869875232877347832248.[encoded data, 4800 characters]

You can remove the portion beyond the decimal point with a call to round.  Use a precision of 52 because there are 52 digits to the left of the decimal point.
bd = bd.round(new MathContext(52, RoundingMode.HALF_EVEN));
System.out.println(bd);

Output:
1004069075557070220314035127599869875232877347832248

EDIT
It is now more precise, but it isn't any more accurate than double precision.  I'm using the Newton-Raphson square root method for BigDecimals to calculate this with better accuracy; there is no sqrt method in Java's BigDecimal.
The bigSqrt method is taken from the SO question I linked above.
MathContext mc = new MathContext(52, RoundingMode.HALF_EVEN);
BigDecimal bd = new BigDecimal(5);
bd = bigSqrt(bd);
bd = bd.add(BigDecimal.ONE);
bd = bd.pow(100, mc);
System.out.println(bd);

Output:
1004069075557066849421378481393742434871238538784961


text:
Q: Cannot get tagged photos In my application I'm trying to display the most recent photos for a specific hashtag. For example, I would like to get let's say the last 50 photos tagged with the word hello. To do this, I've had a look at this link, where they say this is the correct endpoint:
https://api.instagram.com/v1/tags/{tag-name}/media/recent?access_token=ACCESS-TOKEN

But, providing a correct access token (previously obtained with a login by the user) and replacing {tag-name} with the hello, the response from the server is empty:
{"pagination": {"deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead"}, "data": [], "meta": {"code": 200}}

So, no photos are returned.
I can't understand why.

A: If you just need tag photos and no more, you dont have to use api, token etc. You can get https://www.instagram.com/explore/tags/{tag}/?__a=1&max_id={max_id} to receive JSON with array of photos. Parameter &max_id={max_id} is optionally.


text:
Q: Extra backslash in URLs Has anyone noticed that the service started sending the image's URL with an extra backslash before every slash?
e.g.:
"icon": "https:\ /\ /foursquare.com\ /img\ /categories\ /food\ /default.png".
instead of:
https://foursquare.com/img/categories/food/default.png
Is this normal? Thanks in advance.

A: We (foursquare) made the change yesterday to the way we serialize JSON output, but should have done so in a way that won't break any modestly mature JSON handler. We may tweak how we do serialization in the future (always in compliance with the JSON spec) and we recommend you build your system to be robust against future changes.


text:
Q: Simple filter to unhardwrap multiple paragraphs I have many markdown files which are hardwrapped to 80 characters. I would like to copy these to paste into textareas (xclip -sel clipboard < file), but want them to wordwrap normally. This is simple w/o paragraphs - tr "\n" " " < file | xclip -sel clipboard, but turns all text into a run-on paragraph which still requires manual copy-editing.
Is there a short and simple filter using standard *NIX tools (GNU versions are fine) to delete all "\n" except when there are two next to each other? Ideally something I can remember and retype - less than 30 characters with no files. It feels like something sed should be able to do.

A: You could use perl:
For example, using the following hard-wrapped example input file:
$ cat input.txt
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.

$ perl -0777 -p -e 's/(?<!\n)\n/ /g' input.txt
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Or if you still want a blank line between each paragraph:
$ perl -0777 -p -e 's/(?<!\n)\n/ /g; s/\n/\n\n/g' input.txt
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Note: unless the input ends in one or more blank lines, the output won't have a newline on the last line.  If you need that, add ; END {print "\n"} to the end of the script. This will guarantee that the output will end with a newline.
The -0777 option tells perl to "slurp" in its input file all at once, and process it as one long string.
Both versions of the one-liner above use a feature of perl regular expressions called a "zero-width negative lookbehind assertion" - (?<!pattern).  See man perlre and search for "Lookaround Assertions" for details.  In short, (?<!\n)\n matches a newline unless the character before it is another newline - and it does this without actually matching or capturing the preceding character (that's what the "zero-width assertion" means).
Without using negative look behind assertion, you might be tempted to do something like s/[^\n]\n/ /g - but that would end up deleting every character immediately before each newline....which is why the zero-width part of the regex is important, it prevents that.  Another alternative is to use something like s/([^\n])\n/\1 /g which captures the character before the newline and uses it in the replacement - e.g. with GNU sed: sed -E -z 's/([^\n])\n/\1 /g' input.txt but IMO it's better to not match the preceding character at all than to match & delete it and then put it back.
Some other regex engines also support look-around assertions, but they're non-standard so not guaranteed to be supported.

A: tr "\n" " " < file | sed 's/  /\n/g;s/ $//' might work adequately. It requires single-spaced sentences (which some people hate) to re-add the paragraph newlines. It also trims the added space from the final line of the file.


text:
Q: Adding a handler for the first button only There is a div on a page and it contains some buttons with the same class but without id. I'd like to be able to add a handler for it but only for the first button:
  $(document).on("click", "#my_div .some_class", function() {
    alert("yes");
  });

The code adds a handler to all the buttons with in my_div with the certain class. How do I do the same thing only for the first button?
UPDATE:
I remove and add the buttons dynamically on the page. Before deleting this code works well, meaning it works only for the first button, not for any other buttons and this is what I want:
$(document).on("click", "#my_div .some_class:eq(0)", function() {
  alert("yes");
 });

However, after removing and adding the first button again dynamically it doesn't work anymore but this one below does, although it works for all the buttons and this is NOT what I want:
$(document).on("click", "#my_div .some_class", function() {
  alert("yes");
});

A: Use the :first-child selector
$(document).on("click", "#my_div .some_class:first-child", function() {
    alert("yes");
});

A working DEMO
EDIT:
Updated FIDDLE has the dynamically loaded element's usecase

A: jQuery has a First-Child selector which works pretty much exactly like the CSS3 counterpart which you can use. This will select the first instance of ".some_class" located within #my_div.
$(document).on("click", "#my_div .some_class:first-child", function() {
    alert("yes");
});

A: Try this eq selector which takes the index:
$(document).on("click", "#my_div .some_class:eq(0)", function() {
    alert("yes");
});

There are also:

gt: selects multiple greater than given index.
lt: selects multiple lesser than given index.

UPDATE:
$(document).delegate("click", "#my_div .some_class:eq(0)", function() {
    alert("yes");
});

Checking display:
if($("selector").is(":hidden")) {
  //
}

There is also:
:visible, to check if the element is shown

Attach to the first visible element
$(document).delegate("click", "#my_div .some_class:visible:eq(0)", function() {
   alert('yes');
}

A: Create a unique ID for the specific button you want to have the handler and use that to distinguish your button.
If you use a class to put handlers, all elements with that class will have the onclick handler (as long as it fits your query which is "#my_div .some_class")

A: Have you tried :first-child yet?
try,
  $(document).on("click", "#my_div .some_class:first-child", function() {
    alert("yes");
  });

But first, please check in your console if you can find that first child using this selector or not ?
  $("#my_div .some_class:first-child")


text:
Q: Hierarchical use of generics I'm having some issues when trying to "propagate" a generic type over more than one layer of subclasses.
I have three layers of classes :
GenericResponseDtoMapper<T> is an abstract class, and T is a GenericSearchResponseDto.
I have two subclasses which extend GenericResponseDtoMapper: SimpleResponseDtoMapper and GroupedResponseDtoMapper.
In those two subclasses I'm forced to specify the generic type; for istance I must write:
SimpleResponseDtoMapper : GenericResponseDtoMapper<GenericResponseDtoMapper>.
Finally, I have some classes which extend SimpleResponseDtoMapper and some others that extendGroupedResponseDtoMapper.
My problem is that I can't specify a subtype of GenericSearchResponseDto at this level.
So, How I manage generic types in order to leaving the generic type for the first and the second layer of classes, leaving the lower level of classes to use the specified type of the generic type ?
Here is the code:
public abstract class GenericResponseDtoMapper<T> : IResponseDtoMapperDecorator where T : GenericSearchResponseDto
{
    protected List<T> items;

    public GenericResponseDtoMapper()
    {
        items = new List<T>();
    }

    public abstract IList<T> GetItems(IList<Entity.FullText_xml.DreDoc> documents);
}

The Class SimpleResponseDtoBuilder:
public abstract class SimpleResponseDtoBuilder : GenericResponseDtoMapper<GenericSearchResponseDto>
{
    public SimpleResponseDtoBuilder() : base() { }

    public override IList<GenericSearchResponseDto> GetItems(IList<DreDoc> documents)
    {
        foreach (var doc in documents)
        {
            var item = new GenericSearchResponseDto();

            item.IdDatabank = doc.Field.IdDatabank;
            item.IdDocMaster = doc.Field.IdDocMaster;
            item.DescDatabank = doc.Field.DescDatabank;
            item.Materie = doc.Field.MateriaAll.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
            item = setResponseParams(item, doc);

            items.Add(item);
        }

        return items;
    }

    public abstract GenericSearchResponseDto setResponseParams(GenericSearchResponseDto item, DreDoc doc);
}

And Finally the specific implementation:
public class GiurisprudenzaResponseDtoBuilder : SimpleResponseDtoBuilder
{
    private HighlightHelper _highLightHelper;

    private const string _BR = @"<br/>";

    public GiurisprudenzaResponseDtoBuilder() : base()
    {
        _highLightHelper = new HighlightHelper();
    }

    public override IList<GiurisprudenzaSearchResponseDto> GetItems(IList<DreDoc> documents)
    {
        return base.GetItems(documents);
    }

    public override GiurisprudenzaSearchResponseDto setResponseParams(GiurisprudenzaSearchResponseDto item, DreDoc doc)
    {

        item.IdUnitaDoc = doc.Field.IdUnitaDoc;

        ... some item.Something = doc.Something...

        return item;
    }

UML Class Diagram

A: A method for propagating a generic type over more than one layer of subclasses in C# is the following:
public TopClass<T> where T : GenericType{
}

public MiddleClass<T> : TopClass<T> where T : GenericType{
}

public BottomClass : MiddleClass<SpecificType>{
}


text:
Q: Problemas al validar tabla html con jquery Estoy intentando validar las celdas de una tabla html con jquery
tengo una tabla que tiene un campo llamado estado y tengo unos botones que se deben bloquear según el estado que tenga la fila en la tabla. Hice un método que funciona , pero el problema que tiene es que siempre me valida el primer registro que está en al tabla, por lo tanto aunque seleccione otro registro, el sistema me va a indicar la validación correspondiente al primer registro que muestra al tabla y la idea que se valide por fila seleccionada.
Acá imagen de mi tabla.

Acá el código de jquery que utilizo
No agregué el código de la tabla ya que es mucho y esta en un servlet.

    ESTADO
    ACCION

      EDITAR

        Editar

      NO EDITAR

        Editar

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        ...
        <button type="button" id="editar" disabled>Editar</button>

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>


text:
Q: Java - initiate generic variable with no generic type; Could you please explain the difference between these declarations :
List<Number> test = new ArrayList<Number>();
List<Number> test1 = new ArrayList();
test.add(new Integer(10));
test1.add(new Integer(10));
//test.add(new Object());
//test1.add(new Object());

The first 2 invocation of add method work fine, the last 2 fail.
Is there anything else, except compile warning at the second initialization ?
Do I understand correct that compile time type safety is based on variable type (and not the referenced object type)?
Thank you in advance.

A: There is no run-time difference between the following two declarations:
List<Number> test = new ArrayList<Number>();
List<Number> test1 = new ArrayList();

As you discovered, there is a compile-time warning in the second.
The JVM cannot, at run-time, enforce the fact that you only want numbers to be added to test and test1, so it does all of its checking at compile time.  The fact that the types are gone by the time this is compiled into JVM byte code is known as type erasure.
You are correct that all of this checking takes place at compile-time, and this checking is indeed driven by the type of the variable being assigned to, in your case List<Number>.  You can add Integer objects to these lists, but you cannot add Object objects.  The compiler detects this and issues an error.
You might want to try the following to dig a little deeper into your question:
Object x = new Integer(100);
test.add(x);

A:
Do I understand correct that compile time type safety is based on
  variable type (and not the referenced object type)?

Yes.


text:
Q: Data conversion from DT_STR to Currency to load with in 2 destinations I have a data flow task that consists of loading data from a flat file source (Products.csv) to transfer them to:

*

*Staging table: to save valid data

*InvalidRows: a flat file destination to save invalid data

The data that I need to load are shown in the screenshot.
So, my data conversion component allows to convert 2 attributes: ProductID and Price (as shown in the screenshot).
I'm sure that the result should be as follows:

*

*Staging table: contains the two products where ID=4 and ID=6

*InvalidRows: contains the product where ID=5
When executing, I get the following result:

"The value could not be converted because of a potential loss of
  data."

which is caused by the price column that should be converted from DT_STR to DT_CY.
It's a conversion problem, and I tried many things (data conversion / derived column), but without success.


text:
Q: cannot await dynamic for non public types Consider we have a task helper, who has a method named AwaitObject that is used for awaiting an object if it can be awaited.
public static class TaskHelper
{
    private static readonly Type TypeOfVoidTaskResult = Type.GetType("System.Threading.Tasks.VoidTaskResult");
    private static readonly Type TypeOfTaskOfVoidTaskResult = typeof(Task<>).MakeGenericType(TypeOfVoidTaskResult);

    public static async Task<object> AwaitObject(object obj)
    {
        if (obj == null)
            return null;

        var type = obj.GetType();

        if (type == typeof(Task)
            || type == typeof(ValueTask)
            || type == TypeOfTaskOfVoidTaskResult)
        {
            await (dynamic)obj;
            return null;
        }

        if (type.IsGenericType
            && type.GetGenericTypeDefinition() is var genericType
            && (genericType == typeof(Task<>) || genericType == typeof(ValueTask<>)))
        {
            object result = await (dynamic)obj;
            return result;
        }

        return obj;
    }
}

Now we have two test cases:
internal class InternalClass
{
    public int Value { get; set; }
}

[Fact]
public async Task AwaitDynamic_TaskOfInternalClass_Tests()
{
    var task = Task.FromResult(new InternalClass { Value = 1 });
    var result = await TaskHelper.AwaitObject(task);
    Assert.True(result is InternalClass { Value: 1 });
}

[Fact]
public async Task AwaitDynamic_ValueTaskOfInternalClass_Tests()
{
    var task = ValueTask.FromResult(new InternalClass { Value = 1 });
    var result = await TaskHelper.AwaitObject(task);
    Assert.True(result is InternalClass { Value: 1 });
}

Here is the problem.

*

*When TaskHelper and test cases are in the same assembly, all the cases will be passed.

*when I move TaskHelper to another assembly and then run the two tests, I will get the following exceptions.

For test 1#, Microsoft.CSharp.RuntimeBinder.RuntimeBinderException that says "Cannot implicitly convert type 'void' to 'object'".
For test 2#, Microsoft.CSharp.RuntimeBinder.RuntimeBinderException that says "'System.ValueType' does not contain a definition for 'GetAwaiter'".

*

*when I move TaskHelper to another assembly and change InternalClass to public, all the cases will be passed.

It seems a dynamic value cannot be awaited if it is invisible.
Is there something wrong with my code?
Or is that how dynamic works. If so, why?
And how do I make TaskHelper.AwaitObject work properly.

A:
And how do I make TaskHelper.AwaitObject work properly.

As an option replace this:
object result = await (dynamic)obj;

To this:
var task = (Task) obj;
await ((Task) obj).ConfigureAwait(false);
object result = task.GetType().GetProperty(nameof(Task<object>.Result)).GetValue(task);

Or is that how dynamic works. If so, why?

Yes, I think this answer is fully covers the question.


text:
Q: Having column with decimal type with 2 precision. But while save data in it, It saves value with only one precision. I am using Ruby 2.2.4 and PostgreSQL.
I have created migration:
add_column :plans, :price, :decimal, precision: 7, scale: 2

When I am going to create new record, it will save value in price column with only one precision.
Why it happens?
I want value with 2 precisions.
Ex:
Current value which is save: 20.0
I want: 20.00

A: select round(20.0 , 2), 20.00::double precision, 20.00::numeric

so you can use round() for fixed number of digits after the dot

A: I have used number_to_currency(@price). It is a method of ActionView::Helpers::NumberHelper


text:
Q: WIth Vimeo Plus account, how to hide/remove the "play" button in the middle of an embedded video? In searching, I came across this that says Vimeo doesn't support it yet. But I was wondering if anyone has found clever ways around it still?
https://vimeo.com/forums/topic:37769
Here's an image:

A: 2020 answer
Use Vimeo SDK
Set controls option to false

var options = {
    id: '116582567',
    width: '800',
    controls: false
}

Player = new Vimeo.Player('video', options);
Player.play();

A: You can now remove all controls
just wanted to update anyone new looking at this.
It now appears to be possible to have an embeded video without any of the controls, by using an experimental feature: background=1
Things to note

*

*All player toggles and elements will be turned off (including the play/pause button!)

*The video will automatically loop.

*The video will be set to autoplay.

*The video will be muted.

you can then use the js-api to control the video (pause, play, etc).
Example Embed Code

See the forum post here: https://vimeo.com/forums/help/topic:278001

A: In your Vimeo account go to the video you wish to embed, then go to Settings > Embed.  Once there enable the "Show Play Bar" option.  This will eliminate the Play button in the middle of your video image, but will display the Play Bar at the bottom of your image.  From what I can tell it's either/or.  I would love to be able to hide both so you just see the clean poster frame of the video and click on it ti initiate playback.  If anyone knows how please let me know.

A: I hope this isn't against the Vimeo rules, but it is possible to hide those buttons.


text:
Q: What exactly does Mapdeck in R return during a click event with a add_scatterplot? I've been trying to develop a few web apps using Mapdeck in R that revolve around building site maps.  Right now I'm trying to develop an app that will return a value on click.
My question, with the below sample, what exactly does Mapdeck return on a click event?  I thought it was whatever was assigned to the 'id' value, however the stuff I'm getting back seems to be a nested data that isn't related to my data frame input.  In the below example I'd like it to return the 'Point_ID' value for each site.
# ################################################################################################
# ################################################################################################
# # Sec 1a. Needed Libaries & Input Files

library(shiny)
library(shinydashboard)
library(mapdeck)
library(dplyr)

Map_DF <- data.frame("Point_ID" = c("A1", "B1", "C3"),
                     "Latitude" = c(38.05, 39.08, 40.05),
                     "Longitude" = c(-107.00, -107.05, -108.00),
                     "PointUse" = c("farm", "house", "well"),
                     "info" = c("A1 38.05 -107.00 farm",
                               "B1 39.08 -107.05 house",
                               "C3 40.05 -108.00 well"))

################################################################################################
################################################################################################
#UI
ui <- dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody(
        fluidRow(mapdeckOutput(outputId = 'mapA')),
        fluidRow(htmlOutput("textOutA"))
    )
)

################################################################################################
################################################################################################
server <- function(input, output) {

    ##The MapDeck Token
    key <- '## put your own token here ##'
    set_token(key) ## set your access token

    ### The Map
    output$mapA <- renderMapdeck({
        mapdeck() %>%
            add_scatterplot(
                data = Map_DF,
                lat = "Latitude",
                lon = "Longitude",
                id = 'Point_ID',
                tooltip = "info",
                radius = 10000,
                # radius_min_pixels = 3,
                auto_highlight = TRUE,
            )
    })

    ##Click Event, return text
    observe({
        click <- input$mapA_scatterplot_click
        if(is.null(click)) {
            output$textOutA <- renderUI({
                str1 <- paste("Nothing...")
                HTML(paste(str1))
            })
        } else {
            output$textOutA <- renderUI({
                str1 <- paste(click)
                HTML(paste(str1))
            })
        }
    })

}

################################################################################################
################################################################################################
shinyApp(ui = ui, server = server)

A: It might be a bug with id argument .
For now, here is what you can do to overcome this (the idea is to use row index contained on the string):
# ################################################################################################
# ################################################################################################
# # Sec 1a. Needed Libaries & Input Files

library(shiny)
library(shinydashboard)
library(mapdeck)
library(dplyr)

Map_DF <- data.frame("Point_ID" = c("A1", "B1", "C3"),
                     "Latitude" = c(38.05, 39.08, 40.05),
                     "Longitude" = c(-107.00, -107.05, -108.00),
                     "PointUse" = c("farm", "house", "well"),
                     "info" = c("A1 38.05 -107.00 farm",
                                "B1 39.08 -107.05 house",
                                "C3 40.05 -108.00 well"))

################################################################################################
################################################################################################
#UI
ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    fluidRow(mapdeckOutput(outputId = 'mapA')),
    fluidRow(htmlOutput("textOutA"))
  )
)

################################################################################################
################################################################################################
server <- function(input, output) {

  ##The MapDeck Token
  key <- '## put your own token here ##'
  set_token(key) ## set your access token

  ### The Map
  output$mapA <- renderMapdeck({
    mapdeck() %>%
      add_scatterplot(
        data = Map_DF, layer_id = "PointUse",
        lat = "Latitude",
        lon = "Longitude",
        id = 'Point_ID',
        tooltip = "info",
        radius = 10000,
        # radius_min_pixels = 3,
        auto_highlight = TRUE,
      )
  })

  output$textOutA <- renderUI({

    click <- input$mapA_scatterplot_click
    if(is.null(click)) {str1 <- "Nothing..."}
    else {str1 <- Map_DF[as.numeric(gsub(".*:","",gsub(",.*","",click)))+1,]$Point_ID}

    HTML(str1)
    })

}

################################################################################################
################################################################################################


text:
Q: How can I use a console window as a log window from a windows app? Can I implement an ILogger that outputs to a console window?
My only thought is a console application that does a pass-through from Console.In to Console.Out which is started by the implementation, which would have to be a singleton instance...
Is there another, possibly simpler approach or is that the way to do it?
Note: I just remembered I solved this requirement way back in the day on a unix platform.  It was to synchronously append to a text file, and then use tail -f on that file from a console...


text:
Q: How to display the last ordered product in WooCommerce via a shortcode I'm looking for a way to display the last ordered product on another page.
I think it would be possible to maybe create a shortcode in the functions that takes the order details and displays them wherever I add the shortcode.

But I can't seem to figure out how to get it to work. So far I got this information to work with:
add_shortcode( 'displaylast', 'last' );
function last(){
    $customer_id = get_current_user_id();
    $order = wc_get_customer_last_order( $customer_id );
    return $order->get_order();
}

[displaylast] is currently showing me noting. It does work when I change get_order() to get_billing_first_name().
That displays the order name. But I can't seem to get the item that was bought. Maybe there is a get_() that I'm not seeing?

A: You are close, however you must obtain the last product from the order object.
So you get:
function last() {
    // Not available
    $na = __( 'N/A', 'woocommerce' );

    // For logged in users only
    if ( ! is_user_logged_in() ) return $na;

    // The current user ID
    $user_id = get_current_user_id();

    // Get the WC_Customer instance Object for the current user
    $customer = new WC_Customer( $user_id );

    // Get the last WC_Order Object instance from current customer
    $last_order = $customer->get_last_order();

    // When empty
    if ( empty ( $last_order ) ) return $na;

    // Get order items
    $order_items = $last_order->get_items();

    // Latest WC_Order_Item_Product Object instance
    $last_item = end( $order_items );

    // Get product ID
    $product_id = $last_item->get_variation_id() > 0 ? $last_item->get_variation_id() : $last_item->get_product_id();

    // Pass product ID to products shortcode
    return do_shortcode("[product id='$product_id']");
}
// Register shortcode
add_shortcode( 'display_last', 'last' );

SHORTCODE USAGE
In an existing page:
[display_last]

Or in PHP:
echo do_shortcode('[display_last]');


text:
Q: What is an umbilic point of a convex polyhedron? An umbilic point of a smooth ($C^2$) convex surface in Euclidean 3-space is a point where the principal curvatures are equal. Is there some good way to generalize this notion to convex polyhedra? See this earlier question, specially the comments by Igor Rivin and Ivan Izmestiev for the motivation behind the current question.
First, what do I mean by "good"? Here are some requirements that come to mind (which may be negotiable):

*

*It is not necessary for the notion of umbilic to be defined for all convex polyhedra but it would be enough if it is well-defined for generic polyhedra, or a class of polyhderda which is dense in the space of all convex polyhedra, and possibly open as well.

*Each convex polyhedron (or each polyhedron in the generic subclass) should have at least one umbilic point.

*It would be better if each polyhedron had at least two umbilics, or otherwise there was a notion of index associated to each umbilic so that the sum of the indices was constant for all polyhedra (in parallel with the index formula for the singularities of a line field on a sphere).

*It would be reassuring if there were some convex polyhedra with exactly two umbilics.

*(Bonus) Ultimately it would be nice if this notion were stable as a family of convex polyhedra converges to a smooth convex surface, but this can be set aside for now.

Question: Does there exist a notion of umbilic point for convex polyhedra which would satisfy the first four requirements listed above?

As was suggested by Ivan Izmestiev, maybe one should consider the Gauss image around vertices of the polyhedron. More precisely, consider the outward unit normals at the faces around a vertex. These normals form the vertices of a convex spherical polygon whose edges are geodesic arcs which join a pair of normals if and only if those normals correspond to adjacent faces of the polyhedron. So a vertex would be considered umbilic if its spherical image is somehow "circular" or relatively round (as is the case in the smooth case).
Perhaps a useful guide here could be the generalized four vertex theorem for convex (spherical) polygons; see for instance Section 21 of Igor Pak's Lecture Notes and the corresponding papers of Serge Tabachnikov cited there.
I first heard about the question in the title when Brian White asked me that in 2010. My idea back then was to consider the class of convex polyhedra with quadrilateral faces, and define an umbilic point as a vertex with degree different from $4$. It is a simple exercise to show, via Euler's formula, that all convex polyhdera with quadrilateral faces must have at least $8$ umbilics in this sense. The intuition behind this definition was the notion of "circular planar quadrilateral meshes", or  "circular nets" which are discrete analogues of principal curvature lines. See for instance the book of Bobenko and Suris. This then was a purely topological candidate, and I did not get much chance to think about it more since then. Perhaps it might be more fruitful to consider geometric alternatives mentioned above, or some kind of a hybrid.


text:
Q: Shared memory in chroot environment I'm playing with Ubuntu 11.10 launched in a chroot environment under Android 3.2.1. Most of the software works fine except PostgreSQL. When installed or initdb launched it's saying:

FATAL: could not create shared memory segment: Function not implemented.
  DETAIL: Failed Failed system call was shmget(key=1, size=1908736, 03600).

Is there any specific tuning of shared memory/PostgreSQL in a chroot? Perhaps some kind of mount the android ashmem to chrooted shm? I'm a novice in Linux.

A: ashmem uses the /dev/ashmem device node. You need to create it in the chroot's /dev, either by using mknod with the apropriate numbers, or by doing a bind mount:
touch chroot/dev/ashmem
mount --bind /dev/ashmem chroot/dev/ashmem

(You might need Busybox or Ubuntu's mount for this.)


text:
Q: Dealing with columns containing nested json using python pandas I have a pandas df with various columns. One column - myCol - looks like this:
df

someCol   myCol
a         [{}]
b         [{'X': {'A': "value", 'B': "value"}}]
c         [{}, {}]
d         [{'X': {'A': "value", 'B': "value", 'C': "value"}}]

The maximum number of key-val pairs in X is unknown: some rows contain them all, some only contain a selection, and some are empty. I would like to replace myCol with actual columns, with as many columns as needed depending on the unique number of key-val pairs in X. So in this particular example, I would end up with:
df

someCol   A       B       C
a         N/A     N/A     N/A
b         value   value   N/A
c         N/A     N/A     N/A
d         value   value   value

I am struggling in coming up with a general way to solve this, which is needed since I don't know how many 'additional' columns I will need in the end. Any ideas would be much appreciated.

A: Solution return first lists and dictionary with key X, then convert Nones to empty dicts and last pass to DataFrame constructor:
d = [{} if pd.isna(x) else x for x in df.pop('myCol').str[0].str.get('X')]
df = df.join(pd.DataFrame(d, index=df.index))
print (df)
  someCol      A      B      C
0       a    NaN    NaN    NaN
1       b  value  value    NaN
2       c    NaN    NaN    NaN
3       d  value  value  value


text:
Q: WPF UserControl - SelectedItem of a Usercontrol DataGrid to bind to a ItemSource to DataGrid outside the UserControl Hi, My WPF UserControl knowledge is like an hour old. So please forgive me if there are plenty of tutorials or/and answers on SO regarding this question (To be honest I dont think this can be done and will need to re-do code... hence why I thought I ask)
So before creating a UserControl, I had a datagrid that fliters customers based on what text the user typed in a Textbox. Once found, the SelectedItem of that filter DataGrid is then used to bind to a new DataGrid containing a new collection.
So....
Filter DataGrid XAML
SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"
ItemsSource="{Binding Source={StaticResource cvsCustomers}}"

Once the User selects a Customer in that grid,
a new DataGrid would contain rows of properties based on the SelectedCustomer
ItemsSource="{Binding SelectedCustomer.CustomerOrders}"

All well and good and it works.
However, I am going to use this Filter Customer results functionality a lot in my project, so I have created a UserControl in which the filter DataGrid is working.
I have put this UserControl in a view, so the problem is I need whatever the selectedItem is in the Usercontrol to be bounded to a DataGrid in the view. (Like above)
So I need something like this in the DataGrid in the View.
ItemsSource="{Binding ElementName=myUserControl, Path=SelectedCustomer.CustomerOrders}"

Ok a bit long winded but I hope you understand the problem, and I have given enough knowledge on the subject at hand. If I done something wrong, please tell me and just down vote the question.
Cheers

A: You can add a new dependency property to your custom usercontrol and bind your datagrid items source to that property. Make sure to handle selection changed event on your user control's data grid and set the dependency property to the selected item.
   public object MySelectedItem
        {
            get { return (object)GetValue(MySelectedItemProperty); }
            set { SetValue(MySelectedItemProperty, value); }
        }

    // Using a DependencyProperty as the backing store for MySelectedItem.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MySelectedItemProperty =
        DependencyProperty.Register("MySelectedItem", typeof(object), typeof(YOURUSERCONTROLTYPE), new UIPropertyMetadata(null));

handle the selection changed event
   public YourUserControl()
        {
            InitializeComponent();
            dgv.SelectionChanged += dgv_SelectionChanged;

        }

    void dgv_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MySelectedItem = dgv.SelectedItem;
        }

and then bind to
ItemsSource="{Binding ElementName=myUserControl, Path=MySelectedItem.CustomerOrders}"


text:
Q: Display form info on alert (html and javascript) I currently have a form in which a user can put his name, age and the message and then I have a button to submit the message and it is supposed to show an alert with the form information but when I put the information and click the button nothing is happening (the alert doesn't show). Here is the html form and javascript function code:
<form action="#" method="get">
        <fieldset>
            <legend>Informações do utilizador</legend>
            Nome:
            <input id="nome" name="nome" type="text" />

            Idade:
            <select id="idade" name="idade">
                <option value="menor"><18</option>
                <option value="jovem">18-21</option>
                <option value="jovemadulto">22-29</option>
                <option value="adulto">30-39</option>
                <option value="adultoavancado">40-49</option>
                <option value="idoso">>=50</option>
            </select>
        </fieldset>
        <fieldset>
            <legend>Ideias para tornar um campus mais sustentável</legend>
            Mensagem:

            <textarea id="mensagem" name="mensagem" rows="10" cols="50" placeholder="Introduza a sua ideia">
                </textarea>

            <input id="enviar" name="enviar" type="submit" onClick="submitForm()" value="Enviar">

            <input id="limpar" name="limpar" type="reset" value="Limpar" />
        </fieldset>
    </form>

A: the correct way to do that...

const myForm = document.querySelector('#my-form') // use the form parent
                                                 // to refer each form elements

  // think about how to write your code:
  // easier to read again = less typing errors

myForm.onsubmit = evt =>
  {
  alert( 'Nome: ' + myForm.nome.value   // access each element by his name
       + '\n Idade: ' + myForm.idade.value
       + '\n Mensagem: ' +  myForm.mensagem.value
       );

  evt.preventDefault(); // for testing without page relaod
  }
<form action="#" method="get" id="my-form">
  <fieldset>
    <legend>Informações do utilizador</legend>
    Nome:
    <input id="nome" name="nome" type="text" />

    Idade:
    <select id="idade" name="idade">
      <option value="menor"><18</option>
      <option value="jovem">18-21</option>
      <option value="jovemadulto">22-29</option>
      <option value="adulto">30-39</option>
      <option value="adultoavancado">40-49</option>
      <option value="idoso">>=50</option>
    </select>
  </fieldset>
  <fieldset>
    <legend>Ideias para tornar um campus mais sustentável</legend>
    Mensagem:

    <textarea id="mensagem" name="mensagem"
         rows="10" cols="50"   placeholder="Introduza a sua ideia"></textarea>

    <button type="submit"> Enviar </button>
    <button type="reset"> Limpar </button>
  </fieldset>
</form>


text:
Q: Extract string and some number of digits I want to extract a pattern that starts with 1. in the string. After some research I found stringr package and str_extract function. But it is extracting the only first match so far.
 library(stringr)
 library(dplyr)

 clas <- c("1461CD_1.332C","1461CD_1.5C_242","1461CD_1.6CC_131")
      df <- data.frame(clas)

      df %>% mutate(clas = str_extract(clas, "1.{1,2}"))

clas
1  146
2  146
3  146

the expected output
clas
1  1.33
2  1.5
3  1.6

I would appreciate you also write down some explanations to your solution since regular expressions currently complicated topics for me:)

A: To get the right regular expression, you currently want to match 1, a literal ., and then two digits. In regular expressions, . indicates any character, so you need to escape it with \. However, because \ is a special character in strings in R, that means you need to escape the \ as well so you type \\.. Then, you want to match either one or two digits. It's correct to use quantifiers {1,2} to specify one or two, but you need to tell the expression that you want digits specifically. You can do this with [:digit:], or the shorthand \\d. This gives the desired output:
library(tidyverse)
clas <- c("1461CD_1.332C","1461CD_1.5C_242","1461CD_1.6CC_131")
df <- data.frame(clas)

df %>%
  mutate(clas = str_extract(clas, "1\\.\\d{1,2}"))
#>   clas
#> 1 1.33
#> 2  1.5
#> 3  1.6

Created on 2018-02-20 by the reprex package (v0.2.0).
For more information on regular expressions and regex in R specifically, see the chapter in R for Data Science and also look at the handy cheatsheet for stringr from RStudio.


text:
Q: How to setup and run angular js protractor test in jenkins? I have following configuration but getting error
ERROR

registration capabilities Capabilities [{platform=WINDOWS, ensureCleanSession=true, browserName=internet explorer, version=}] does not match the current platform LINUX
18:17:05.892 INFO - Driver provider org.openqa.selenium.edge.EdgeDriver registration is skipped:
registration capabilities Capabilities [{platform=WINDOWS, browserName=MicrosoftEdge, version=}] does not match the current platform LINUX
18:17:05.896 INFO - Driver class not found: com.opera.core.systems.OperaDriver
18:17:05.896 INFO - Driver provider com.opera.core.systems.OperaDriver is not registered
18:17:06.187 WARN - Failed to start: SocketListener0@0.0.0.0:4444
Exception in thread "main" java.net.BindException: Selenium is already running on port 4444. Or some other service is.
    at org.openqa.selenium.server.SeleniumServer.start(SeleniumServer.java:492)
    at org.openqa.selenium.server.SeleniumServer.boot(SeleniumServer.java:305)
    at org.openqa.selenium.server.SeleniumServer.main(SeleniumServer.java:245)
    at org.openqa.grid.selenium.GridLauncher.main(GridLauncher.java:64)
Selenium Standalone has exited with code 1
Selenium standalone server started at http://10.33.24.128:43448/wd/hub

Jenkins commands

## run testing
node_modules/protractor/bin/webdriver-manager update --standalone
node_modules/protractor/bin/webdriver-manager start > /dev/null 2>&1 &

while ! curl http://localhost:4444/wd/hub/status &>/dev/null; do :; done

node_modules/protractor/bin/protractor protractor.conf.js

My configuration file is below
exports.config = {
  directConnect: false,

  capabilities: {
    'browserName': 'chrome'
  },
    chromeDriver: './node_modules/protractor/selenium/chromedriver',
  seleniumAddress: 'http://localhost:4444/wd/hub',
  framework: 'jasmine',
  specs: ['tests/specs/*-spec.js'],
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000
  }
};

A: You have an error message:

Selenium is already running on port 4444. Or some other service is.

So your tests are failing because Selenium could not be set up, as the port it requires is already in use.
This could be perhaps because another build running in parallel on the same machine, or because Selenium wasn't stopped by a previous build, or some other server is using port 4444.
You need to ensure that this port is free before starting your build.
You can restrict multiple builds running in parallel on the same machine that want to use the same port number with the Port Allocator plugin or the Throttle Concurrent Builds plugin.

A: Avoid handling directly this and delegate it to gulp plugin like gulp-angular-protractor to:
1).Start/stop selenium server
2).And run protractor tests
Full Example
Gulpfile.js
/*jshint node: true, camelcase: false*/
/*global require: true*/

'use strict';

var gulp = require('gulp'),
gulpProtractorAngular = require('gulp-angular-protractor');

// Setting up the test task
gulp.task('regression-suite', function(callback) {
    gulp
        .src(['./tests/specs/*spec.js'])
        .pipe(gulpProtractorAngular({
            'configFile': 'protractor.conf.js',
            'debug': false,
            'autoStartStopServer': true
        }))
        .on('error', function(e) {
            console.log(e);
        })
        .on('end', callback);
});

conf.js
Same as before
Command Prompt
C:>gulp regression-suite

Jenkins
Add a step as execute windows command
gulp regression-suite


text:
Q: express-gateway on Heroku - {$PORT} binding error I have deployed my express-gateway on Heroku, using env variables in this way in the gateway.config.yml file:
http:
  port: ${PORT:-8080}
  host: ${HOST:-localhost}
https:
  port: ${PORT:-8080}
  host: ${HOST:-localhost}
apiEndpoints:
  ....

Anyway Heroku keeps giving this error:
[EG:gateway] gateway http server listening on :::8080

State changed from starting to crashed

Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

I have used the notation ${ENV_VAR_NAME:-DEFAULT} according to official documentation. Why Heroku tries to bind the 8080?
====== UPDATE
Just an out-of-topic tip, for who is going to use Heroku, here's how I get the redis url from the env vars.
      var redis_Url = process.env.REDIS_URL;
      var groups = /^redis:\/\/(.*?)\:(.+?)\@(.+?)\:(.+)$/gi.exec(redis_Url);

      var nm = groups[1];
      var pasw = groups[2];
      var host = groups[3];
      var port = groups[4];

      process.env.REDIS_NM   = nm;
      process.env.REDIS_PASW = pasw;
      process.env.REDIS_HOST = host;
      process.env.REDIS_PORT = port;

      console.log('redis url   --> '+process.env.REDIS_URL);
      console.log('nm   --> '+process.env.REDIS_NM);
      console.log('pasw --> '+process.env.REDIS_PASW);
      console.log('host --> '+process.env.REDIS_HOST);
      console.log('port --> '+process.env.REDIS_PORT);

A: You should not make listen both the http and the https server on the same port, otherwise it's going to fail.
Heroku provides its own router handling the SSL termination for you, so you can just remove the whole https section.