text:
Q: while( var row = fn() ); Is there any equivalent metod to make like an php mysql_fetch_array while loop in js?
in php you can do:

<?php
while ($row = mysql_fetch_array($result)) {
    echo "my name is " . $row['name'] . " and i'm " . $row['age'] . " yeas old";
}
?>

i have this object/array:
function fetch_array(arr) {
    // My magic fn that dose not work well, b/c it change the orginal refence
    return arr.shift();
}
var result = [{
    name: "Bob",
    age: 12
}, {
    name: "Jim",
    age: 18
}]

// And want to do:

while (row = fetch_array(result)) {
     alert("my name is " + row["name"] + " And I'm " + row['age'] + " years old");
 }

// returns zero :( dont want that
console.log(result.length);

A: I changed your fetch_array function in this way
function fetch_array(arr) {
   var i = fetch_array.i || 0;
   fetch_array.i = ("undefined" === typeof arr[i])? 0 : i + 1;
   return arr[i];
}

and this leave untouched your array. The idea is to attach and increment an index property to the the function itself
Edit: I had to reset the index when the end of array is reached, otherwise you would not be able to loop more than once on the same (or different) «resultset», e.g.
while(row = fetch_array(result)){
    alert("my name is " + row["name"] + " And I'm " + row['age'] + " yo");
}

while(row = fetch_array(result)){
   alert("here again the name " + row["name"] + " and age: " + row['age']);
}

console.log(result.length); // returns 2;

as aside note, the condition to reset the index could be also done with
fetch_array.i = (i === arr.length)? 0 : i + 1;

A: Array.shift removes the first element of the array, so when you're done looping through it like that, it's empty.
If all you want to do is to go through it and use the data, try this:
var row;
for (var i = 0, l = result.length; i < l; i++) {
    row = result[i];
    alert("my name is " + row["name"] + " And I'm " + row['age'] + " years old");
}

// returns 2
console.log(result.length);

or change the fetch_array function to this, and leave the rest as it is:
var index = 0;
function fetch_array(arr){
   return arr[index++];
}

You would have to reset the index variable to 0 if you wanted to loop through it again though.

A: You have the array item available in your loop so you could always recreate it if you wanted. Or just copy it before you use your fetch_array function.
Alternatively just loop through the array.

A: Depending on what browsers joy want to support, array.forEach could be an option:
result.forEach(function(row) {
    alert("my name is " + row["name"] + " And I'm " + row['age'] + " years old");
});

Or if you use jQuery:
$(result).each(function() {
    var row = this;
    alert("my name is " + row["name"] + " And I'm " + row['age'] + " years old");
});


text:
Q: Where Should I put my Login PHP script (for controller ) in CodeIngiter? I have a simple question.
 In my Home controller, there is a function for Log in, inside the function there is the account control for

*
*Sql Databse (Accounts saved in a Database, like the root account)

*LDAP

For the LDAP i have a seperate file with contains a function to validate the LDAP accounts.
My question is, should i put the file inside the 'helper' folder, put in a model or add the function in the controller.

This is simply for better organization.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Удалить один div по нажатию на кнопку У меня есть генератор div`ов на РНР:
echo '
'.$result['title'].' - '.$result['price'].' рублей

<button name="delete" class="delete" style="margin-bottom: 30px;">Удалить</button>
';

и этих блоков может быть очень много. Нужно сделать так, чтобы при нажатии на кнопку delete удалялся лишь тот, на кнопку которого нажали. Я не особо силён в JS, но смог написать такой код:
document.querySelectorAll('.delete').forEach(
  b => b.addEventListener('click',
    () => b.closest('.block').remove())
);

Вот только таким образом исчезают все блоки. Как получить нужный блок и удалить именно его? Кто может помочь?

A: По id:
echo '
'
.$result['title']
.' - '
.$result['price']
.' рублей

<button name="delete"'
.' onclick="document.getElementById(\''.$result['id'].'\').remove()"'
.' style="margin-bottom: 30px;">Удалить</button>
';

Но id обязательно должен быть уникальный, можете сделать префикс, к примеру: '
'
А еще в своем коде вы не закрыли div

A: Вы можете использовать следующий JavaScript код в конце своего HTML:
// Блок #1
function act(event) {
    event.target.parentElement.remove();
}

// Блок #2
document.querySelectorAll('button.delete').forEach(
    button => button.addEventListener('click', act)
);

Блок #1 является функцией, которая вызывается при нажатии на кнопку. Данная функция имеет аргумент event, который содержит в себе кучу информации о произошедшем событии, в том числе и target - элемент, который был нажат (в нашем случае - кнопка). Дальше мы вызываем метод remove() у прямого родителя кнопки (в нашем случае это div).
Блок #2 регистрирует событие click для каждой кнопки с классом delete, где обработчиком события является функция act из Блока #1.
Дайте, пожалуйста, знать, если это не помогло, или я непонятно объяснил.


text:
Q: how to open a csv file in python having double quotes I have a huge file about 500k rows and 187 columns. After saving it into a csv file, I ran into a situation whereby my header is separated by semicolon (;) and the contents are also separated by the semicolons but wrapped in double quotes(""). Opening it with pandas does not look the way i want it to look. I tried using a csv model but the result is very disturbing. Available solutions on the net do not answer my task.
Below is the sample of my file from CouponSales&Refund.csv.
flt_no;aa_code;dep_port;arr_port;sch_dep_dt;sch_dep_dt_with_time;sch_arr_dt;sch_arr_dt_with_time
106;"SW";"OND";"ERS";"04-06-2020";"04/06/2020 15:50:00";"04-06-2020";"04/06/2020 16:45:00"
101;"SW";"ERS";"OND";"04-06-2020";"04/06/2020 08:20:00";"04-06-2020";"04/06/2020 09:15:00"
134;"SW";"MPA";"ERS";"21-06-2020";"21/06/2020 12:40:00";"21-06-2020";"21/06/2020 14:05:00"

This is what I have done so far but I am still not happy
import csv
with open('CouponSales&Refund.csv', 'rt') as f:
    csv_reader = csv.reader(f)

    for line in csv_reader:
        print(line)

df = pd.read_csv('CouponSales&Refund.csv', sep=";")

All I want is a tabular data. How Can I achieve that?

A: Assuming your csv hs newlines as in
lt_no;aa_code;dep_port;arr_port;sch_dep_dt;sch_dep_dt_with_time;sch_arr_dt;sch_arr_dt_with_time
106;"SW";"OND";"ERS";"04-06-2020";"04/06/2020 15:50:00";"04-06-2020";"04/06/2020 16:45:00"
101;"SW";"ERS";"OND";"04-06-2020";"04/06/2020 08:20:00";"04-06-2020";"04/06/2020 09:15:00"
134;"SW";"MPA";"ERS";"21-06-2020";"21/06/2020 12:40:00";"21-06-2020";"21/06/2020 14:05:00"

I get
In [4]: pd.read_csv('tmp.csv', sep=';')
Out[4]:
   lt_no aa_code dep_port arr_port  sch_dep_dt sch_dep_dt_with_time  sch_arr_dt sch_arr_dt_with_time
0    106      SW      OND      ERS  04-06-2020  04/06/2020 15:50:00  04-06-2020  04/06/2020 16:45:00
1    101      SW      ERS      OND  04-06-2020  04/06/2020 08:20:00  04-06-2020  04/06/2020 09:15:00
2    134      SW      MPA      ERS  21-06-2020  21/06/2020 12:40:00  21-06-2020   21/06/2020 14:05:00

pd.read_csv escapes double quotes by default.


text:
Q: How can I make a Marquee with 3D effects similar that is there in Android website? I want to make a 3D marquee like that is there in Android Website (http://www.android.com)
I realized that it's used -webkit-transform: translateZ but how can I put it to work?

A: To do complex animations like that, you will need to use the css properties "transform" and "transition" along with the vendor prefixes such as -webkit- and -moz- because these properties are not fully accepted yet.
All you would have to do is setup the html as follows:

</div

And then for the css:
.container{
    width: 960px;
    height: 300px;
}
.movingDiv{
   position: absolute;
   transition: transform 1s, opacity 1s, left 1s, top 1s;
   opacity: 1;
}
.movingDiv.foreward{
   transform: scale(1.2);
   opacity: 0;
   left: -400px;
   top: 400px;

}
.movingDiv.backward{
   transform: scale(1.2);
   opacity: 0;
   left: 600px;
   top:-100px;
}

And then use some javascript to give each of the elements (movingDiv) a class of "backward" or "forward" based on its position and leave it just as the default class (movingDiv) if it is the primary element.
I recommend spending some time reading up on it. One good source is this site, but there are plenty others.


text:
Q: How can we sort the object array based on another object array value in node js How can we sort the object array based on another object array value, like we have an object array:
var _userEnd = [{"userID":554,"tEnd":6},{"userID":597,"tEnd":3},{"userID":605,"tEnd":3},{"userID":617,"tEnd":1},{"userID":553,"tEnd":1},{"userID":616,"tEnd":1},{"userID":596,"tEnd":0}]

In this the index 1,2,3,4,5 are having the same value of the key "tEnd" i.e., 3 and 1 so I just need to sort only those index on the basis of another object array
var _profsort=[{"userID":596,"score":100},{"userID":616,"score":95},{"userID":553,"score":100},{"userID":617,"score":85},{"userID":605,"score":95},{"userID":597,"score":85},{"userID":554,"score":100}]

Here the userID 597,605,617,553,616 are having the score value 85,95,85,100,95
so based on score, I want to sort my first array
Output should be:
[{"userID":554,"tEnd":6},{"userID":605,"tEnd":3},{"userID":597,"tEnd":3},{"userID":553,"tEnd":1},{"userID":616,"tEnd":1},{"userID":617,"tEnd":1},{"userID":596,"tEnd":0}]

A: You could take the delta of tEnd and find the score and take that delta.

function getScore(uID) {
    return (_profsort.find(({ userID }) => userID === uID) || { score: 0 }).score;
}

var _userEnd = [{ userID: 554, tEnd: 6 }, { userID: 597, tEnd: 3 }, { userID: 605, tEnd: 3 }, { userID: 617, tEnd: 1 }, { userID: 553, tEnd: 1 }, { userID: 616, tEnd: 1 }, { userID: 596, tEnd: 0 }],
    _profsort = [{ userID: 596, score: 100 }, { userID: 616, score: 95 }, { userID: 553, score: 100 }, { userID: 617, score: 85 }, { userID: 605, score: 95 }, { userID: 597, score: 85 }, { userID: 554, score: 100 }];

_userEnd.sort(function (a, b) {
    return b.tEnd - a.tEnd || getScore(b.userID) - getScore(a.userID);
});

console.log(_userEnd);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: Use sort and find
var fnGetScore = uid => _profsort.find(s => s.userID == uid).score; //method to get the score value based on userId

var output = _userEnd.sort( (a, b) =>
        (b.tEnd - a.tEnd) ||
           fnGetScore(b.userID) - fnGetScore(b.userID)) //compare tEnd first and if they are same, compare the score value

Demo

var _userEnd = [{
  "userID": 554,
  "tEnd": 6
}, {
  "userID": 597,
  "tEnd": 3
}, {
  "userID": 605,
  "tEnd": 3
}, {
  "userID": 617,
  "tEnd": 1
}, {
  "userID": 553,
  "tEnd": 1
}, {
  "userID": 616,
  "tEnd": 1
}, {
  "userID": 596,
  "tEnd": 0
}];

var _profsort = [{
  "userID": 596,
  "score": 100
}, {
  "userID": 616,
  "score": 95
}, {
  "userID": 553,
  "score": 100
}, {
  "userID": 617,
  "score": 85
}, {
  "userID": 605,
  "score": 95
}, {
  "userID": 597,
  "score": 85
}, {
  "userID": 554,
  "score": 100
}];

var fnGetScore = uid => _profsort.find(s => s.userID == uid).score;

var output = _userEnd.sort((a, b) => (b.tEnd - a.tEnd) || fnGetScore(b.userID) - fnGetScore(b.userID))

console.log(output);

A: Create an object of score by userID using Array.reduce. Sort by tEnd, and if it's equal sort by the score you get from the sortObject by the userId:

var _userEnd = [{"userID":554,"tEnd":6},{"userID":597,"tEnd":3},{"userID":605,"tEnd":3},{"userID":617,"tEnd":1},{"userID":553,"tEnd":1},{"userID":616,"tEnd":1},{"userID":596,"tEnd":0}]

var _profsort=[{"userID":596,"score":100},{"userID":616,"score":95},{"userID":553,"score":100},{"userID":617,"score":85},{"userID":605,"score":95},{"userID":597,"score":85},{"userID":554,"score":100}]

var sortObj = _profsort.reduce((r, o) => {
  r[o.userID] = o.score;

  return r;
}, Object.create(null));

_userEnd.sort((a, b) => b.tEnd - a.tEnd || sortObj[b.userID] - sortObj[a.userID]);

console.log(_userEnd);


text:
Q: Can MATPLOTLIB be used from languages other than Python? I was wondering if it would be possible to use MATPLOTLIB from a language other than Python.
Scenario:

*

*I could have a Windows .NET executable to accept user input

*do some lengthy calculations.

*then invoke MATPLOTLIB to display the results

I was comparing with GNUPLOT which is a stand alone executable and you can issue commands to this executable through the command line , thereby making such a scenario possible.
Thank you.

A: Not directly.  However, just as you can call gnuplot as a system call, you can also call python to run a script.  And, just as you might create a gnuplot script on-the-fly and then run that through gnuplot, you can also generate a Python script on the fly and run that through python.
It will be harder true interactivity from a program calling python to run a script.  Gnuplot works with pipes and so can better interact with the calling program.  I do not know if that is possible.  You could set up a "python service" and use some inter-process communication (say, XML-RPC or SOAP) to send data between the python process and the calling program.   This can work (I've done it, though not from .NET), but is a bit of work to set up.  Matplotlib is able to work with a GUI event loop, but not with the normal "pyplot" interface, in which pyplot.show() tends to block I/O.
In many cases, one can also embed a Python interpreter in an application.  Sadly, with .NET / CLR one would want to use IronPython, which (as far as I know) doesn't work with matplotlib.

A: Not unless there is specific package in the other language (e.g. Julia has the 'pyplot' package) or there is a way of calling python from the other language.

A: You may compile a python script into an executable. This might be done e.g. using pyinstaller. The python code could be rather generic and allow for arguments to be passed to it, which are then used to plot something with matplotlib.
The drawback of this is that the executable would be rather large, because it needs to contain matplotlib and all of its dependencies.


text:
Q: How to write to a file over the network I have two ubuntu linux boxes: I'm in bash on one machine running some battery of tests (storage, memory, etc.). Now, I want to test writing to a file over the network to the other linux box. Any idea of the command to write to a file across the network (behind the same router)? I could easily ssh into the second machine, but I want to send data across the network, writing to a file at the root or some particular directory. Thanks!

A: SCP!

A: You should use scp (Secure copy) or rsync (Remote Sync).
From the command line type
scp file_to_copy user@remote_linx:/tmp/copy_of_file


text:
Q: Problem with booting (computer boots weirdly) I've downloaded and burned the .iso file from Ubuntu page (Ubuntu 16.04.1 LTS), and burned it on USB with Rufus.
Now, I've already had Ubuntu installed, but because of this problem, I thought I'd reinstall it directly by Ubuntu instructions, since I didn't for the first time.
I've also reset the CMOS settings to default, I thought maybe something I've done on the PC while messing with themes and installing lots of stuff via terminal may've messed up with BIOS.
Now, I went through this procedure when installing:

*

*Try Ubuntu (I didn't install immediately, but through try mode)

*Install Ubuntu

*Download updates and third party apps

*Erase disk and install Ubuntu

And then all the other misc stuff (date, place, login info etc).
I also set it to log me in automatically (no password).
When I rebooted the PC, I normally booted it from the HDD. But the thing is, the boot is super weird. It takes about 50 sec to boot.
This is how it goes:

*

*Purple screen

*Screen power saving mode

*Black screen with something written in the top left corner (/dev/sda1 something, I also noticed the word "clean")

*Ubuntu load screen

*Black screen (I think)

*Instant load of desktop (w/o animations, desktop just shows up)

I don't think this is how it's supposed to boot, is it?
What do you think about the issue? And how should I fix it?
edit - SPECS
Processor: AMD Athlon(tm) II X2 250, 3.00 GHz
RAM: 2x 4gb DDR3
Motherboard: MSI 770-C45 (MS-7599)
GC: NVIDIA Corporation GT216 [GeForce GT 220] (rev a2)
*edit*2 - BOOT TIMES
10.971s apparmor.service
6.207s ModemManager.service
5.117s accounts-daemon.service
4.990s dev-sda1.device
4.982s snapd.firstboot.service
3.130s networking.service
3.035s systemd-logind.service
2.809s console-setup.service
2.779s NetworkManager.service
2.727s pppd-dns.service
2.469s avahi-daemon.service
2.186s gpu-manager.service
2.091s polkitd.service
1.873s lightdm.service
1.784s apport.service
1.530s grub-common.service
1.476s systemd-tmpfiles-setup.service
1.417s plymouth-start.service
1.326s systemd-journal-flush.service
1.132s plymouth-quit-wait.service
1.128s systemd-tmpfiles-setup-dev.service
1.103s colord.service
1.061s systemd-journald.service

A: The black screens are due to changes in resolution and often times also created by changing graphics drivers.
Plus as you choose on installation your system logs in automatically, hence no login screen.
Seems everything is fine.


text:
Q: Possible Scope problems in a JSF2 web application I´ve a JSF web application using SPRING3 + JSF2 (mojarra 2.1.12) and I´m having some problems that I think can be derived of a bad choose of the Scope of one controller in one combo of the JSF2+primefaces interface.
This combo functionality allows the user to choose one of the internal xhtml subpages and a button that automatically redirects you to that page.
The website uses a template technology: there is template (standard.xhtml) with the JSF2 code and using this template there are  several pages: a inicio.xhtml that is the home page and a contact page (contacto.xhtml). In both pages the combo is displayed properly.
The following code it is working properly only if you´re navigating at the home page (incio.xhtml) but when you´re in other part of the web (i.e. contacto.xhtml) it displays the combo with all the options, but the button doesn´t work at all.
Here it´s my code in standard.xhtml file:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<f:view contentType="text/html">
       <h:head>
             //HEAD
       </h:head>

                           //CODE
                           //CODE to go from one page (inicio.xhtml) to other (contacto.xhtml)

<h:commandLink value="${msg.app_menu_contacto}" action="mContacto" />

                           //MORE CODE
                           <h:form>
                                  //MORE CODE
                                  <h:panelGrid id="buscar" columns="2" style="margin-top:20px;" cellpadding="5">

                                        <f:selectItem itemLabel="${msg.app_comun_seleccionar}" itemValue="" />
                                        <f:selectItems value="#{buscador.procedimientos}" var="proc" itemLabel="#{proc.codigo}" itemValue="#{proc.valor}"/>

                                  </h:panelGrid>
                                  </h:form>

</f:view>

In the faces-navigation.xml we have these lines (faces-navigation is only used in several inherited parts of the code):
<navigation-case>
<from-outcome>mContacto</from-outcome>
<to-view-id>/views/comun/contacto.xhtml</to-view-id>
<redirect />
</navigation-case>

Code of the xhtml home page where it is working:
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
       xmlns:ui="http://java.sun.com/jsf/facelets"
       xmlns:h="http://java.sun.com/jsf/html"
       xmlns:f="http://java.sun.com/jsf/core"
       xmlns:fn="http://java.sun.com/jsp/jstl/functions"
       xmlns:c="http://java.sun.com/jsp/jstl/core"
       xmlns:p="http://primefaces.org/ui"
    xmlns:sec="http://www.springframework.org/security/tags"
       template="/WEB-INF/layouts/standard.xhtml">

//Code independent of the combo or button failing
// it uses ui:define to show different components in the page.

    </ui:composition>

and this is the controller code:
@Controller("buscador")
//@Scope("Session")  Do not work with "request", "view" or without scope
public class BuscadorController implements Serializable {

       public List<ValorCombo> getProcedimientos() {
             //Code that returns a list of pair String to show in the combo, name of the xhtml page should be redirected
}

public String direccion() {
//CODE
String salida = "proc/"+procedimiento+"?faces-redirect=true";
//more CODE
return salida;
}

}
I have tried this but it doesn´t work neither.
http://balusc.blogspot.com.es/2011/09/communication-in-jsf-20.html
how can I solve this problem?
Thanks!


text:
Q: MySQL Select Dates in the Past: Problem with MAX and GROUP BY So, the query I'm trying to make looks like this right now:
SELECT `jid`, MAX(`start`) as `start` FROM `dates` WHERE `start` < NOW() GROUP BY `jid`

The table dates basically holds a DATETIME value start associated with a job.
As you probably guessed, jid is the id of a job, stored in another table.
A job can have many dates
What I'm trying to accomplish is to find out what jobs have all their start dates in the past.
My thought was to select the highest values of the start dates, grouped by jid and if they were in the past, it would imply that all other dates associated with the same job are also in the past.
This query isn't working because it's checking for start dates in the past and then selecting the highest of those. This doesn't exclude the possibility of another date for the same job, lying in the future.
I have no idea how I could proceed now. Any help or clue is appreciated.
Cheers - Tom

A: You have to use HAVING :
SELECT jid, MAX(start) as start
FROM dates
GROUP BY jid
HAVING MAX(start) < NOW();

HAVING acts a bit like WHERE. It filters out the rows after they were selected. Usually (and actually, I can't think of any other case), you only use HAVING with aggregate functions.
(I hope you really inserted dates in the future in your table, though!)


text:
Q: HashMap vs Switch statement performance A HashMap essentially has O(1) performance while a switch state can have either O(1) or O(log(n)) depending on if the compiler uses a tableswitch or lookup switch.
Understandably, if a switch statement is written as such,
switch (int) {
    case 1:
    case 2:
    case 3:
    case 4:
    default:
}

then it would use a tableswitch and clearly have a performance advantage over a standard HashMap. But what if the switch statement is sparse? These would be two examples that I would be comparing:
HashMap<Integer, String> example = new HashMap<Integer, String>() {{
        put(1, "a");
        put(10, "b");
        put(100, "c");
        put(1000, "d");
}};

.
switch (int) {
    case 1:
        return "a";
    case 10:
        return "b";
    case 100:
        return "c";
    case 1000:
        return "d";
    default:
        return null;
}

What would provide more throughput, a lookupswitch or HashMap?
Does the overhead of the HashMap give the lookupswitch an advantage early but eventually tapers off as the number of cases/entries increase?
Edit: I tried some benchmarks using JMH, here are my results and code used. https://gist.github.com/mooman219/bebbdc047889c7cfe612
As you guys mentioned, the lookupswitch statement outperformed the HashTable. I'm still wondering why though.

A: The accepted answer is wrong here.
http://java-performance.info/string-switch-implementation/
Switches will always be as fast as if not faster than hash maps.  Switch statements are transformed into direct lookup tables.  In the case of Integer values (ints, enums, shorts, longs) it is a direct lookup/jmp to the statement.  There is no additional hashing that needs to happen.  In the case of a String, it precomputes the string hash for the case statements and uses the input String's hashcode to determine where to jump.  In the case of collision, it does an if/else chain.   Now you might think "This is the same as HashMap, right?"  But that isn't true.  The hash code for the lookup is computed at compile time and it isn't reduced based on the number of elements (lower chance of collision).
Switches have O(1) lookup, not O(n).  (Ok, in truth for a small number of items, switches are turned into if/else statements.  This provides better code locality and avoids additional memory lookups.  However, for many items, switches are changed into the lookup table I mentioned above).
You can read more about it here
How does Java's switch work under the hood?

A: It depends:

*

*If there are a few items | fixed items. Using switch if you can ( worst case O(n))

*If there are a lot of items OR you want to add future items without modifying much code ---> Using hash-map ( access time is considered as constant time)

*You should NOT try to improve performance for the case, because the difference in execution time is nanoseconds. Just focus on readability/maintainability of your code. Is it worth optimizing a simple case to improve a few nanoseconds?

A: TL/DR
Base it on code readability and maintainability.  Both are cost O(1) and provide almost no difference (though switches generally will be slightly faster).
In this particular case a map would be faster, as a switch returns an address and then must go to that address to identify the return value. (A rare case example).  If your switch is just calling functions anyways, a Map would also be faster.
To make things faster, I would ensure using numeric cases and avoid using strings via constants or enumerators (typescript).
(edited) I confirmed by expectation:  How does Java's switch work under the hood? with switches.
More detailed answer
In the weeds:
A switch statement will usually be higher performance.  It creates a lookup table and goto reference and starts at that point.  However there are exceptions.
When you utilize a simple switch such as return map.get(x) vs. switch(1=>'a', 2=>'b', etc).  That is because the map can directly return the value desired where the switch will stop map the addresses and continue until break or the end is met.
In any event, they should be extremely similar in execution cost.
Think about maintainability and readability of the code
Using a map decouples the data, which can gain the benefit of creating "switch" cases dynamically.  More detailed below.
If there are several complex functions/processes you need to handle, it may be easier to read/write if you utilize a map instead.  Especially if the switch statement starts to exceed 20 or 30 options.
Personally used case example for maps:
I have been utilize the following pattern for flux (Redux/useReducer) in React applications for some time.
I create a central map where I map the trigger as the key, and the value is a functional reference. I can then load cases where and when it makes sense.
Initially I used this to be able to break the use cases down to reduce file size and group cases of similar function together in a more organized fashion.  Although I later evolved it to be loaded in domains and configured the events and data in a domain hook, like useUser, useFeedback, useProfile, etc...
Doing so allowed me to create the default state, initialization functions, events, and so forth into a logical file structure, it also allowed me to keep the footprint low until needed.
One note to keep in mind
Using a map does not allow for drop through, though most people consider this code smell anyways.  At the same time it protects from accidental fall through.

A: In your case, since you are using an Integer key for your HashMap and a plain 'int' for your switch statement, the best performing implementation will be the switch statement unless the number of passes through this section of code is very high (tens or hundreds of thousands).

A: If I have that kind of example I use Guava ImmutableMaps (sure You can use java 9 builder as well).
private static final Map<String, String> EXAMPLE = ImmutableMaps.<String, String>>builder()
    .put("a", "100")
    .put("b", "200")
    .build();

That way they are immutable and initated only once.
Sometimes I use strategy pattern that way:
private static final Map<String, Command> EXAMPLE = ImmutableMaps.<String, String>>builder()
    .put("a", new SomethingCool())
    .put("b", new BCool())
    .build();

private static final Command DEFAULT= new DefCommand();

Use:
EXAMPLE.getOrDefault("a", DEFAULT).execute(); //java 8

About performance just pick readability. You will thank me later (1 year later) :D.


text:
Q: how to run spring boot project-test.jar file from command line? Following is my test class file
@RunWith( SpringJUnit4ClassRunner.class )
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = {Application.class, SecurityConfig.class})

public class PolicyTest {

After running a build i got two jar files, one is src jar and another is test jar file...I want to run project-test.jar from command line
Note: developed this project on Netbeans IDE


text:
Q: What is a general purpose of "Update SQL layer" in QGIS 3? Can someone explain to me, what is a general purpose of "Update SQL layer"?
When I "update" it becomes not editable... (see gif ▼)

A: Regarding the layer becoming uneditable after selecting and applying an SQL query via "Update SQL Layer" on the layer context menu, I discovered selecting "Change Data Source" from the same context menu and then just reselecting the original data source returns the table to editable.
I haven't tested this but my guess is the problem results from "Update SQL Layer" replacing the original data source with a database view (which are not editable). So reselecting the original source does the trick. I think no matter what you do in that SQL window it always creates a view even with just SELECT * FROM "thetablename". This is my theory, anyways. Either way reselecting the original table works to recover editability.
Using set filter is probably the best idea. I am guessing the project does the filtering of what is displayed


text:
Q: Get FormCollection out controllerContext for Custom Model Binder I had a nice function that took my FormCollection (provided from the controller).  Now I want to do a model bind instead and have my model binder call that function and it needs the FormCollection.  For some reason I can find it.  I thought it would have been
controllerContext.HttpContext.Request.Form

A: Try this:
var formCollection = new FormCollection(controllerContext.HttpContext.Request.Form)

FormCollection is a type we added to ASP.NET MVC that has its own ModelBinder. You can look at the code for FormCollectionBinderAttribute to see what I mean.

A: Accessing the form collection directly appears to be frowned on. The following is an example from an MVC4 project where I have a custom Razor EditorTemplate that captures the date and time in separate form fields. The custom binder retrieves the values of the individual fields and combines them into a DateTime.
public class DateTimeModelBinder : DefaultModelBinder
{
    private static readonly string DATE = "Date";
    private static readonly string TIME = "Time";
    private static readonly string DATE_TIME_FORMAT = "dd/MM/yyyy HH:mm";
    public DateTimeModelBinder() { }

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext == null) throw new ArgumentNullException("bindingContext");

        var provider = new FormValueProvider(controllerContext);
        var keys = provider.GetKeysFromPrefix(bindingContext.ModelName);
        if (keys.Count == 2 && keys.ContainsKey(DATE) && keys.ContainsKey(TIME))
        {
            var date = provider.GetValue(string.Format("{0}.{1}", bindingContext.ModelName, DATE)).AttemptedValue;
            var time = provider.GetValue(string.Format("{0}.{1}", bindingContext.ModelName, TIME)).AttemptedValue;
            if (!string.IsNullOrWhiteSpace(date) && !string.IsNullOrWhiteSpace(time))
            {
                DateTime dt;
                if (DateTime.TryParseExact(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0} {1}", date, time),
                                            DATE_TIME_FORMAT,
                                            System.Globalization.CultureInfo.CurrentCulture,
                                            System.Globalization.DateTimeStyles.AssumeLocal,
                                            out dt))
                    return dt;
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}

A: Use bindingContext.ValueProvider (and bindingContext.ValueProvider.TryGetValue, etc.) to get values directly.


text:
Q: php get URL of current file directory Might be an easy question for you, but I'm breaking my head over this one.
I have a php file that needs to know it's current directory url to be able to link to something relative to itself.
For example, currently I know to get the current directory path instead of the url. When I use this I get the path:
realpath(__DIR__)

result:
/Applications/MAMP/htdocs/mysite/dir1/dir2/dir3

But this would be my desired result:
http://localhost:8888/dir1/dir2/dir3

Note that this is not the location of the current page. The page calls a file from "http://localhost:8888/dir1/dir2/dir3/myfile.php"
And "myfile.php" has the script from above.
-- edit to elaborate more details --
Thanks for your answers. But I get that I need to add more detail.

*

*http://localhost:8888/index.php calls: "http://localhost:8888/dir1/dir2/dir3/myfile.php"

*"myfile.php" needs to know it's place in the universe :) "Where am I"

*"myfile.php" should know it's url location is "http://localhost:8888/dir1/dir2/dir3/"

A: If your URL is like this: https://localhost.com/this/is/a/url
$_SERVER['DOCUMENT_ROOT'] - gives system path [/var/www/html/this/is/a/url]
$_SERVER['PHP_SELF'] - gives the route of the current file (after the domain name) [/this/is/a/url]
$_SERVER['SERVER_NAME'] - gives the domain name [localhost.com]
$_SERVER['HTTP_REFERER'] - gives the correct HTTP(S) protocol and domain name. [https://localhost.com]

If you would like to get the full url, you can do something like:
echo $_SERVER['HTTP_REFERER'] . $_SERVER['PHP_SELF'];
However, I do believe in this case, that all you need is the relative path.. and in that case you should only need to use $_SERVER['PHP_SELF'];

A: I've found a solution here:
https://stackoverflow.com/a/1240574/7295693
This is the code I'll now be useing:
function get_current_file_url($Protocol='http://') {
   return $Protocol.$_SERVER['HTTP_HOST'].str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(__DIR__));
}

A: Use echo $_SERVER['PHP_SELF'];
For example if the URL is http://localhost/~andy/test.php
The output would be:
/~andy/test.php
That's enough to generate a relative URL.
If you want the directory your current script is running in - without the filename  - use:
echo dirname($_SERVER['PHP_SELF']);
In the case above that will give you /~andy (without test.php at the end). See http://php.net/manual/en/function.dirname.php
Please note that echo getcwd(); is not what you want, based on your question. That gives you the location on the filesystem/server (not the URL) that your script is running from. The directory the script is located in on the servers filesystem, and the URL, are 2 completely different things.
There is also a function to parse URL's built in to PHP: http://php.net/manual/en/function.parse-url.php

A: Based on your question, I believe this will get you what your want:
$_SERVER['HTTP_HOST'] . substr($_SERVER['REQUEST_URI'], 0, strrpos($_SERVER['REQUEST_URI'], "/"));

Reference:

*

*$_SERVER['HTTP_HOST'] - In your case this would return: http://localhost:8888

*$_SERVER['REQUEST_URI'] - In your case this would return: /dir1/dir2/dir3/myfile.php
With the added substr() and strrpos() methods, you can strip the _myfile.php` off of the end to get the desired result:
http://localhost:8888/dir1/dir2/dir3


text:
Q: RegEx match for groups that show up in different order I'm trying to come-up with a RegEx Match Pattern (preferably for Python) for the following possible strings combinations. These are JVM generic args strings with –D switches that may appear in any random order.
How do I account for such random-ness in my RegEx?
So far I have this, but it doesn't work for all the scenarios below. Matches only #1
\-javaagent:.+\/javaagent.jar\s+-Dappdynamics\.agent\.applicationName=[A-Za-z0-9\-\_]+\s+-Dappdynamics\.agent\.tierName=[A-Za-z0-9\-\_]+\s+\-Dappdynamics\.agent\.nodeName=[A-Za-z0-9\-\_\$\{\}]+\s+\-Dappdynamics\.agent\.uniqueHostId=[A-Za-z0-9\-\_\$\{\}]+

Search contexts:
1.
-javaagent:/path/to/folder/with/javaagent.jar -Dappdynamics.agent.applicationName=1234_APP-NAME -Dappdynamics.agent.tierName=myTIER-NAME -Dappdynamics.agent.nodeName=${WAS_SERVER_NAME} -Dappdynamics.agent.uniqueHostId=${HOSTNAME}

2.
-javaagent:/path/to/folder/with/javaagent.jar -Dappdynamics.agent.tierName=myTIER-NAME -Dappdynamics.agent.applicationName=1234_APP-NAME -Dappdynamics.agent.nodeName=${WAS_SERVER_NAME} -Dappdynamics.agent.uniqueHostId=${HOSTNAME}

3.
-javaagent:/path/to/folder/with/javaagent.jar -Dappdynamics.agent.uniqueHostId=${HOSTNAME} -Dappdynamics.agent.applicationName=1234_APP-NAME -Dappdynamics.agent.tierName=myTIER-NAME -Dappdynamics.agent.nodeName=${WAS_SERVER_NAME}

A: An out of order regex (random placement) of unique items would be
something like this form.
-javaagent:(\S+)(?:.*?\s+-Dappdynamics(?:(\S+APP-NAME)|(\S+TIER-NAME)|(\S+{WAS_SERVER_NAME})|(\S+{HOSTNAME})))*

https://regex101.com/r/WXKWqW/1
Note - Out-of-Order basically means, each literal item is always captured
in the same group, but it can be matched anywhere within the line.
Obviously, the items should be unique.
In this example, 4 items per line are captured as well as the agent.
If an item is duplicated in the line, only the last one is captured.
Explained
 -javaagent:
 ( \S+ )                       # (1), agent

 (?:
      .*?                           # anything between
      \s+
      -Dappdynamics
      (?:                           # Any of these
           ( \S+ APP-NAME )              # (2), app
        |
           ( \S+ TIER-NAME )             # (3), tier
        |
           ( \S+ {WAS_SERVER_NAME} )     # (4), server
        |
           ( \S+ {HOSTNAME} )            # (5), host
      )
 )*


text:
Q: How to reduce the time delay between Activity Pause and Re-Start(by a Service)? I am implementing an activity to be on top always ( generally implementing a lock screen),
The Algorithm is simple as :

*

*Start Activity

*Disable All Hardware buttons, disable backpress,camera lock, volume buttons etc.

*Whenever activity is paused call a service to check and restart the activity.

Refer to these answers for the logic: Answer 1, Answer 2
There is a 6-7 seconds delay whenever the Activity is paused, and is restarted by the Service. How may I reduce this time delay between the pause and restart of my Activity.
On Pause and On Resume Code:
protected void onPause() {
    isFront = false;
    Intent lockHelper = new Intent( this, LockHelper.class);
    startService( lockHelper );
    super.onPause();
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
    if(keyCode==KeyEvent.KEYCODE_CAMERA)
        return true;
    else if(keyCode==KeyEvent.KEYCODE_VOLUME_DOWN)
        return true;
    else if(keyCode==KeyEvent.KEYCODE_VOLUME_UP)
        return true;
    else if(keyCode==KeyEvent.KEYCODE_HOME)
        return true;
    else if(keyCode==KeyEvent.KEYCODE_POWER)
        return true;
    else
        return true;
}

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent keyEvent) {
    if(keyCode==KeyEvent.KEYCODE_HOME)
        return true;
    else if(keyCode==KeyEvent.KEYCODE_POWER)
        return true;
    else
        return true;
}

@Override
public void onBackPressed() {
}

@Override
protected void onResume() {
    isFront = true;
    Intent lockHelper = new Intent( this, LockHelper.class);
    startService( lockHelper );
    super.onResume();
}

}
Service is:
public class LockHelper extends Service {
@Override
public void onStart(Intent intent, int startId) {
    if(Locker.isFront == false){
        Intent locker = new Intent( this, Locker.class);
        locker.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity( locker );
        stopSelf();
    }
}

public LockHelper() {
}

@Override
public IBinder onBind(Intent intent) {
    throw new UnsupportedOperationException("Not yet implemented");
}
}

A: The code in your onPause, onStop and onDestroy should execute as fast as possible. That is to say, don't block these methods by putting a lot of code here. But again, it depends on what you are doing here. If those things are really important, I am not sure how you can reduce the time delay.

A:
"is how may I reduce this time delay between the pause and restart of my Activity."

Did you measure the time cost happened this two interval?
Basically, two type of task: one is system task and your app task.
adb logcat -b system -v threadtime should print out all the system bahvoir related to Activity/Service start/stop, along with the timestamp.
You should/could reduce the time spend on your app as much as possible but there is no way to reduce the time cost of system behavior.


text:
Q: Cannot add to firebase using polymer project's  I am using polymer's  to add records to my firebase. I am able to successfully log in buy cannot write, i get an error:
'Uncaught TypeError: Cannot read property 'ref' of undefined'.

Has any one successfully tried to add record using new firebase-element?
JS Bin is at http://jsbin.com/nohujoceto/edit?html,console,output


text:
Q: Redirect old custom Posts URL to new WordPress URL In short, I converted my old custom site to a new WordPress site, the domain remains same, I used PHP to insert thousands of old articles with its comments into WordPress database maintaining the same id sequence, meaning if the old links were:
www.mysite.com/index.php?id=11058
www.mysite.com/index.php?category=12
Than the new link are:
www.mysite.com/?p=11058
www.mysite.com/?cat=12
Everything was done well, the only problem is that I don't want to lose the old backlinks, and I want to use PHP to redirect, for example:
    if (isset($_GET['old_id'])) {  $id=$_GET['old_id']; $Wordpress_post_id = $id; }

How can I use this code in WordPress? and is this method better or redirect by .htaccess? Or is there another way that is better than the two?

A: I would do this in template_redirect:

This action hook executes just before WordPress determines which template page to load. It is a good hook to use if you need to do a redirect with full knowledge of the content that has been queried.

add_action(
    'template_redirect',
    static function() {

        if(!isset($_GET['old_id'])){
            return;
        }

        // Do custom look up here, possibly get_posts()

        // Once you determine where to go, use wp_safe_redirect with the appropriate code (probably 301)
        // https://developer.wordpress.org/reference/functions/wp_safe_redirect/

        // Also possibly use get_permalink() to find the canonical link for the object
        // https://developer.wordpress.org/reference/functions/get_permalink/
    }
);

Unfortunately, the "custom stuff" is really dependent upon how you stored things. Is it post meta, did you manually insert post IDs, is it a custom lookup table?
If it is a true mapping of legacy IDs to PostIDs, you might even be able to use a plugin such as Redirection with a simple rule.

A: Since you mentioned (and tagged) .htaccess you could do it like this at the top of the .htaccess file (before the # BEGIN WordPress comment marker):
# Redirect "/index.php?id=<number>" to "/?p=<number>"
RewriteCond %{QUERY_STRING} ^id=(\d+)
RewriteRule ^index\.php$ /?p=%1 [R=301,L]

# Redirect "/index.php?category=<number>" to "/?cat=<number>"
RewriteCond %{QUERY_STRING} ^category=(\d+)
RewriteRule ^index\.php$ /?cat=%1 [R=301,L]

Where %1 is a backreference to the captured group in the preceding CondPattern in both cases. ie. the value of the id and category URL parameters respectively.
Test with 302 (temporary) redirects to avoid caching issues.

A: I recently had to do the same thing. I reorganized a site and moved the structure from the root (and all directory structure) to the blog folder. I experimented with several methods for WordPress, analyzed logs for issues, etc., and implemented the following method.
First I created a list of every page, article, etc.
Then I created a .htaccess file located in the site root directory.
In my example below I show the redirect for one page, but with two entries (trailing slash or not). The bottom portion handles files and directors, etc.
My .htaccess is about 600 lines long. I have not noticed any performance issues with the redirects.
Note: I am using a 302 for redirects, if yours are permanent, consider using a 301.
<IfModule mod_rewrite.c>
  <IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
  </IfModule>

  RewriteEngine On

  RewriteRule ^aboutme$ https://www.example.com/blog/aboutme/ [L,R=302]
  RewriteRule ^aboutme/$ https://www.example.com/blog/aboutme/ [L,R=302]

  # Handle Authorization Header
  RewriteCond %{HTTP:Authorization} .
  RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Redirect Trailing Slashes If Not A Folder...
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} (.+)/$
  RewriteRule ^ %1 [L,R=301]

  # Send Requests To Front Controller...
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^ index.php [L]
</IfModule>


text:
Q: Android View.requestRectangleOnScreen: Scroll-error in API-23! How, do I work around it? I am developing my first Android App and after a good start, I have spent days of deep debugging on a problem, which by now seems to be an error in the implementation of View.requestRectangleOnScreen in API-23 and probably many levels before that.  Just now, I have discovered that the implementation of this routine is changed significantly in API-25.
The problem is that a request for focus on an EditText placed inside a HorizontalScrollView may cause the HorizontalScrollView to scroll away from the field requesting the focus.
In my case it is an EditText with centered text, which is then placed in the center of 1048576 pixels and scrolled roughly half a million pixels to the right making the text centered and visible (this part is perfectly ok!) But then this offset of half a million pixels is propagated up the parent chain and makes the HorizontalScrollView move to its far right and far away from the input field.
I have tracked it down to the View.requestRectangleOnScreen routine, which in the API-23 sources is as follows:
public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
    if (mParent == null) {
        return false;
    }

    View child = this;

    RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
    position.set(rectangle);

    ViewParent parent = mParent;
    boolean scrolled = false;
    while (parent != null) {
        rectangle.set((int) position.left, (int) position.top,
                (int) position.right, (int) position.bottom);

        scrolled |= parent.requestChildRectangleOnScreen(child,
                rectangle, immediate);

        if (!child.hasIdentityMatrix()) {
            child.getMatrix().mapRect(position);
        }

        position.offset(child.mLeft, child.mTop);

        if (!(parent instanceof View)) {
            break;
        }

        View parentView = (View) parent;

        position.offset(-parentView.getScrollX(), -parentView.getScrollY());

        child = parentView;
        parent = child.getParent();
    }

    return scrolled;
}

The idea is to make the rectangle visible by scrolling it onto the screen in every containing View, starting at the leaf level and passing the request up the chain of parents.  The initial rectangle is given in child coordinates, which of course have to be adjusted as we work our way up the chain of parents.  This is done with the statement
position.offset(-parentView.getScrollX(), -parentView.getScrollY());

close to the end of the code above.
What I have found, is that this is wrong because we are transforming the position given in child coordinates using the scroll X/Y values pertaining to the parent coordinates.  Using the scroll X/Y of the child instead solved my problem but it was not possible to make a perfect override of this routine because it relies on private member variables.  Specifically, I found no way of mimicing the mAttachInfo.
Now, digging a bit further, I found that the code for this routine in API-25 has changed significantly and (IMHO) correctly to the following:
public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
    if (mParent == null) {
        return false;
    }

    View child = this;

    RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
    position.set(rectangle);

    ViewParent parent = mParent;
    boolean scrolled = false;
    while (parent != null) {
        rectangle.set((int) position.left, (int) position.top,
                (int) position.right, (int) position.bottom);

        scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);

        if (!(parent instanceof View)) {
            break;
        }

        // move it from child's content coordinate space to parent's content coordinate space
        position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());

        child = (View) parent;
        parent = child.getParent();
    }

    return scrolled;
}

The most important change being the line
position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());

where the scroll X/Y adjustment is now made with child values.
Now, I have two questions.
First, do you agree with my observations above?
Second, how do I implement an App that can be used on both API-23 and API-25 under the given circumstances?
My current thoughts are to sub class the EditText and override the requestRectangleOnScreen method such that when the API is 25 and above, it just calls the super class method and when the API is below 25, I basically do a full override using code along the lines of the code from API-25 but then missing out on the mAttachInfo part.


text:
Q: can't mount /boot/efi: dependency failed my ubuntu 20.04 vbox machine, with kernel 5.11.3 can't work correctly. Last friday I reboot my virtual machine, it stucks for about 1 minute halting, and then the following error message is generated :
enter image description here
Despite has errors , I can still got a shell, but my x11 can't work, it means I can't get a Graphic interface. so does the netcard. First time I think it may because my disk is almost full, the /dev/sda2 mounted in / is about 96% used. I delete some big file and reboot, but useless. Before asking this question, I've tried some methods, but it doesn't work.

*

*I've checked blkid output and /etc/fstab file, the uuid is same enter image description here
enter image description here

*replace the uuid in /etc/fstab with /dev/sda1 and reboot

*I mount the /dev/sda1 in /boot/efi manully, and it does't output anything, but when I check the dh -f command, I found /dev/sda1 is not mounted. type ls -l /boot/efi, it has nothing.

*it seems that I can mount /dev/sda1 in /mnt directory. Thanks very much for giving me some advice!


text:
Q: Paragraph character in URL? I just ran across this an Google App Engine article that uses that funny backwards 'P' character in some URL's (look near the top of the first code box). You know that character that your high school English teacher used to mark new paragraphs (which I've learned, thanks to Wikipedia, is called a "pilcrow").
I've never seen this in a URL.  So which is it?

*

*This has a standard specific meaning which is ...

*This is a typo, it should be ...

*This is something that somebody at Google just made up. What they might mean is ...

*What character?  I'm seeing things.

A: &para is in the URL which forms part of the html escape sequence ¶, i.e. ¶. It is odd browser behavior that, given the escape sequence is not complete (missing ;), Chrome is still rendering the symbol. The escape sequence itself has just not been escaped correctly in the snippet I believe..

A: What happens is that the page contains the sequence &para some browsers (Chrome at least) interpret that as if it was ¶ the escape code for the symbol ¶. Funny browser behaviour, but the page should not have contained raw ampersands.

A: Escaping everything properly and dealing with divergent browser behavior is a pain: Accidental HTML entities in urls.
The odd thing in this case is that &param should not be recognized by the browser as &para and then m.

A: My shot... rendering bug.
IE - shows it
Chrome - Shows it
FireFox - Displays the correct & symbol (used in URLS+parameters)
Checked source with the 3 browsers, and they all show the & char.


text:
Q: Burgers' equation after rarefaction wave catches up with the shock Burgers' equation
$$u_t+\Bigl(\frac{u^2}{2}\Bigr)_x=0$$
with initial conditions as below:
$$\left\{\begin{aligned}&u(x,0)=2&&\text{if $0<x<1$}\\
&u(x,0)=0&&\text{otherwise}
\end{aligned}\right.$$
So on the right hand side of $1$, it would have a shock wave of $x-1=t$.
On the left hand side of $0$, it will have a rarefaction wave of $x=2t$.
At some $T_c$, the rarefaction wave would catch up with the shock wave.
But the question asks what's the location of $x_s(t)$ after the two waves meet?  And it asks to solve it in two ways:

*

*Solve an ODE using Rankine-Hugoniot jump condition

*For $t>T_c$, the exact solution is triangular-shaped. Use conservation law(?) to determine $x_s(t)$ based on the area of this triangle?

I am very lost on this problem...  When $t<T_c$, I know the shock location is $(1+t,t)$, does it change after they meet?

A: Since the question is old, I'll give the complete solution, not just the $x_s$ part.
Before $T_c$
Draw the $xt$ coordinates, with $t$-axis pointing up.  From the given $u(x,0)$, we find three families of characteristic lines:

*

*vertical lines $x=x_0$ with $x_0\le 0$

*slope $1/2$ lines $t=\frac12(x-x_0)$ with $0<x_0<1$

*vertical lines $x=x_0$ with $x_0\ge 1$

There is a gap between the families 1 and 2: it's a triangular region bounded by $x=0$ and $t=\frac12 x$.
This is the rarefaction wave: within this region, all characteristic lines go through $(0,0)$, the origin of the wave.
Therefore, the line through $(x,t)$ has slope $t/x$, which yields
$$
u(x,t)=x/t ,\qquad   0<x< 2t
$$
This is family 4 of characteristics.
The families 2  and 3 appear to overlap. This means they are separated by shock wave, which originates at $x=1$ at time $t=0$ and
moves to the right with velocity $\frac12(2+0)=1$ (the mean of velocities in front and behind the shock, as the jump condition says). Its trajectory is $x=1+t$.
The front edge of rarefaction wave $x=2t$  meets the shock wave $x=1+t$ when $t=1$. Thus, $T_c=1$.   The meeting point is $(2,1)$.
After $T_c$
The characteristics of family 2 are no more; the shock is between families 3 and 4. The speed of shock wave as it passes through $(x,t)$ is the mean
of velocities in front and behind the shock:
$$
\frac{1}{2}\left( \frac{x}{t} +0  \right)  = \frac{x}{2t}
$$
Therefore, the trajectory of shock wave is described by the ODE
$$
\frac{dx}{dt}=\frac{x}{2t}
$$
Solve this separable ODE with the initial condition   $x(1)=2$ to get
$$
x_s(t) = 2 \sqrt{t}
$$
This is the trajectory of shock for $t>1$.
Second method, conservation law
Introduce  the quantity $P(t)=\int_{-\infty}^\infty u(x,t)\,dx$. It is actually independent of $t$  because
$$\frac{dP}{dt} = \int_{-\infty}^\infty  u_t \,dx = - \int_{-\infty}^\infty  (u^2/2) _x \,dx = (u^2/2)  \bigg|_{-\infty}^\infty =0$$
Since $P =2$ at $t=0$, it stays at $2$ for all times. At time $t>T_c$ the function $u$ is equal to $x/t$ for $0< x <x_s$, and is zero otherwise. Thus, its integral is
$$
\frac{1}{t} \frac{x_s^2}{2}
$$
Equating the above to $2$, we once again get
$$
x_s(t) = 2 \sqrt{t}
$$


text:
Q: Secure cookie not being set on AWS ASP.NET MVC website We had a security review that revealed that the cookies in our ASP.NET MVC application were not being set as secure, despite having the following setting in web.config:
<httpCookies requireSSL="true" httpOnlyCookies="true" />

The website is not using forms authentication so no need for <forms requireSSL="true"> setting.
The website is hosted on an AWS app server and is accessed via an ELB. Internally on the app server the website is HTTP but externally it is HTTPS.
I've tried to implement a solution found here:
http://www.jamescrowley.co.uk/2014/03/07/ssl-termination-and-secure-cookiesrequiressl-with-asp-net-forms-authentication/
Added the following rewrite rules to this to web.config:
<rewrite>
   <rules>
        <rule name="HTTPS_AlwaysOn" patternSyntax="Wildcard">
            <match url="*" />
            <serverVariables>
                <set name="HTTPS" value="on" />
            </serverVariables>
            <action type="None" />
            <conditions>
                <add input="{HTTP_X_FORWARDED_PROTO}" pattern="https" />
            </conditions>
        </rule>
    </rules>
</rewrite>

And added HTTPS variable to the applicationHost.config to contain:
<rewrite>
    <allowedServerVariables>
        <add name="HTTPS" />
    </allowedServerVariables>
</rewrite>

Unfortunately this causes the ELB to fail. When speaking to our internal AWS support team they say this is because the ELB health check is failing. There is a health.html page in the root of the website. Is there a way of applying a condition to the above so that it ignores this for the health.html page which the ELB uses? I'm new to rewrite rules so not fully versed in the syntax and the way they work.

A: I can't test this yet, but in theory I think you would just need to change your conditions:
        <conditions logicalGrouping="MatchAll" >
            <add input="{HTTP_X_FORWARDED_PROTO}" pattern="https" />
            <add input="{REQUEST_URI}" negate="true" pattern="^/health.html$" ignoreCase="true" />
        </conditions>


text:
Q: How to auto-remove trailing whitespaces on save in Matlab? I don't find an essential feature in Matlab 2012b:
Remove trailing whitespaces on save.

Related:
How to auto-remove trailing whitespace in Eclipse?
Aptana 3 - How remove trailing whitespaces on save

A: I had the same need, and wrote a little script to do something close. Put the following in a MATLAB desktop shortcut. Whenever you click the shortcut button, it will strip trailing whitespace from the active file in the editor. Not quite as good as automatically doing it on save - you need to remember to press the button before saving - but nearly. Tested on 11b, 12a, and 13b, but should also be fine on 12b.
Hope that helps!
% Temp variable for shortcut. Give it an unusual name so it's unlikely to
% conflict with anything in the workspace.
shtcutwh__ = struct;

% Check that the editor is available.
if ~matlab.desktop.editor.isEditorAvailable
    return
end

% Check that a document exists.
shtcutwh__.activeDoc = matlab.desktop.editor.getActive;
if isempty(shtcutwh__.activeDoc)
    return
end

% Get the current text.
shtcutwh__.txt = shtcutwh__.activeDoc.Text;

% Remove trailing whitespace from each line.
shtcutwh__.lines = deblank(regexp(shtcutwh__.txt,'[^\n]*(\n)|[^\n]*$', 'match'));

% Reconcatenate lines.
shtcutwh__.addNewline = @(x)sprintf('%s\n',x);
shtcutwh__.lines = cellfun(shtcutwh__.addNewline, shtcutwh__.lines, 'UniformOutput', false);
shtcutwh__.newtxt = horzcat(shtcutwh__.lines{:});

% Set the current text.
shtcutwh__.activeDoc.Text = shtcutwh__.newtxt;

% Delete temp variable.
clear shtcutwh__

A: I don't have enough reputation to comment, but I created a Gist on github, to update Sam Roberts' answer:
It will remember your last cursor position/selection and select back after removing the trailing whitespace.
I also made it remove all trailing blank lines at the end of the editor.
I find it quite useful for longer files
https://gist.github.com/hmaarrfk/8462415
% To remove a Matlab trailing whitespace in the editor
% Original Author: Sam Roberts
% http://stackoverflow.com/questions/19770347/how-to-auto-remove-trailing-whitespaces-on-save-in-matlab
% Modified by Mark Harfouche to remember cursor location
%
%
% Temp variable for shortcut. Give it an unusual name so it's unlikely to
% conflict with anything in the workspace.
shtcutwh__ = struct;

% Check that the editor is available.
if ~matlab.desktop.editor.isEditorAvailable
    return
end

% Check that a document exists.
shtcutwh__.activeDoc = matlab.desktop.editor.getActive;
if isempty(shtcutwh__.activeDoc)
    return
end

% save the old cursor location
shtcutwh__.Selection = shtcutwh__.activeDoc.Selection;

% Get the current text.
shtcutwh__.txt = shtcutwh__.activeDoc.Text;

% Remove trailing whitespace from each line.
shtcutwh__.lines = deblank(regexp(shtcutwh__.txt,'[^\n]*(\n)|[^\n]*$', 'match'));

% remove the trailing blank lines
for n = length(shtcutwh__.lines):-1:1
    if length(shtcutwh__.lines{n}) == 0
        shtcutwh__.lines(n) = [];
    else
        break
    end
end

% Reconcatenate lines.
shtcutwh__.addNewline = @(x)sprintf('%s\n',x);

shtcutwh__.lines = cellfun(shtcutwh__.addNewline, shtcutwh__.lines, 'UniformOutput', false);

% If you always want to add a newline at the end of the file, comment this line out
% Remove the last newline character
shtcutwh__.lines{end}(end) = '';

shtcutwh__.newtxt = horzcat(shtcutwh__.lines{:});

% Set the current text.
shtcutwh__.activeDoc.Text = shtcutwh__.newtxt;

% Place the cursor back
shtcutwh__.activeDoc.Selection = shtcutwh__.Selection;

% Delete temp variable.
clear shtcutwh__


text:
Q: MySQL - How can I insert multiple rows using select statement? Here is my query:
insert into unique_products values (product_id, serial_numnber, pronexo_code, entry_time, exit_time, guarantee_long, expanded_guarantee_long)
select product_id, serial_number, pronexo_code, start_guarantee_date, start_guarantee_date, guarantee_long, expanded_guarantee_long
from table_24

It throws this error message:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select product_id, serial_number, pronexo_code, start_guarantee_date, start_guar' at line 2

Does anybody know what's the problem and how can I fix it?

A: Remove the VALUES key word from your Query.
Try this:
INSERT INTO unique_products (product_id, serial_numnber, pronexo_code, entry_time, exit_time, guarantee_long, expanded_guarantee_long)
SELECT product_id, serial_number, pronexo_code, start_guarantee_date, start_guarantee_date, guarantee_long, expanded_guarantee_long
FROM table_24;

A: try this :
  insert into unique_products (product_id, serial_numnber,
  pronexo_code, entry_time, exit_time, guarantee_long,
  expanded_guarantee_long)
  select product_id, serial_number, pronexo_code, start_guarantee_date,
  start_guarantee_date, guarantee_long, expanded_guarantee_long
  from table_24

A: Take care at the SQL syntax and at the field name typing:
VALUE keyword is incorrect here, and watch serial_numnber or serial_number correct spelling for your field name:
insert into unique_products (product_id, SERIAL_NUMBER, pronexo_code, entry_time, exit_time, guarantee_long, expanded_guarantee_long)
select product_id, SERIAL_NUMBER, pronexo_code, start_guarantee_date, start_guarantee_date, guarantee_long, expanded_guarantee_long
from table_24

Details on correct INSERT-INTO-SELECT syntax here.


text:
Q: How do you do signed 32bit widening multiplication on SSE2? This question came up when reviewing the WebAssembly SIMD proposal for extended multiplication.
To support older hardware, we need to support SSE2 and the only vector multiplication operation for 32 bit integers is pmuludq.  (Signed pmuldq was only added in SSE4.1)
(non-widening is relatively easy; shuffle to feed 2x pmuludq and take the low halves of the 4 results to emulate SSE4.1 pmulld).

A: mulhs(a, b) = mulhu(a, b) - (a < 0 ? b : 0) - (b < 0 ? a : 0)
Using that, two signed double-width products can be computed like this,
__m128i mul_epi32(__m128i a, __m128i b) {
    a = _mm_shuffle_epi32(a, _MM_SHUFFLE(3, 1, 1, 0));
    b = _mm_shuffle_epi32(b, _MM_SHUFFLE(3, 1, 1, 0));
    __m128i unsignedProduct = _mm_mul_epu32(a, b);
    __m128i threshold = _mm_set_epi32(INT_MIN, 0, INT_MIN, 0);
    __m128i signA = _mm_cmplt_epi32(a, threshold);
    __m128i signB = _mm_cmplt_epi32(b, threshold);
    __m128i x = _mm_shuffle_epi32(_mm_and_si128(signA, b), _MM_SHUFFLE(2, 3, 0, 1));
    __m128i y = _mm_shuffle_epi32(_mm_and_si128(signB, a), _MM_SHUFFLE(2, 3, 0, 1));
    return _mm_sub_epi32(_mm_sub_epi32(unsignedProduct, x), y);
}

That saves a couple of operations over the other proposal, but it's very close and now it includes a load which could be bad if this code is cold.

A: Big shout out to @GeDaMo on ##asm for helping come up with this solution.
Godbolt
C/C++:
#include <xmmintrin.h>
#include <stdint.h>
#include <tmmintrin.h>
#include <smmintrin.h>
#include <cstdio>

typedef int32_t int32x4_t __attribute__((vector_size(16))) __attribute__((aligned(16)));
typedef int64_t int64x2_t __attribute__((vector_size(16))) __attribute__((aligned(16)));

int64x2_t multiply32_low_s(int32x4_t a, int32x4_t b) {
    auto aSigns = a >> 31;
    auto bSigns = b >> 31;
    auto aInt = a ^ aSigns;
    aInt -= aSigns;
    auto bInt = b ^ bSigns;
    bInt -= bSigns;
    const auto shuffleMask = _MM_SHUFFLE(1,1,0,0);
    auto absProd = _mm_mul_epu32(_mm_shuffle_epi32((__m128i)aInt, shuffleMask), _mm_shuffle_epi32((__m128i)bInt, shuffleMask));
    auto aSignsInt = _mm_shuffle_epi32((__m128i)aSigns, shuffleMask);
    auto bSignsInt = _mm_shuffle_epi32((__m128i)bSigns,shuffleMask);
    auto prodSigns = aSignsInt ^ bSignsInt;
    absProd ^= prodSigns;
    absProd -= prodSigns;
    return (int64x2_t)absProd;
}

int64x2_t multiply32_high_s(int32x4_t a, int32x4_t b) {
    auto aSigns = a >> 31;
    auto bSigns = b >> 31;
    auto aInt = a ^ aSigns;
    aInt -= aSigns;
    auto bInt = b ^ bSigns;
    bInt -= bSigns;
    const auto shuffleMask = _MM_SHUFFLE(3,3,2,2);
    auto absProd = _mm_mul_epu32(_mm_shuffle_epi32((__m128i)aInt, shuffleMask), _mm_shuffle_epi32((__m128i)bInt, shuffleMask));
    auto aSignsInt = _mm_shuffle_epi32((__m128i)aSigns, shuffleMask);
    auto bSignsInt = _mm_shuffle_epi32((__m128i)bSigns,shuffleMask);
    auto prodSigns = aSignsInt ^ bSignsInt;
    absProd ^= prodSigns;
    absProd -= prodSigns;
    return (int64x2_t)absProd;
}

int main(int argc, char* argv[]) {
    int32x4_t a{-5,500,-5000,50000};
    int32x4_t b{10,-100,-5000,500000000};
    auto c = multiply32_low_s(a,b);
    auto d = multiply32_high_s(a,b);
    printf("%ld %ld\n", c[0],c[1]);
    printf("%ld %ld\n", d[0],d[1]);
}

Assembly
multiply32_low_s(int __vector(4), int __vector(4)):
 movdqa xmm3,xmm0
 movdqa xmm2,xmm1
 psrad  xmm3,0x1f
 psrad  xmm2,0x1f
 pxor   xmm0,xmm3
 pxor   xmm1,xmm2
 psubd  xmm1,xmm2
 psubd  xmm0,xmm3
 pshufd xmm2,xmm2,0x50
 pshufd xmm1,xmm1,0x50
 pshufd xmm0,xmm0,0x50
 pshufd xmm3,xmm3,0x50
 pmuludq xmm0,xmm1
 pxor   xmm2,xmm3
 pxor   xmm0,xmm2
 psubq  xmm0,xmm2
 ret
 nop    WORD PTR [rax+rax*1+0x0]
multiply32_high_s(int __vector(4), int __vector(4)):
 movdqa xmm3,xmm0
 movdqa xmm2,xmm1
 psrad  xmm3,0x1f
 psrad  xmm2,0x1f
 pxor   xmm0,xmm3
 pxor   xmm1,xmm2
 psubd  xmm1,xmm2
 psubd  xmm0,xmm3
 pshufd xmm2,xmm2,0xfa
 pshufd xmm1,xmm1,0xfa
 pshufd xmm0,xmm0,0xfa
 pshufd xmm3,xmm3,0xfa
 pmuludq xmm0,xmm1
 pxor   xmm2,xmm3
 pxor   xmm0,xmm2
 psubq  xmm0,xmm2
 ret
 nop    WORD PTR [rax+rax*1+0x0]


text:
Q: Int instance variable not incrementing after method call Can anyone please tell me why the output is 82 instead of 92?
public class practice {
    int squares = 81;
    public static void main(String[] args) {
        new practice().go();
    }

    void go() {
        incr(++squares);
        System.out.println(squares);
    }

    void incr(int squares) {
        squares += 10;
    }
}

A: void incr(int squares) {
      squares += 10;
  }

squares here in parameter name will hide instance variable . so, + happens on parameter variable, not on instance variable.
use this.squares if you want operate on instance variable (incr(...) is instance method).

A: You have pre-incremented squares here:
incr(++squares);

So 82 is passed in to incr.  But incr receives a copy of the value 82 in its local variable squares.  That copy is modified, but the original is not modified.  In incr, the name squares refers to the local variable, not the instance variable.  So, back in go, squares is still 82.
To get 92, all you would have to do is rename the squares parameter to any other legal identifier (say, _squares, or square, or foo), so that squares in the method's body would refer to the instance variable, and not the parameter.
(There are other ways of course, such as writing this.squares += 10; in incr, or returning squares in incr and assigning the result to squares in go.)

A: The reason squares is still 82 is due to the scope. Once the incr function is called, squares is 82, and then the function gets a local copy of the variable.
The local copy it has, does get incremented by 10, and then goes out of scope at the end of the function. Control then goes back to the go function, with the squares that hasn't been incremented by 10.
And then it prints it out.
If you did this:
public class practice {

int squares = 81;
public static void main(String[] args) {
    new practice().go();
}

void go() {
    incr(++squares);
    System.out.println(squares);
}

void incr(int squares) {
    squares += 10;
    System.out.println(squares);
}
}

You would then see
92
82

as output.

A: You don't modify the variable after sending it to the method. You call:
incr(++squares);

which increases 81 by 1 (thus getting 82), THEN sends it to the incr method. That method then updates the parameter it was send by 10, getting 92.
However, this value isn't returned, and as such, the print statement produces 82.
If you put a print statement inside the incr() method, you would get 92.

A: void go() {
     squares++;
     incr(squares);
     System.out.println(squares);
 }

Increment squares to get 82 then pass that in as a refreshed integer and it should come out 92.

A: Since squeres is a local variable to incr method .So it should be
 void go() {
   squares = incr(++squares);
   System.out.println(squares);
 }
 int incr(int squares) {
    return  (squares += 10);
 }

or
 void go() {
   incr(++squares);
   System.out.println(squares);
 }
 void incr(int squares) {
    this.squares = squares + 10;
 }

A: You are not returning your incremented value from incr method. If you print out on screen result in that method, you will see it is 92 in it indeed;

A: The local variable squares is hiding the class variable
void incr(int squares) {
    squares += 10;
}

You should use
void incr(int squares) {
    this.squares += 10;
}


text:
Q: Lista encadeada sem cabeça, problema na função interseccão Estou fazendo um série de função com lista encadeada sem cabeça, porém uma função chamada Interseccão não está funcionando corretamente, o problema compila sem erros porém essa função especificamente não roda e o programa apresenta runtime erro, nessa função deve passar como parametro duas lista e a função me retorna uma terceira lista com a interseccao das duas listas. Segue o código abaixo:
#include<stdio.h>
#include<stdlib.h>

struct reg {
     int conteudo;
     struct reg *prox;
};

typedef struct reg celula;

void insere (celula **p, int x) {
     celula *novo, *q;
     q = *p;
     novo = (celula *)malloc(sizeof(celula));
     novo->conteudo = x;

     if (*p == NULL) {
          novo->prox = NULL;
          *p = novo;
     }

     else {
           while (q->prox != NULL)
                  q = q->prox;

           novo->prox = q->prox;
           q->prox = novo;
     }
}

void imprima (celula *p) {
     celula *q;
     if (p == NULL) printf ("Nao");
     else {
          for (q = p; q != NULL; q = q->prox)
                printf ("%d ", q->conteudo);
         printf ("\n");
      }
}

int NumElementos (celula *p) {
     celula *q;
     int n = 0;

     for (q = p; q != NULL; q = q->prox)
         n++;

return n;
}

int Pertence (celula *p, int x) {
     celula *q; int pt;
     q = p;

     while (q != NULL && q->conteudo != x)
           q = q->prox;

     if (q->conteudo == x) pt = 1;
     else pt = 0;

return pt;
}

celula *Interseccao (celula *p, celula *q) {
     celula *aq, *ap, *r = NULL;
     int aux;

     for (ap = p; ap !=NULL; ap = ap->prox) {
           for (aq = q; aq != NULL; aq = aq->prox) {
                aux = aq->conteudo;
                   if (Pertence(ap, aux) ==  1) {
                          if (Pertence(r, aux) == 0)
                                insere(&r, aux);
                 }
           }
      }
    return r;
}

int main () {
     celula *lista = NULL;
     celula *lst = NULL;
     celula *lis = NULL;

     int ne, p;

     insere (&lista, 8);
     insere (&lista, 2);
     insere (&lista, 1);
     insere (&lista, 3);
     insere (&lista, 9);
     imprima(lista);
     ne = NumElementos (lista);
     printf ("%d ", ne);
     p = Pertence(lista, 3);
     if (p == 0) printf("\n pertence");
     else printf("\npertence\n");
     insere (&lst, 7);
     insere (&lst, 3);
     insere (&lst, 5);
     insere (&lst, 1);
     imprima(lst);
     lis = Interseccao(lista, lst);
     imprima(lis);

return 0;
}

A: A função Pertence() não está verificando se o parâmetro p (atribuído à variável local q) é um ponteiro nulo e, ao acessar o elemento conteudo, ocorre o erro no runtime.
Basta alterar o if dentro da função para fazer essa verificação antes do acesso:
int Pertence (celula *p, int x) {
     celula *q; int pt;
     q = p;

     while (q != NULL && q->conteudo != x)
           q = q->prox;

     // AQUI  => verifica se q é diferente de NULL antes de acessar conteudo
     if (q != NULL && q->conteudo == x) pt = 1;
     else pt = 0;

return pt;
}

O resultado da execução, após a alteração:
8 2 1 3 9
5
pertence
7 3 5 1
3 1       <== interseccão


text:
Q: echo php result in the javascript code i'm trying to echo some result in php in the javascript but it keeps not working messing up the interface of the javascript player
that's the full javascript :

i want to replace this :
            {
                title:"Name",
                mp3:"audio.mp3",
            },

with this :
    while(
    $row = mysql_fetch_assoc($result)) {
    $sender = $row['sender'];
    $sender_name_query = mysql_query("SELECT fullname FROM users WHERE id = '$sender'");
    $sender_name = mysql_fetch_object($sender_name_query);
    $sender_fullname = $sender_name->fullname;
    echo '{
title:"' . $sender_fullname . '",
mp3:"link",
},';
}

it's a while loop i need it to get all the results
can anyone pls help in how to replace it ?
thanks

A:
 isn't valid in javascript. Try:
echo '{\ntitle:"' . $sender_fullname . '",\nmp3:"link",\n},';

A: yet another solution. You could do:
<?php
    $playlist = array();

    while($row = mysql_fetch_assoc($result)) {
        $sender = $row['sender'];
        $sender_name_query = mysql_query("SELECT fullname FROM users WHERE id = '$sender'");
        $sender_name = mysql_fetch_object($sender_name_query);
        $sender_fullname = $sender_name->fullname;
        $playlist[] = (object) array(
            'title' => $sender_fullname,
            'mp3' => 'audio.mp3'
        );
    }
?>

A: Don't use
 tags, use \n instead to add newlines (if you really need it, script will work without linebreaks).
You cant use HTML tags in javascript

A: {
    title: "<?php echo json_encode($sender_fullname);?>",
    mp3: "audio.mp3",
},


text:
Q: Google Cloud Bigtable Java Client - tcnative errors I am trying to connect to Cloud Bigtable; however, I'm getting issues with netty-tcnative not being found.
Maven dependencies:
<dependency>
    <groupId>com.google.cloud.bigtable</groupId>
    <artifactId>bigtable-hbase-1.2</artifactId>
    <version>0.9.2</version>
</dependency>

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-tcnative-boringssl-static</artifactId>
    <version>1.1.33.Fork19</version>
</dependency>

Error output:
ERROR 2016-09-09 22:26:00,969 [main] com.google.cloud.bigtable.grpc.BigtableSession: Neither Jetty ALPN nor OpenSSL are available. OpenSSL unavailability cause:
java.lang.IllegalArgumentException: Failed to load any of the given libraries: [netty-tcnative-osx-x86_64, netty-tcnative]
Exception in thread "BigtableSession-startup-2" java.lang.ExceptionInInitializerError
at com.google.cloud.bigtable.grpc.BigtableSession$3.run(BigtableSession.java:194)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: zip file closed
at java.util.zip.ZipFile.ensureOpen(ZipFile.java:634)
at java.util.zip.ZipFile.getEntry(ZipFile.java:305)
at java.util.jar.JarFile.getEntry(JarFile.java:227)
at java.util.jar.JarFile.getJarEntry(JarFile.java:210)
at sun.misc.URLClassPath$JarLoader.getResource(URLClassPath.java:840)
at sun.misc.URLClassPath.getResource(URLClassPath.java:199)
at java.net.URLClassLoader$1.run(URLClassLoader.java:358)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at org.mule.module.launcher.FineGrainedControlClassLoader.findClass(FineGrainedControlClassLoader.java:175)
at org.mule.module.launcher.MuleApplicationClassLoader.findClass(MuleApplicationClassLoader.java:134)
at org.mule.module.launcher.FineGrainedControlClassLoader.loadClass(FineGrainedControlClassLoader.java:119)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at com.google.bigtable.repackaged.io.netty.util.concurrent.MultithreadEventExecutorGroup.<init>(MultithreadEventExecutorGroup.java:36)
at com.google.bigtable.repackaged.io.netty.util.concurrent.MultithreadEventExecutorGroup.<init>(MultithreadEventExecutorGroup.java:58)
at com.google.bigtable.repackaged.io.netty.util.concurrent.MultithreadEventExecutorGroup.<init>(MultithreadEventExecutorGroup.java:47)
at com.google.bigtable.repackaged.io.netty.channel.MultithreadEventLoopGroup.<init>(MultithreadEventLoopGroup.java:58)
at com.google.bigtable.repackaged.io.netty.channel.nio.NioEventLoopGroup.<init>(NioEventLoopGroup.java:77)
at com.google.bigtable.repackaged.io.netty.channel.nio.NioEventLoopGroup.<init>(NioEventLoopGroup.java:72)
at com.google.bigtable.repackaged.io.netty.channel.nio.NioEventLoopGroup.<init>(NioEventLoopGroup.java:59)
at com.google.cloud.bigtable.grpc.BigtableSessionSharedThreadPools.init(BigtableSessionSharedThreadPools.java:85)
at com.google.cloud.bigtable.grpc.BigtableSessionSharedThreadPools.<init>(BigtableSessionSharedThreadPools.java:77)
at com.google.cloud.bigtable.grpc.BigtableSessionSharedThreadPools.<clinit>(BigtableSessionSharedThreadPools.java:45)
... 4 more
Exception in thread "BigtableSession-startup-1" java.lang.IllegalStateException: zip file closed
at java.util.zip.ZipFile.ensureOpen(ZipFile.java:634)
at java.util.zip.ZipFile.getEntry(ZipFile.java:305)
at java.util.jar.JarFile.getEntry(JarFile.java:227)
at java.util.jar.JarFile.getJarEntry(JarFile.java:210)
at sun.misc.URLClassPath$JarLoader.getResource(URLClassPath.java:840)
at sun.misc.URLClassPath.getResource(URLClassPath.java:199)
at java.net.URLClassLoader$1.run(URLClassLoader.java:358)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at org.mule.module.launcher.FineGrainedControlClassLoader.findClass(FineGrainedControlClassLoader.java:175)
at org.mule.module.launcher.MuleApplicationClassLoader.findClass(MuleApplicationClassLoader.java:134)
at org.mule.module.launcher.FineGrainedControlClassLoader.loadClass(FineGrainedControlClassLoader.java:119)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at com.google.bigtable.repackaged.com.google.api.client.http.javanet.NetHttpTransport$Builder.trustCertificates(NetHttpTransport.java:270)
at com.google.bigtable.repackaged.com.google.api.client.googleapis.javanet.GoogleNetHttpTransport.newTrustedTransport(GoogleNetHttpTransport.java:55)
at com.google.cloud.bigtable.config.CredentialFactory.getHttpTransport(CredentialFactory.java:94)
at com.google.cloud.bigtable.grpc.BigtableSession$2.run(BigtableSession.java:183)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

A: This issue was due to Mule's class loader. Mule runs each app in its own class loader. Need to move this to Mule's common class loader (java.class.path), rather than the app class loader. Ensuring both BigTable client library and tcnative is in the same classpath.
This issue would arise in other containers such as Tomcat, as they follow similar class loader patterns.


text:
Q: Unable to navigate to other view controller after Google sign-in How can I go to another view controller after successfully signing with google? I've tried "self.inputViewController?.performSegue(withIdentifier: "goToMain", sender: self)" in my App Delegate but not getting any respond. Am I supposed to add the method in App Delegate or the view controller with the sign-in button?
App Delegate
import UIKit
import Firebase
import GoogleSignIn

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate{

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        FirebaseApp.configure()

        GIDSignIn.sharedInstance()?.clientID = "my_client_id"
        GIDSignIn.sharedInstance()?.delegate = self

        return true
    }

    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        if let error = error {
          print(error)
          return
        }

        guard
          let authentication = user?.authentication,
          let idToken = authentication.idToken
        else {
          return
        }

        let credential = GoogleAuthProvider.credential(withIDToken: idToken,
                                                       accessToken: authentication.accessToken)

        Auth.auth().signIn(with: credential) { authResult, error in
            if let error = error {
              let authError = error as NSError
                print(authError.localizedDescription)
              return
            }

            self.inputViewController?.performSegue(withIdentifier: "goToMain", sender: self)
        }

    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        return GIDSignIn.sharedInstance().handle(url)
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }

}

A: Are you sure about the inputViewController is not nil? This may a reason for not working.
You can add a function to test this, or you can use the print function to check, or, you can use debug point to check inputViewController is nil or not.
I'd like to add comment but I don't have enough reputation point :).
Good luck.


text:
Q: Is it possible to have the database ids loaded from a fixture start at a certain number? I'm working with the Play Framework 2.2.1, for Java. I would like to have my fixtures, for my unit tests, have all the tables start their id counting at over 200.
The reason being this: Compare non-primitive Long values 127 and 128
Googling it gives a bunch of "best practice" articles, non of which include this option.
So I'm wondering if it's possible.
EDIT: To clarify, this would be for the unit tests only, not for the working environment. The unit tests are loaded via fixtures. Every test can have a different fixture, meaning the db gets wiped for ever test, meaning it would have to be done for every single table in the database on the loading of the fixture.
The Play Framework uses ebean as an abstraction layer. Play uses the H2 database for unit testing in memory.
EDIT: I ended up fixing it with a regular connection to H2. Ebeean does not seem to support this.

A: Yes it is (with most dbms at least).
This sql statement works for MySQL: ALTER TABLE <table_name> AUTO_INCREMENT = 200;
This one works for H2: ALTER TABLE <table_name> ALTER COLUMN <column_name> RESTART WITH 1


text:
Q: Is there a clever way to determine negative area of an integral? Given some continuous, integratable function f(x) that has only positive area over a range from x1 to x2...is there a way to determine the negative area of the integral of f(x) - c (from x1 to x2), where c is some number?
Is there a way to do this without knowing the zeros of f(x) -c?

A: Well you could integrate $(f-|f|)/2$ (the negative part of the function), but it depends on $f$ if this leads to anything nice.


text:
Q: Spring MVC -HIbernate-MySQL I am developing an application with Spring MVC , Hibernate and database MySQL
Controller handle the request and response. Hibernate handles the database transaction.
My problem is when one or two access the service it works fine, but for more than that work fine for some time, but after that I get the error frequently lock time out
//My sample Controller code

 @RequestMapping(value = "Bank", method = RequestMethod.GET)
    public ResponseEntity<List<Bank>> getAllBank(@RequestHeader int data) {
        try {
            //My DAO implementation class for bank table
            bankdao = new BankDAOImpl();
            List<Bank> bank = bankdao.getAllBank(data);

            return new ResponseEntity<List<Bank>>(bank, HttpStatus.OK);
        } catch (HibernateException he) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

//My DAO implementation code

public List<Bank> getAllBank(int organizationId) throws HibernateException {
//I'm opening session in every function
Session session = SessionFactoryUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            Criteria criteria = session.createCriteria(Bank.class);
            criteria.add(Restrictions.eq("organizationId", organizationId));
            criteria.add(Restrictions.eq("deleteFlag", false));
            criteria.addOrder(Order.asc("bankName"));
            List<Bank> ls=criteria.list();
            return ls;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            session.getTransaction().commit();
            session.close();
        }

That session causing the problem
If I create a separate session factory for all functions instead of open a session
Will it solve my problem?

A: You shouldn't create a separate session factory for every method. Just open a session. May be a problem is your incorrect way of working with transactions. You should do it this way
public List<Bank> getAllBank(int organizationId) throws HibernateException {
    //I'm opening session in every function
    Session session = SessionFactoryUtil.getSessionFactory().openSession();
    Transaction tx = null;
            try {
                tx = session.beginTransaction();
                Criteria criteria = session.createCriteria(Bank.class);
                criteria.add(Restrictions.eq("organizationId", organizationId));
                criteria.add(Restrictions.eq("deleteFlag", false));
                criteria.addOrder(Order.asc("bankName"));
                List<Bank> ls=criteria.list();
                tx.commit();// commit here
                return ls;
            } catch (Exception e) {
                e.printStackTrace();
                if (tx != null) {
                  tx.rollback();// rollback here
                }
                return null;
            } finally {
                session.close();
            }
    }

May be a problem is your SessionFactoryUtil. It would be interesting to see it.


text:
Q: Angular 2 Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response I'm using codeigniter REST API for my server application. And client as Angular2, in my REST API I have given basic auth. I have set like
$config['rest_auth'] = 'basic';

And
$config['rest_valid_logins'] = ['uname' => 'pwd'];

And also for CORS Check i have used below code,
$config['check_cors'] = TRUE;
$config['allowed_cors_headers'] = [
  'Origin',
  'X-Requested-With',
  'Content-Type',
  'Accept',
  'Access-Control-Request-Method'
];
$config['allowed_cors_methods'] = [
  'GET',
  'POST',
  'OPTIONS',
  'PUT',
  'PATCH',
  'DELETE'
];
$config['allow_any_cors_domain'] = TRUE;

And also I have tried explicitly tried with in my rest controller,
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');

I used below code in angular,
import { Component, OnInit } from '@angular/core';
import { Http, Headers, RequestOptions  } from '@angular/http';
import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { CommonService, BaseAPIURL } from '../common/common.service';
export class Login implements OnInit {
 private headers: Headers;
  constructor(fb: FormBuilder, private router: Router, private http: Http,
    private commonService: CommonService) {
     this.headers = new Headers();
     this.headers.append('Authorization', 'Basic ' + btoa('uname:pwd'));
     this.headers.append('Content-Type', 'application/json');

  }
 ngOnInit() {
  }

  public onSubmit(values: Object): void {
    this.submitted = true;
    if (this.form.valid) {
      let options = new RequestOptions({ headers: this.headers });
      this.http.post(this.getuserLoginURL, JSON.stringify(values),  options ).subscribe(
        response => {
          let result = response.json();
          this.errorMessage = result.message;
        },
        error => {
          this.isDisabled = false;console.log(error);
          if (error.status == 400) {
            this.errorMessage = JSON.parse(error._body).message;
          } else {
            this.errorMessage = 'Internal server error. please contact admin.';
          }
        }, () => {
        });
    }
  }
}

When i have check with postman it is working well without any issue. When check with angular error comes like,
XMLHttpRequest cannot load http://localhost:97/sencogold/index.php/Adminaccount_api/login_adminuser. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

If i false the rest auth and remove the Authorization header it is working well without check the api user name and password
$config['rest_auth'] = FALSE;

and in angular
 this.headers = new Headers();
    //this.headers.append('Authorization', 'Basic ' + btoa('lmxretail:lmx@2017'));
    this.headers.append('Content-Type', 'application/x-www-form-urlencoded');

Please help any one to apply authentication for my api.

A: Add Authorization to the CORS Check:
$config['allowed_cors_headers'] = [
  'Authorization',
  'Origin',
  'X-Requested-With',
  'Content-Type',
  'Accept',
  'Access-Control-Request-Method'
];

A: In order for your preflight request to succeed, the server controller must accept the "Authorization" header as valid. You can do that by adding the "authorization" key along with other allowed headers values:
Access-Control-Allow-Headers: Authorization, Content-Type, Content-Range, Content-Disposition, Content-Description

A: in php codeigniter backend just put this header in the construct() of your api controller.
example:
class ApiController extends CI_Controller {
    function __construct(){

            parent::__construct();
            header('Access-Control-Allow-Origin: *');
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
            header("Access-Control-Allow-Headers: Origin,X-Requested-With,Content-Type,Accept,Access-Control-Request-Method,Authorization,Cache-Control");
            header('Content-Type: application/json');
    }
public function index(){
        $MYARRAY = array(1);
        echo json_encode($MYARRAY);
}
}