text:
Q: Any way to send HTML element object from one BrowserWindow to another BrowserWindow in electron using IPC? I can send string and object from one BrowserWindow to another BrowserWindow using ipcRenderer and ipcMain in electronJS
the code:
mainProcess.js:
function createWindow1 () {
  window1 = new BrowserWindow({width: 800,height: 600})
  window1.loadURL(`file://${__dirname}/window1.html`)
  window1.webContents.openDevTools()
  window1.on('closed', function () {
     window1 = null
  })
  return window1
}
function createWindow2 () {
  window2 = new BrowserWindow({width: 1000, height: 600})
  window2.loadURL(`file://${__dirname}/window2.html`)
  window2.webContents.openDevTools()
  window2.on('closed', function () {
    window2 = null
  })
  return window2
}

app.on('ready', () => {
  window1 = createWindow1();
  window2 = createWindow2();

  ipcMain.on('nameMsg', (event, arg) => {
  console.log("name inside main process is: ", arg); // this comes form within window 1 -> and into the mainProcess
  event.sender.send('nameReply', { not_right: false }) // sends back/replies to window 1 - "event" is a reference to this chanel.
  window2.webContents.send( 'forWin2', arg ); // sends the stuff from Window1 to Window2.
});

window1.html:

    <input type="text" id="name" value="" placeholder="Enter your name">
    <button type="button" id="sendName" >Send the name! </button>

window1.js:
const ipcRenderer = require('electron').ipcRenderer

let name = document.getElementById('name');

ButtonSendName = document.getElementById('sendName');
ButtonSendName.addEventListener('click', (event) => {
  ipcRenderer.send('nameMsg', name.value);
})

ipcRenderer.on('nameReply', (event, arg) => {
  console.log(arg) // why/what is not right..
});

window2.html:

window2.js:
const { ipcRenderer } = require('electron')

showName = document.getElementById('showName')
ipcRenderer.on('forWin2', function (event, arg){
  console.log(arg);
  showName.innerHTML = arg;
});
console.log("I'm Window2");

A demo would be better, but I don't know how to build an electron CodeBin app. This image gives you an idea:

This works nicely.
But I am not able to send DOM object (HTML element object) using this approch
ipcRenderer.invoke('slideChange', document.getElementById('selectedSlide'))
I am getting error Uncaught (in promise) Error: An object could not be cloned.
Is there any way to pass HTML element to another BrowserWindow using same machanism?

A: Unfortunately, using Electron, you can't send DOM objects between processes.

Electron's IPC implementation uses the HTML standard Structured Clone Algorithm to serialize objects passed between processes, meaning that only certain types of objects can be passed through IPC channels.
In particular, DOM objects (e.g. Element, Location and DOMMatrix), Node.js objects backed by C++ classes (e.g. process.env, some members of Stream), and Electron objects backed by C++ classes (e.g. WebContents, BrowserWindow and WebFrame) are not serializable with Structured Clone.

Ref: Electron - Inter-Process Communication - Object serialization.


text:
Q: std::vector::resize in gcc4.2 a week ago i upgraded from gcc4.0 to llvm gcc4.2. everything went well except for one thing i have really big trouble to figure out because i am more the audio signal processing kind of guy. so i really hope someone of you could help me. my issue is that the use of ::resize in stl_vector.h has completely changed.
in gcc4.0 the following code compiled fine:
std::vector< std::vector<myData> >  mMy;

std::for_each( mMy.begin(), mMy.end(),
  std::bind2nd(std::mem_fun_ref(&std::vector<myData>::resize), numMy) );

in gcc4.2 it does not compile with error:
no matching function for call to mem_fun_ref ..
i am pretty sure that i do not know how to implement ::resize correctly, could someone tell me what i have to do get this fixed. i am happy if you could show me a correct code example, but hints (books) and keywords that could help me figure this out would also be greatly appreciated ..
thanks a lot for your help ..
kind regards,
bzt

A: Make sure you have
#include <functional>

in your included.
However it would be easier for you to do this (if you are trying to set the size of all the vectors of myData.
std::vector<std::vector<myData > > mMy (size, std::vector(numMy) );

Here each vector will of size numMy
Also you do know that gcc 4.2 is still really quite old, if you can I would highly recommend gcc 4.6.
with gcc 4.6 you could do rid of all that mem_func whatever stuff with this:
std::for_each( mMy.begin(), mMy.end(),
    std::bind(std::vector<myData>::resize, std::placeholders::_1, numMy));

(although I would still prefer the constructor option if it is required by your use case).

A: mem_fun_ref takes a member function with zero or one argument.
I suspect your code will compile if you were to try that technique with 'reserve' which takes one argument (but doesn't resize.)
resize wants two arguments: a size and an initializer (which has a default value). I guess this is why there is no matching mem_fun_ref template - it is confused by the optional initializer.
Maybe your gcc 4.0 worked around this smoothly, but gcc 4.2 does not?
I tested on a RH5 linux gcc 4.1.2 (no match for mem_fun_ref) and RH6 linux gcc 4.4.5 (does find a match) so maybe you should migrate forward.

A: 111111 has the right answer, but I wanted to explain what I think is going on here.
I believe the code is not actually legal, because std::vector::resize is an overloaded function. You have to cast &std::vector<myData>::resize in order to select the overload you want:
std::for_each( mMy.begin(), mMy.end(),
  std::bind2nd(std::mem_fun_ref(
    reinterpret_cast<void (std::vector<myData>::*)(std::size_t)>(&std::vector<myData>::resize)),
    numMy));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Distributed tensorflow where to keep data I am using 3 machines for distributed tensorflow (2 workers and 1 ps). All lie on the same cluster. I have placed my data on worker 1. My model works well but it uses only ps and 1 worker.
My question is how is data placed so that all my workers can access it? Should I place it in shared memory like hdfs?

tf.reset_default_graph()
if FLAGS.job_name == "ps":
    server.join()
elif FLAGS.job_name == "worker":
    # Between-graph replication
    with tf.device(tf.train.replica_device_setter( worker_device="/job:worker/task:%d" % FLAGS.task_index, cluster=Cluster)):
      ## here defining my model, cost, optimizer

    sv = tf.train.Supervisor(is_chief=(FLAGS.task_index == 0), global_step=global_step, init_op=init_op)
    with sv.prepare_or_wait_for_session(server.target) as sess:
        for epoch in range(training_epochs):
           cost_val = sess.run([ cost ], feed_dict={X: data})

A: Found some relevant info here:
[1]GRPC causes training to pause in individual worker (distributed tensorflow, synchronised)
Appears that we need to create TFRecords.


text:
Q: Всплывают ли переменные, объявленные с помощью let и const в ES6? Проверяя новшества ES6, я обратил внимание, что переменные объявленные с var всплывают как и ожидалось...
console.log(typeof name); // undefined
var name = "John";

...в то время как, переменные объявленные с помощью let или const похоже имеют с подъемом некоторые проблемы:
console.log(typeof name); // ReferenceError
let name = "John";

и
console.log(typeof name); // ReferenceError
const name = "John";

Означает ли это, что переменные объявленные с помощью let или const не всплывают? Что происходит здесь на самом деле? Есть ли разница между let и const в этом случае?

Перевод вопроса: Are variables declared with let or const not hoisted in ES6?

A: tl; dr; цитата из секции 13.3.1 Let and Const Declarations

The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated.

Переменные создаются когда инстанциируется содержащий их Lexical Environment, но остаются недоступными никоим образом до вычисления их LexicalBinding.

Так что, ответ на твой вопрос: да, let и const всплывают, но ты не можешь получить доступ к ним, до выполнения фактического определения в run-time.

Как сказано выше, эти переменные не могут быть доступны, до их объявления. Однако, все немного сложнее.

Означает ли это, что переменные объявленные с помощью let или const не всплывают? Что происходит здесь на самом деле?

В JavaScript все определения (var, let, const, function, function*, class) всплывают. Это значит, что если имя определено в скопе, в этом скопе идентификатор всегда будет указывать на конкретную переменную:
x = "global";
// функциональный скоп:
(function() {
    x; // не "global"

    var/let/… x;
}());
// блочный скоп (не для `var`):
{
    x; // не "global"

    let/const/… x;
}

Это верно и для функционального, и для блочного скопов1.
Различие между определениями var/function/function* и let/const/class в их инициализации.
Первые инициализируются значением undefined или функцией (генератором) прямо когда создается связывание в начале скопа. Однако, лексически объявленные переменные остаются неинициализированными. Это значит, что при попытке доступа к ним будет брошено исключение ReferenceError. Инициализируются они. только в момент выполнения выражений let/const/class, все перед этим (выше) называется временная мертвая зона (temporal dead zone).
x = y = "global";
(function() {
    x; // undefined
    y; // Reference error: y is not defined

    var x = "local";
    let y = "local";
}());

Обратите внимание, что выражение let y; инициализирует переменную значением undefined, аналогично выражению let y = undefined;.
Временная мертвая зона, это не синтаксическое место, а, скорее, время между созданием переменной (скопа) и инициализацией. Так, не будет ошибкой обращение к переменной в коде выше определения, пока этот код не будет выполнен (например тело функции или просто недостижимый код), но будет выкинуто исключение при попытке доступа к переменной до ее инициализации, даже если код доступа расположен ниже определения (например, во всплывшем определении функции, которая была вызвана слишком рано).

Есть ли разница между let и const в этом случае?

Нет, они работают абсолютно одинаково, если рассматривать со стороны всплытия. Единственное отличие их в том, что constанты должны и могут быть присвоены только в части инициализатора определения (const one = 1;, вариант const one; с последующим присвоением значения one = 2 недопустим).

1: естественно, определение var работает только на уровне функции

Переводы ответов @thefourtheye и @Bergi


text:
Q: What is the difference between coretemp-isa-0000 and "Virtual" temperatures? I notice when I run thinkfan on my laptop, it has no problem running with just the coretemp sensors, but wont run with the virtual sensors.
Do I need to include the virtual sensors in my thinkfan.config file or is it okay to manage fan speed / temperature levels without them?
Here is the output of sensors:
coretemp-isa-0000
Adapter: ISA adapter
Package id 0:  +35.0°C  (high = +100.0°C, crit = +100.0°C)
Core 0:        +34.0°C  (high = +100.0°C, crit = +100.0°C)
Core 1:        +33.0°C  (high = +100.0°C, crit = +100.0°C)

iwlwifi-virtual-0
Adapter: Virtual device
temp1:        +43.0°C

acpitz-virtual-0
Adapter: Virtual device
temp1:        +35.0°C  (crit = +128.0°C)

thinkpad-isa-0000
Adapter: ISA adapter
fan1:           0 RPM

pch_skylake-virtual-0
Adapter: Virtual device
temp1:        +31.0°C


text:
Q: Cannot deserialize a Pipeline Stage from string I have a mongodb a agggregation pipeline stage on a string like this:
{ $project: {
    txtStatus: { $trim: { input: '$txtStatus' } }
} },
{ $match: {$or: [{'txtStatus': {$eq: 'VALID'}},{'txtStatus': {$eq: 'NOTVALID'}}]} },
{ $group: {
    _id: '$txtStatus',
    Count: { $sum: 1 }
} }

I currently need to separate each of the stages and append one by one like this:
_myRepo.SetDatabase("MyDbName")
    .GetCollection("MayColl")
    .Aggregate<dynamic>()
    .AppendStage<dynamic>(stageProject.ToBsonDocument())
    .AppendStage<dynamic>(stageMatch.ToBsonDocument())
    .AppendStage<dynamic>(stageGroup.ToBsonDocument());

I need to pass the entire string to the "AppendStage" without having to split it into stages like Im doing today, something like this:
_myRepo.SetDatabase("MyDbName")
    .GetCollection("MayColl")
    .Aggregate<dynamic>()
    .AppendStage<dynamic>(myEntireAggregationString.ToBsonDocument());

A: I put my query inside brackets:
[
    { $project: {
        txtStatus: { $trim: { input: '$txtStatus' } }
    } },
    { $match: {$or: [{'txtStatus': {$eq: 'VALID'}},{'txtStatus': {$eq: 'NOTVALID'}}]} },
    { $group: {
        _id: '$txtStatus',
        Count: { $sum: 1 }
    } }
]

Then, I deserialized the query into a BsonDocument Array and passed this array/list in the Aggregate() method:
var pipelineStages = BsonSerializer.Deserialize<BsonDocument[]>(myQuery).ToList();

var ret = _myRepo.SetDatabase("MyDbName")
    .GetCollection("MayColl")
    .Aggregate<dynamic>(pipelineStages)
    .ToList();


text:
Q: nginx: using directives with if I want to have the logical:
if ($do_not_cache) {
fastcgi_pass_header "Set-Cookie";
}

But I got error: "fastcgi_pass_header" directive is not allowed here
I tried to use named locations for "fastcgi_pass_header "Set-Cookie"" but don't know, how to forward in it in if section.
I tried to forward in location with this construction:
if ($do_not_cache = 1) {
rewrite ^(.*(?<!nginx_cache))/$ https://$server_name$1?r=no_ cache permanent;
}

but it doesn't work properly too.


text:
Q: Apache CGI in user directory "End of script output before headers" I know there are some questions about this topic, but none seems to solve my issue. See this or this or this.
I'm on Linux, Fedora21, and I'm trying to enable per user directory CGI script. I followed these instructions, but without success.
I get the error:
[cgi:error] End of script output before headers: test.cgi

test.cgi is an executable sh file, containing a very simple script:
#!/usr/bin/sh

echo "Content-type: text/plain"
echo ""
echo "Hello"

which has executable flag and runs without problems from shell.
I also tried with Python: same result.
I also disabled selinux for good measure.
I also tried setting the debug level to Apache's ErrorLog, but all I get is only "granted" permissions before the error above.
I also configured the /etc/httpd/conf.d/userdir.conf file with
<Directory "/home/*/public_html">
    AllowOverride All
    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
    Require all granted
</Directory>

<Directory /home/*/public_html/cgi-bin/>
    Options ExecCGI FollowSymLinks
    SetHandler cgi-script
    AddHandler cgi-script .cgi .exe .pl .py .vbs
    Require all granted
    AllowOverride All
</Directory>

and restarted the server. No success. Everything looks fine to me, I can't understand... What's wrong??
EDIT:
I forgot to add that the issue is just for per-user directory: if I move the same script to /var/www/cgi-bin directory, it works as expected.
EDIT 2:
The shell does exist:
$ ls /usr/bin/sh
/usr/bin/sh

A: For me, it worked when I changed the shebang line (#!/usr/bin/sh) to #!/usr/bin/env sh. I found that any shebang lines from What is the preferred Bash shebang? seemed to work (however note that sh is different from bash so if you want to use sh stick with it).
So this code worked for me:
#!/usr/bin/env sh
echo "Content-type: text/plain"
echo ""
echo "Hello"

Also, according to the post mentioned above, it seems /usr/bin/env sh seems preferred over /bin/sh. I have no idea about the per directory stuff.

A: This sometimes comes up when you try to call other Python module methods from your cgi where you might have left some 'print' statements (perhaps for debugging). So scan your code for any 'print' statement, sometimes this fixes the problem easily.

A: Let only the file owner have write permissions on the cgi script, but not the group, that is -rwxr-xr-x and not -rwxrwxr-x.
In user directories often the group will be a personal user group that only the user is member of anyway, but it seems like Apache gets nervous about seing the g+w bit but gives a somewhat bogus error message about this.

A: I had the same  issue. I also needed this:
sudo setsebool -P httpd_read_user_content 1

which I found out by looking at the log (journalctl -b )
which told me...
SELinux is preventing /usr/bin/python2.7 from search access on the directory public_html.

A: Finally I solved that. Thanks to @JimB, because in his comment he pointed out SUEXEC, which I didn't know about (or simply ignored till now).
After reading a bit the suEXEC documentation, I understood the the problem had to be there. So, I took a look at the configuration:
# suexec -V
 -D AP_DOC_ROOT="/var/www"
 -D AP_GID_MIN=1000
 -D AP_HTTPD_USER="apache"
 -D AP_LOG_SYSLOG
 -D AP_SAFE_PATH="/usr/local/bin:/usr/bin:/bin"
 -D AP_UID_MIN=1000
 -D AP_USERDIR_SUFFIX="public_html"

and everything looked Ok (good uid/gid for my user, userdir_suffix is fine, etc). So I took a look at the system logs:
# journalctl -b | grep "suexec"
May 22 11:43:12 caladan suexec[5397]: uid: (1000/user) gid: (1000/user) cmd: test.cgi
May 22 11:43:12 caladan suexec[5397]: directory is writable by others: (/home/user/public_html/cgi-bin)

and that's the problem: my cgi-bin directory was writable by others.
I fixed by simply changing the permissions to 755.

A: I saw the message "End of script output before headers: myscript.py" for a Python 2.x CGI script that ran fine from the command line.
The problem turned out to be that it wasn't executing correctly by the web server, even though it was from the command-line. Whatever error message the system gave back to the server, it surely didn't pass for CGI headers (e.g., "Content-Type: text/html\r\n\r\n"). Hence, this failure message.
For me, correcting it meant changing the shebang from:
#!/usr/bin/env python

To a more system-specific (but verifiable):
#!/usr/local/bin/python

Perhaps you're encountering something similar.
(FreeBSD 9.x.)

A: Try running your script as the apache user.
There are a number of reasons this could be happening.  @JimB mentions problem with the shebang.  @premganz mentions problems with debug print statements that fire before your Content-Type string is written. In my case it was a db connection failure.  It could be any other problem.
I found the best way to debug this is to run the script directly as the apache user on the command line, and see what errors it gives.
How to run your script as the Apache user
Assuming you're running apache2, and the apache user is www-data, and your cgi script is /myapp/myreport.py - you can do the following.

*

*Allow logins as the www-data user, by changing its default shell. Edit /etc/passwd (temporarily)
sudo su -
cd /etc
cp -p passwd passwd.2017-10-22

emacs passwd     # edit file - use your favorite editor

Change:
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin

To:
www-data:x:33:33:www-data:/var/www:/bin/bash

*Log in as the www-data user
sudo su - www-data

*Set any environment vars.  Convert your apache SetEnv statements to export statements.  In my case, my apache config directory settings has these vars set
SetEnv PYTHONPATH /myapp/lib
SetEnv VCONF /myapp/conf/prod.yaml

Run them as
export PYTHONPATH=/myapp/lib
export VCONF=/myapp/conf/prod.yaml

*Then try your cgi script
cd /myapp
./myreport.py

*You should see whatever error Apache is experiencing.  FIX THEM.

*Set the www-data user's default shell back to /usr/sbin/nologin

A: This error occurs when we use print in older way.
print 'your test'

It should be for later version of Python.
print ('your test')

A: I was having a problem executing a python cgi in a userdir.
/var/log/httpd/error_log reveals:

[Fri Apr 26 13:09:41.840285 2019] [cgi:error] [pid 25421] [client 98.234.206.134:60837] End of script output before headers: index.cgi

The user being invoked in the URL was doug, user 42, group 42
I vaguely remembered suexec having a problem executing cgi scripts for a group or user below 1000.
So I created a new group called user1k as 1000.
Then I did
adduser -g 1000 -u 1000 dwg
chmod 755 /home/dwg
mkdir /home/dwg/public_html

And I placed my python cgi script into this directory.
Now that the group and user were >= 1000 the script began executing correctly.
I am not sure whether it was the user or the group which fixed the problem, but changing them both definitely solved it.
Note: It was the userid being below 1000 that was the problem.
So make the the userID of a userdir cgi executee is > 999.
Here is an excerpt from the man suexec output.

Is the target userid ABOVE the minimum ID number? The minimum user ID
  number is specified during configuration. This allows you to set the
  lowest possible userid that will be allowed to execute CGI/SSI
  programs. This is useful to block out "system" accounts.
Is the target groupid ABOVE the minimum ID number? The minimum group
  ID number is specified during configuration. This allows you to set
  the lowest possible groupid that will be allowed to execute CGI/SSI
  programs. This is useful to block out "system" groups.


text:
Q: Are you able to call 3 for loops in a specific order? At the moment I have 3 loops, is it possible to call them one time instead of 3? The problem lies in the fact that loop one has to be finished before loop 2 can work, and loop 2 has to be finished before loop 3 can be run. So at the moment it's something like this.
public void handling() {
    for (Object object : Code.objects) {
        handle_One(object);
    }
    for (Object object : Code.objects) {
        handle_Two(object);
    }
    for (Object object : Code.objects) {
        handle_Three(object);
    }
}

If I try something like this it doesn't work because they are all being called at the same time and it has to be ordered.
public void handling() { //Code that doesn't work...
    for (Object object : Code.objects) {
        handle_One(object);
        handle_Two(object);
        handle_Three(object);
    }
}

Is there any way around this, any way to fix it? Have been trying for a while now and nothing...Having 3 for loops is very bad in this situation and causing problems. (And sadly the only way we can get it working)
Edit: The reason this is bad in my case is because the for loop can reach up to 300 sometimes. (As Code.objects, represents how many connections there are, sometimes its 100, meaning it's doing 300 loops per iteration.

A: You can use SwigUtilities.invokeAndWait(<your task>). Please refer the following link
SwingUtilities.invokeAndWait


text:
Q: How to redirect LINE IN to LINE OUT? I want to redirect the audio signal coming from my gaming console via LINE IN to my headphones which are connected to LINE OUT.
In Windows 10 I can select the LINE IN device in the sound options and select a target to redirect the signal but in Ubuntu I can't find that option.
Ubuntu 20.04


text:
Q: Vaadin Flow dark mode Dialog How can i set my dialog theme from light to dark?
When i'm doing
dialog.setAttribute("theme", Lumo.DARK);

then background under dialog have solid colour and i can't see what is benath it like in normal theme. I changed dialog theme on the official vaadin page and there isthis same problem. I`m using Vaadin 14.7.6.

A: There's no out-of-the-box support for a dark variant for Dialog specifically. You can set the whole application to use the dark theme, though.
If you only want a dark themed Dialog, you need to do what you already did, but override the background color of the <vaadin-dialog-overlay> element.


text:
Q: twilio recordingStatusCallback is not sending parameters to url I want to send a number with recordingStatusCallback url. But, when I receive the log of the parameters in web-hook url, I don't see the parameter I passed in the URL. I was parsing the parameters as url-endcoded format.
Below code, I am sending chunkStartNumber=18 in url,but there is no trace of chunkStartNumber in log below
   var recLenDivided=18;
   let twiml = new Twilio.twiml.VoiceResponse();
    twiml.record({
        action:`https://xyz`,
        method: 'GET',
        finishOnKey: '5',
        recordingStatusCallback:`http://xyz/hookFolder?chunkStartNumber=${recLenDivided}`
    });
      return callback(null, twiml);
   }

The parser code
const express = require ('express')
const bodyParser = require ('body-parser')
const app = express()
const PORT = 3000

app.use(express.static("public"))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))

app.post("/hookFolder",(req, res) => {
    console.log(req.body)

    res.status(200).end()
})

The log
{ RecordingSource: 'RecordVerb',RecordingSid: 'RE', RecordingUrl: 'https://api.twilio.com/2010-04-01/', RecordingStatus: 'completed', RecordingChannels: '1', ErrorCode: '0', CallSid: 'CA', RecordingStartTime: 'Tue, 22 Dec 2020 18:09:44 +0000', AccountSid: 'AC', RecordingDuration: '9' }

A: Try req.query.
Also, no need to use Bodyparser. Built in with later versions of Express.

*

*4.16.0 - Release date: 2017-09-28
https://expressjs.com/en/changelog/4x.html
app.use(express.json());
app.use(express.urlencoded({ extended: false }));


text:
Q: Searching MySQL for part of an array Im trying to take an array of titles from the column 'list' and then get details for every title on said list.
//Get list
$r=$link->prepare('SELECT list FROM lists WHERE user=? LIMIT 1');
$r->bindValue(1,$user,PDO::PARAM_STR);
$r->execute();
$list=$r->fetchAll(PDO::FETCH_ASSOC);

//See how many titles the list has
$list_length=count($list);

//Get details for every title
for($i=0;$i<$list_length;$i++)
{
    $r2=$link->prepare('SELECT * FROM details WHERE title=?');
    $r2->bindValue(1,$list[$i],PDO::PARAM_STR);
    $r2->execute();
    $details=$r2->fetchAll(PDO::FETCH_ASSOC);
}
return json_encode($details);

As it is I get echoed just [].
I also get Notice: Array to string conversion in $r2->bindValue(1,$list[$i],PDO::PARAM_STR);

A: *

*You have to learn to read your code, instead of asking others to do it for you.
SELECT list FROM lists WHERE user=? LIMIT 1

Look at this query. Does it looks like one that can return an array of rows?

*Learn SQL. And JOINS particularly

And here goes the code
$sql = 'SELECT details.*  FROM lists JOIN details on title=list WHERE user=?';
$stm = $link->prepare($sql);
$stm->execute([$user]);
json_encode($stm->fetchAll(PDO::FETCH_ASSOC));

Just FOUR lines


text:
Q: Ionic2 identify back view How could I identify in ionic2 the back/caller view?
in ioni1 I was using
var backView:ionic.View = this.$ionicHistory.backView();
backView.stateName === 'app.view_I_want_to_test';

I was thinking about getting the view controller, but don't know how to test if that view controller is the view I'm interested in.
let lastView:ViewController = this.navController.getPrevious(this.navController.getActive());
then???

A: I found a solution which I don't like because I've to do a dirty "any" cast to access a private value for the comparison but following code do the job:
onPageDidEnter() {
    // this.navController.last() strangely equals the view which entered
    let previousView:ViewController = this.navController.getPrevious(this.navController.last());

    if (previousView != null && (<any> previousView).instance instanceof MyPage) {
        doSomeStuffs();
   } else {
        doSomeOtherStuffs();
   }
}


text:
Q: How can I reload HTML table after AJAX success on Django web page? I'm using two datepickers from the jQuery library for start and end dates. Once I have the two dates I send them to my django view via ajax. I then run the model query in my views which will return a filtered dict into my django context. My question now is how can I reload the table on the template?
Would I have to define a Javascript function to load a table and call it on ajax success? Or perhaps a better way?
html

    Start Date: <input id="mail_start_date"/>
    End Date: <input id="mail_end_date"/>
    <button id='btn'>Filter</button>

  Desk
  # of Packages

{% for desk, count in pick_dict.items %}

  {{desk}}
  {{count}}

{% endfor %}

Javascript
  $(document).ready(function(){
$('#mail_start_date').datepicker({ dateFormat: "yy-mm-dd" });
$('#mail_end_date').datepicker({ dateFormat: "yy-mm-dd" });

$('#btn').click(function(){
  var start = $('#mail_start_date').val();
  var end = $('#mail_end_date').val();
  $.ajax({
    url: "/apps/centraldesk/mail/stats/",
    type: "POST",
    data: {
      'start': start,
      'end': end,
      csrfmiddlewaretoken: '{{ csrf_token }}',
    },
    success: "SOMTHING NEEDS TO HAPPEN HRERE"
  });
});

views.py
def mail_stats(request):
  pick_dict = {}
  if request.is_ajax():
    pick_start = request.POST['start']
    pick_end = request.POST['end']
    pick_start = str(pick_start)
    pick_end = str(pick_end)

    in_date = datetime.datetime.strptime(pick_start, "%Y-%I-%d")
    out_date = datetime.datetime.strptime(pick_end, "%Y-%I-%d")

    pick_list = MailRecord.objects.filter(timeIn__range=(pick_start, pick_end))
    for item in pick_list:
      if pick_dict.has_key(item.desk.name):
        pick_dict[item.desk.name] += 1
      else:
        pick_dict[item.desk.name] = 1

  context = {
    "mail_list" : mail_list,
    "pick_dict" : pick_dict,
  }
  return render("mail_stats.html", context, context_instance=RequestContext(request, processors=[custom_proc]))

A: Yes, you define a javascript function, like so
...
},
success: function(json) {
  // Access your table here and manipulate it with the returned data from "json" (json is the dictionary given by your django view)
}
});
...

You could also add an error-function next to the success function.


text:
Q: System architecture advice for a dual interface online/mobile marketplace My startup is building an online/mobile labor marketplace where there will be a business interface for businesses posting jobs and we distribute these jobs through a mobile interface for users. We use Rails, REST, Amazon RDS & EC2 and mysql.
My question is: from an architecture standpoint on the server-side does it make sense to?:
a) Have 2 applications one serving the web interface and one acting as the server-side (API) for the mobile interface and both communicating via the DB and via 2 different EC2 instances
b) Try to build one comprehensive application serving both interfaces
Any opinion and perspective on pros and cons would be much appreciated
Thanks

A: Amazon Web Services are giving you a few tools to make your architecture simpler, more robust and scalable, if you break down your system into smaller, simpler and independent components.
Since you have a set different sizes of instances from micro to extra large (and a few sizes of extra large), you have the flexibility to mix each service type to the appropriate size, configuration, software dependencies, update cycle etc. It will make the life of the developers, testers and administrators much easier.
You also have the ability to scale and even auto-scale each layer and service independently. If you have more users of one of the interfaces, or the other, or increase in data size that is fed through one of the interfaces, you can scale only the relevant service. It will save you the complexity and cost of scaling the full system as a whole.
Another characteristic of AWS is the ability to scale up, down, out and in based on your need. For example, if one of the interface has more users on working weekdays and fewer on weekends, you can scale down this interface for the weekend or night, saving 50% of your computation costs for this instances. In this regards, you can switch from the on-demand model for the more static interfaces to reserved instances, saving again 50% of your costs.
To allow communication between the different interfaces you can use your DB, but you also have a few more options based on your use case. One option is to use Queueing system as SQS. The queue is used as a buffer between the interfaces, reducing the risk of failure of one component (software bug, hardware failure...), affecting the whole system. Another option for inter interfaces communication, that is more tuned to performance is to use in-memory cache. AWS are offering ElasticCache as such service. It can be more efficient than updating such transient data for short period of time and with high load.
I see no long term cons, other than the quick (and dirty) implementation of a single service on a single machine.

A: The overall goal should be to have most amount of code common between the mobile and web application. Otherwise you are looking at maintenance headaches where you will end up e.g. fixing bugs, or adding features at two places at minimum.
Ideally everything below the front end should be common. The web UI should itself be calling the server side APIs that you are going to need for mobile application. And most amount of logic should be put into these APIs, leaving only presentation details to the UI. This is as prescribed by many patterns such as MVC.
I have a mobile site and desktop site running myself. The codebase is exactly the same at PHP level. Only the smarty templates are different between the two. Granted that mobile application is different from mobile site, but the basic principles still apply.


text:
Q: How tf.nn.dynamic_rnn works with different lengths of inputs sepcially when working with seq2seq? Here I am asking how the dynamic behavior work.
This is the tensorflow documentation for above dynamic_rnn function. What is the maximum length of RNN input blocks that this function create? Will it pad all shorter ones according to the largest input?

A: It is your responsibility to pad the sequences, and then supply the sequences lengths.
For example:
# Create input data
X = np.random.randn(2, 10, 8)

# The second example is of length 6
X[1,6:] = 0
X_lengths = [10, 6]

cell = tf.nn.rnn_cell.LSTMCell(num_units=64, state_is_tuple=True)

outputs, last_states = tf.nn.dynamic_rnn(
    cell=cell,
    dtype=tf.float64,
    sequence_length=X_lengths,
    inputs=X)

Here you can see, we pad the sequences ourselves  X[1,6:] = 0 will assign 0 to all of the values after the 6th element, that means this sequence is of length 6 and we state so by giving X_lengths 2nd value the value 6


text:
Q: How to use Visual Studio C code on other Compiler? I have seen same sample a C code, It can work on Visual Studio 2010.
I want it run on Embarcadero RAD Studio, Netbeans/MinGW, eclipse/MinGW, How can I do?
Is it can use on other Platform & Compiler(Linus/GCC, Mac/Xcode)? If yes, How to do?
dlg_three.c
#include <windows.h>

#include "resource.h"

HBRUSH g_hbrBackground = NULL;

BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
    switch(Message)
    {
        case WM_INITDIALOG:
            g_hbrBackground = CreateSolidBrush(RGB(0, 0, 0));

            SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)LoadIcon(NULL,
                MAKEINTRESOURCE(IDI_APPLICATION)));
            SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)LoadIcon(NULL,
                MAKEINTRESOURCE(IDI_APPLICATION)));
        break;
        case WM_CLOSE:
            EndDialog(hwnd, 0);
        break;
        case WM_CTLCOLORDLG:
            return (LONG)g_hbrBackground;
        case WM_CTLCOLORSTATIC:
        {
            HDC hdcStatic = (HDC)wParam;
            SetTextColor(hdcStatic, RGB(255, 255, 255));
            SetBkMode(hdcStatic, TRANSPARENT);
            return (LONG)g_hbrBackground;
        }
        break;
        case WM_COMMAND:
            switch(LOWORD(wParam))
            {
                case IDOK:
                    EndDialog(hwnd, 0);
                break;
            }
        break;
        case WM_DESTROY:
            DeleteObject(g_hbrBackground);
        break;
        default:
            return FALSE;
    }
    return TRUE;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    return DialogBox(hInstance, MAKEINTRESOURCE(IDD_MAIN), NULL, DlgProc);
}

dlg_three.rc
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_CAN
#pragma code_page(1252)
#endif //_WIN32

#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//

1 TEXTINCLUDE DISCARDABLE
BEGIN
    "resource.h\0"
END

2 TEXTINCLUDE DISCARDABLE
BEGIN
    "#define APSTUDIO_HIDDEN_SYMBOLS\r\n"
    "#include ""windows.h""\r\n"
    "#undef APSTUDIO_HIDDEN_SYMBOLS\r\n"
    "\0"
END

3 TEXTINCLUDE DISCARDABLE
BEGIN
    "\r\n"
    "\0"
END

#endif    // APSTUDIO_INVOKED

/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//

IDD_MAIN DIALOG DISCARDABLE  0, 0, 186, 46
STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Dialog tricks"
FONT 8, "MS Sans Serif"
BEGIN
    DEFPUSHBUTTON   "OK",IDOK,129,7,50,14
    LTEXT           "Hi there.",IDC_STATIC,43,16,28,8
END

/////////////////////////////////////////////////////////////////////////////
//
// DESIGNINFO
//

#ifdef APSTUDIO_INVOKED
GUIDELINES DESIGNINFO DISCARDABLE
BEGIN
    IDD_MAIN, DIALOG
    BEGIN
        LEFTMARGIN, 7
        RIGHTMARGIN, 179
        TOPMARGIN, 7
        BOTTOMMARGIN, 39
    END
END
#endif    // APSTUDIO_INVOKED

#endif    // English (Canada) resources
/////////////////////////////////////////////////////////////////////////////

#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//

/////////////////////////////////////////////////////////////////////////////
#endif    // not APSTUDIO_INVOKED

resource.h
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by dlg_three.rc
//
#define IDC_STATIC -1
#define IDD_MAIN                        101

// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE        102
#define _APS_NEXT_COMMAND_VALUE         40001
#define _APS_NEXT_CONTROL_VALUE         1000
#define _APS_NEXT_SYMED_VALUE           101
#endif
#endif


text:
Q: Use value to reference a variable in a function How can I get value to see a variable in a local scope?
For example:
a:2;

func:{
  a:1;
  value "a"
 }

returns 2

A: value will always work on global scope.
If you really need this, maybe make use of workspace variables, e.g. .a.b:1 ... I don't have a q instance to hand to test if that works but i'm almost sure it does.

A: You can use other function instead of 'value'. One option is 'eval' function:
        q)a:2;

        q) func:{ a:1; eval a}
        q)  func[]
        q) 1


text:
Q: Make a nn.Module faster I have a nn.Module (CRAFT from clovaai) and I am a bit bothered because the prediction is quite long (~13s) on my CPU.
Is there general tips (other than taking a GPU) to improve the prediction with such networks ?
Thanks

A: Pruning
You should look into "model pruning". It's a general concept in the field for which there are a number of tools and techniques.
The basic idea is that large networks can often be pretty "sparse", meaning that the majority of the weights are not contributing very much to the final output. As such, you can remove them and observe fairly little degradation in performance. Removing weights from the network reduces its size and therefore also how much work inference requires.
Reducing precision
This I am less familiar with in practice, but the idea is that if you reduce the "precision" (i.e. bit-depth) of the computations at runtime, you can similarly trade accuracy (or really, precision) for speed in inference.


text:
Q: android want to add searchview in actionbar but app crash i am working on action bar . i want to add searchview option on the action bar but app crash here.
this is crash

this is my code of option menu xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/search"
    android:title="Search"
    android:icon="@drawable/search"
    android:showAsAction="collapseActionView|ifRoom"
    android:actionViewClass="android.widget.SearchView"/>

this is the code of searchable.xml
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="@string/enter"
android:includeInGlobalSearch="false"
android:label="@string/search"
android:searchSettingsDescription="@string/search_global_description" />

and this is my activity code
    public class Thrd extends ActionBarActivity {
    Menu m;
    final Context context=this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_thrd);

        getSupportActionBar().setTitle("3rd page");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#20a780"));
        getSupportActionBar().setBackgroundDrawable(colorDrawable);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate( R.menu.options_menu, menu );

        // Add SearchWidget.
        SearchManager searchManager = (SearchManager) getSystemService( Context.SEARCH_SERVICE );
        SearchView searchView = (SearchView) menu.findItem( R.id.search ).getActionView();

        searchView.setSearchableInfo( searchManager.getSearchableInfo( getComponentName() ) );

        return super.onCreateOptionsMenu( menu );
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.search:
                onSearchRequested();

                return true;
            case R.id.action_Exit:
                openExit();
                return true;
            default:
                return super.onOptionsItemSelected(item);
    }
}

    private void openExit() {

    }

}

please help me to solve my problem.thanks advance

A: This was how I implemented my search handling.
In the XML folder under layout, add a searchable.xml file and put this code like so:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_name"
android:hint="Search Trends" />

Then in your ANDROID manifest file, add
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="com.tobisoft.trendify.MainActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
//This is the meta to add for your activity
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchResultsActivity" />
</activity>

Also you would need to make an activity for the search results like so:
<activity
android:name=".SearchResultsActivity"
android:label="@string/app_name"
android:theme="@style/MyMaterialTheme">
<!-- to identify this activity as "searchable" -->
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
</activity>

now in the menu folder, with a file name main.xml (or anything you are using)
<item
android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:orderInCategory="100"
android:title="@string/action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always" />

You can get the icon yourself by a simple google search. You would also need to add the AppCompat Library to your project, something you can also do from a simple google search. In the SearchResultsActivity, add this:
public class SearchResultsActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
handleIntent(getIntent());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
SearchManager searchManager =
(SearchManager)getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return true;
}

@Override
protected void onNewIntent(Intent intent) {
    handleIntent(intent);
}

private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//use the query to search
}
}
}

The activity_result.xml layout file is this :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff141414">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:textSize="@dimen/_25sdp"
android:textStyle="bold"
android:text="Search Result goes here!"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

In your MainActivity.java add this:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView)menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return true;
}

All this shld help your app on the right track. Hope it helps

A: Changing to import android.support.v7.widget.SearchView helped me and also change these lines
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView= (SearchView) searchItem.getActionView();
        searchView.setOnQueryTextListener(this);`


text:
Q: Run a java method by passing class name and method name as parameter I am trying to make a program that executes a particular method when the class name and method name are passed as String parameter to the caller. Consider the code below. I have a class CarBean :
public class CarBean {

    private String brand;
    private String color;

    /**
     * @return the brand
     */
    public String getBrand() {
        return brand;
    }

    /**
     * @param the brand to set
     */
    public void setBrand(String brand) {
        this.brand= brand;
    }

    /**
     * @return the color
     */
    public String getColor() {
        return color;
    }

    /**
     * @param the color to set
     */
    public void setColor(String color) {
        this.color= color;
    }

}

Now I want to run this via a method as below :
runTheMehod("CarBean","getColor");

The implementation of runTheMethod would be like this :
public runTheMethod(String className, String methodName){
try {
            Object carObj = Class.forName(className).newInstance();
            //What to do now???
        } catch (InstantiationException | IllegalAccessException
                | ClassNotFoundException e) {
            e.printStackTrace();
        }
}

I can get an object using the class name. Now I need to cast it to a CarBean object and then I can run its method. So wondering how to cast it at runtime as the classname would be different for each call. Also, can I check whether the class has specific method before I try call it?
Any suggestion on the problem would be appreciated. Also, I'm all ears to know if there is a better approach to do this.

A:
What to do now???

You can now call the method on your carObj like this:
Method method = carObj.getClass().getMethod(methodName);
method.invoke(carObj);

See also:
Method.invoke

A: If all you are trying to do is call a method by name, you don't need to cast it to anything. It is sufficient to use the Object with further reflection.
See Class.getDeclaredMethod(), as in:
Object carObj = ...;
Method method = carObj.getClass().getDeclaredMethod(methodName, ...);
Object retObj = method.invoke(carObj, ...);

Note that we don't care what type carObj actually is, although if you wanted to check you could always use instanceof or Class.isAssignableFrom or Class.isInstance.
It is a bit weird, though, that you are instantiating a new object then calling one of its methods all in one go. That object goes away once your runTheMethod returns.

By the way, it looks like you're just trying to get and set bean properties. You might want to have a look at Apache Commons BeanUtils instead, then your example becomes simply:
CarBean bean = ...;
String color = (String)PropertyUtils.getSimpleProperty(bean, "color"); // calls getter.

A: I doubt you really need to do this. I suspect you have an XY Problem. Your question is somewhat similar to asking whether Java has an eval function and the correct answer is similar:
First ask yourself, where did these String come from? Did another part of your program generate them, or was it input provided by the user?

*

*Another part of my program generated it: so, you want one part of your program to decide the kind of operation to perform, but not perform the operation, and a second part that performs the chosen operation. Instead of generating and then evaluating Strings, use the Strategy, Command or Builder design pattern, as appropriate for your particular case.

*It is user input: the user could input anything, including class and method names that, when executed, could cause your program to misbehave, crash, expose information that should be secret, damage persistent information (such as the content of a database), and other such nastiness. The only way to prevent that would be to parse the Strings and then either immediately execute the method on a successful parse, or have the parser create a Command object for later execution.


text: Q: How to determine the shard Id for a particular key in redis? I have a number of Redis shards, and am trying to retrieve the shard details given a key with the Redis Python client. Is there any way to do this?


text:
Q: Works on codepen not on site, why? Hey guys my code is working fine on codepen but not on my site. Can you tell me why? I have Jquery 1.11.1 included.
It behaves like the jquery was not recognized...
Here's my codepen, site and the function:
http://codepen.io/Nikolaus91/pen/azgLJG
http://178.62.215.130/LAMBRE/NewApp/subpages/kosmetykaPielegnacyjna/3.ProductPage.html#
 jQuery(document).ready(function ($) {
    var topis = $('.trigger_opis');
    var opis = $('#opis');
    var tskl = $('.trigger_skl');
    var skl = $('#sklaktywne');
    var tcos = $('.trigger_dzial');
    var cos = $('#dzialanie');
    var tbadania = $('.trigger_badania');
    var badania = $('#badania');
    var all = $('.describ');
    var all3 = $('.marker');

    all3.slideUp(10);
    console.log(all3);
    topis.click(function (e) {
        all.fadeOut(500);
        e.preventDefault();
        opis.delay(100).fadeIn(2000);
console.log(opis)
    });
    tskl.click(function (e) {
        all.fadeOut(200);
        e.preventDefault();
        skl.delay(100).fadeIn(2000);

    });
    tcos.click(function (e) {
        all.fadeOut(200);
        e.preventDefault();
        cos.delay(100).fadeIn(2000);

    });
    tbadania.click(function (e) {
        all.fadeOut(200);
        e.preventDefault();
        badania.delay(100).fadeIn(2000);

    });

});

A: The issue was in timing and order of code execution. Somehow pasting the code at the begining of my script.js solved it.


text:
Q: Does a protocol continue to be in memory and usable by other drivers even after the driver that installed it is unloaded? If we have a driver that installs a protocol in EDK2/UEFI and then that driver is unloaded, does the protocol continue to exist and be usable by other drivers and services?
Same question for UEFI applications.
I am mostly wondering if the UEFI framework somehow ties the protocols to the drivers that installed them and if the driver is unloaded does the protocol remain usable by other drivers after the image is unloaded or does the protocol also exit memory when the driver is unloaded.
I think code could certainly be made to make this be the case that when the driver exits it uninstalls the protocol it made, however does this occur by default within UEFI/EDK2? Or would this only occur if the driver explicitly stated to uninstall the protocol when it is unloaded?
Additionally, what is best practice for industry here? Should protocols generally continue to live on past the drivers that installed them or should the two be linked?
Sorry if this question is high level. I am trying to gain some high-level intuition for this topic.

A: A driver or application is required to uninstall its protocols and free the associated memory before exiting. It is not done automatically by the UEFI core.
Since protocols generally contain pointers to functions in the driver, it would be impossible for the driver to be unloaded while the protocols still exist. (However, it would be possible to orphan a protocol that doesn't contain any function pointers.)
(Citations are from UEFI specification version 2.8.)
7.4, EFI_IMAGE_ENTRY_POINT:

If the image supports dynamic unloading, it must supply an unload function in the EFI_LOADED_IMAGE_PROTOCOL structure before returning control from its entry point.

7.4 Exit:

When an EFI boot service driver or runtime service driver exits, firmware frees the image only if the ExitStatus is an error code; otherwise the image stays resident in memory. The driver must not return an error code if it has installed any protocol handlers or other active callbacks into the system that have not (or cannot) be cleaned up. If the driver exits with an error code, it is responsible for freeing all resources before exiting.

7.4, UnloadImage:

If the image has been started and has an Unload() entry point, control is passed to that entry point. If the image's unload function returns EFI_SUCCESS, the image is unloaded; otherwise, the error returned by the image's unload function is returned to the caller. The image unload function is responsible for freeing all allocated memory and ensuring that there are no references to any freed memory, or to the image itself, before returning EFI_SUCCESS.
If the image has been started and does not have an Unload() entry point, the function returns EFI_UNSUPPORTED.

4.7.3:

Any protocols installed or memory allocated ... must be uninstalled or freed [in the driver's Unload function].


text:
Q: How to get AdditionalUserInfo of a signed-in user (Auth > Web > Twitter)? I use firebase Auth (Web version 8) > Twitter for user log-in/ sign-up in my vue app, using Firebase auth getRedirectResult() method. This method returns a UserCredential object as expected (that contains the AdditionalUserInfo details). I use this data and store it in the database.
Is there  way to retrieve the AdditionalUserInfo of the current signed-in user later i.e. after the initial re-direct ? (as this will be useful for me to handle scenarios like error while saving the data first-time, update the latest AdditionalUserInfo from the provider, etc.)


text:
Q: What is the distribution followed by this function of random variables $X$ and $Y$ are independently distributed $U(0,1)$ random variables (Uniform distribution)
Find the Variance of the random variable
$U = \dfrac{\ln(X)}{( \ln(X)+\ln(1-Y) )}$

I know $-\ln(X)$ follows $\exp(1)$ and $(1-Y)$ is also $U(0,1)$
Therefore it becomes $\exp(1)$ in the numerator and $\text{gamma}(1,2)$ in the denominator.
I dont know what to do next.

A: Write as
$$
U=\frac{-\ln X}{-\ln X-\ln (1-Y)}
$$
As you noted $-\ln X\sim \exp(1)$ and because $1-Y\sim \text{Unif}(0,1)$ it folows that $-\ln(1-Y)\sim \exp(1)$. Since $-\ln X$ and $-\ln (1-Y)$ are independent it follows that $U\sim \text{Beta}(1,1)$ which is the same as a uniform random variable on $(0,1)$.

A: $G(\lambda)=e^{-x}x^{\lambda-1};x>0,\lambda>0 $ and $B_1(u,v)={x^{u-1}}(1-x)^{v-1} ; 0<x<1 ,u>0,v>0 $
$X \sim G(\lambda) $ and $Y\sim G(m)$
$\dfrac{X}{X+Y} \sim B_1(\lambda,m)$
And good luck for JAM $2019$


text:
Q: Is there a reason phase information isn't given for RF wideband amplifiers? I have an application where I would like to amplify a HF signal (25 MHz) by around 20dB.  The signal can't be inverted (it sits within a PLL loop where the phase is important).  I considered building my own, but then I figured this component ought to be fairly common and will be much better than anything I'd build myself, with everything on a small die.
I checked the datasheets of many wideband mmic amplifiers offered by my local distributor and I noticed that none of them actually said whether the amplifier was inverting or not.  I suspect that most are based on some kind of collector feedback arrangement (common for RF amplifiers) but I can't be sure.  That would make them inverting.
None of the datasheets I examined offered non-inverting as a distinguishing feature, so I'm wondering if I'm missing something obvious?  I realize I could cascade two low attenuating amps together, but that's a bit of a pain.  A quick search on the internet threw up the NE5205, but like many RF components it seems to have gone the way of the dodo.  Is there a reason phase isn't important or relevant in RF wideband amps and what do you do when you require a non-inverted signal?


text:
Q: Calling GetRequestStream() hangs WPF UI for 1sec I have created a wpf application which has controls one label and two butons for start and stop timers.
I have created two DispatcherTimers one timer will fire after every 50 milliseconds and update the lable with count value. Another DispatcherTimer will fire after every 2 seconds it will Post data to a HTTP post test server called "http://posttestserver.com/post.php?dir=Test". In this timer i am using GetRequestStream which causes UI to stop 1 sec but my data is posting to posttestserver.
I have used the following code.
public partial class MainWindow : Window
    {
    static int count = 0;
    DispatcherTimer dispatchtimer = null;
    DispatcherTimer WebDispatchTimer = null;
    public MainWindow()
    {
        InitializeComponent();
        dispatchtimer = new DispatcherTimer();
        WebDispatchTimer = new DispatcherTimer();
        WebDispatchTimer.Interval = TimeSpan.FromMilliseconds(2000);
        dispatchtimer.Interval = TimeSpan.FromMilliseconds(50);
        dispatchtimer.Tick += new EventHandler(dispatchtimer_Tick);
        WebDispatchTimer.Tick += new EventHandler(senddata_Tick);
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        WebDispatchTimer.Start();
        dispatchtimer.Start();
    }
    private void dispatchtimer_Tick(Object sender, EventArgs args)
    {
        count += 1;
        label1.Content = count.ToString();
    }
    private void senddata_Tick(Object sender, EventArgs args)
    {
        string postdata = "This is a test that posts this string to a Web server\n";
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://posttestserver.com/post.php?dir=abcd");
            request.Method = "POST";
            request.ProtocolVersion = HttpVersion.Version11;
            byte[] byteArray = Encoding.UTF8.GetBytes(postdata);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            request.Proxy = null;
            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Flush();
                dataStream.Close();
            }
            var response = request.GetResponse() as HttpWebResponse;
            response.Close();
            request.Abort();
            request = null;
        }
        catch (WebException ex)
        {
            MessageBox.Show(ex.Message);
            WebDispatchTimer.Stop();

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            WebDispatchTimer.Stop();
        }
    }
    private void button2_Click(object sender, RoutedEventArgs e)
    {
        WebDispatchTimer.Stop();
        dispatchtimer.Stop();
    }
}

I don't want my UI to hang for 1 sec. where i made a mistake ? Help me.


text:
Q: How can I print out all text in a web table column in python using selenium? I am attempting to use a for-loop in python to print out the text in a web table column using the xpath of all cells in the column. The xpath is similar to this:
//*[@id="webTable"]/tbody/tr[2]/td[6]

The for-loop I am using is written like this:
for x in range(totalRows):
    y = driver.find_elements(by = By.XPATH, value = '//*[@id="webTable"]/tbody/tr[' + str(x) + ']/td[6]')
    print(y)

However, when I run the program, this is the output that I get:
[<selenium.webdriver.remote.webelement.WebElement (session="e8afe17e1e80e6c09dd2656800326654", element="c488195e-8751-43c8-9d01-6e873cb2cc4a")>]
[<selenium.webdriver.remote.webelement.WebElement (session="e8afe17e1e80e6c09dd2656800326654", element="70f9ad39-4bdd-4bcf-b869-c31968de4492")>]
[<selenium.webdriver.remote.webelement.WebElement (session="e8afe17e1e80e6c09dd2656800326654", element="f8fd427e-2bd3-4995-8b24-7cb7bda14f1a")>]
[<selenium.webdriver.remote.webelement.WebElement (session="e8afe17e1e80e6c09dd2656800326654", element="0541eb71-24a1-44e9-bb9d-bacc63426bad")>]
[<selenium.webdriver.remote.webelement.WebElement (session="e8afe17e1e80e6c09dd2656800326654", element="b19a839e-a6c1-43f2-bcf1-1f0692ff2c0f")>]
[<selenium.webdriver.remote.webelement.WebElement (session="e8afe17e1e80e6c09dd2656800326654", element="b427383a-31a5-49f8-a466-62fb5a489047")>]
[<selenium.webdriver.remote.webelement.WebElement (session="e8afe17e1e80e6c09dd2656800326654", element="1cd4bd3f-6e7f-4a89-950e-0f5dab47eabd")>]
[<selenium.webdriver.remote.webelement.WebElement (session="e8afe17e1e80e6c09dd2656800326654", element="5c964e47-2fff-4c4d-9743-eecbd1c7bea6")>]
[<selenium.webdriver.remote.webelement.WebElement (session="e8afe17e1e80e6c09dd2656800326654", element="54ff1ef7-0693-43e2-939e-c387f8f20e06")>]
[<selenium.webdriver.remote.webelement.WebElement (session="e8afe17e1e80e6c09dd2656800326654", element="21a63bd7-7dc5-4860-bfb2-1309a842c2f7")>]
[<selenium.webdriver.remote.webelement.WebElement (session="e8afe17e1e80e6c09dd2656800326654", element="aee78709-f4ee-4e0f-8cb7-6c3114b52fba")>]
[<selenium.webdriver.remote.webelement.WebElement (session="e8afe17e1e80e6c09dd2656800326654", element="28ef515e-4c66-472b-8126-76793eeebee2")>]
[<selenium.webdriver.remote.webelement.WebElement (session="e8afe17e1e80e6c09dd2656800326654", element="2fb995ff-9100-4124-9efe-f8c2bfe49767")>]

I tried writing the for-loop like this:
for x in range(totalRows):
    y = driver.find_elements(by = By.XPATH, value = '//*[@id="webTable"]/tbody/tr[' + str(x) + ']/td[6]')
    print(y.text)

and:
for x in range(totalRows):
    y = driver.find_elements(by = By.XPATH, value = '//*[@id="webTable"]/tbody/tr[' + str(x) + ']/td[6]').text
    print(y)

but when I write it like that, I receive this error:
AttributeError: 'list' object has no attribute 'text'

I don't know how else to extract the text within the cells, so any help would be appreciated!

A: Here is the solution:
table = driver.find_element(by=By.XPATH, value='//*[@id="webTable"]/tbody')
rows = table.find_elements(by=By.TAG_NAME, value="tr")

# column to choose by its index, say 2nd column in the table
desired_column = 1
desired_column_data = []

for row in rows:
    columns = row.find_elements(by=By.TAG_NAME, value='td')

    for index, col in enumerate(columns):
        if index == desired_column:
            desired_column_data.append(col.text)

print(desired_column_data)

Hope, it helps :)

A: driver.findElements returns List of WebElements. Hence you are getting expected error while trying to get text value of List object. Instead you should be using driver.findElement in your logic while iterating through totalRows.
for x in range(totalRows):
    y = driver.find_element(by = By.XPATH, value = '//*[@id="webTable"]/tbody/tr[' + str(x) + ']/td[6]').text
    print(y)


text:
Q: Multiple frameworks and common library Using iOS 8, Xcode 6.
Let's say I have 2 dynamic frameworks, frameworkA and frameworkB and they are both dependent on libC. In addition, I have an app that uses both frameworkA and frameworkB. My original thought was to make frameworkA and frameworkB umbrella frameworks and libC a subframework. However, Apple advises against umbrella framework and this post describes why umbrella framework is a bad idea due to potential linker conflict issue.
My second option is to use cocoapods (still new to this so a bit fuzzy on details) to use libC as a pod which then gets compiled into frameworkA and frameworkB. However, it occurred to me that both frameworks still has its own copy of the libC. Since the app uses both frameworks, will this result in a linker conflict issue as well? Is there a better way to solve this problem?
UPDATE
@Rob The projects I work on do require complex dependency management but I kept the problem domain simple in the question to try to better understand how and if using cocoapods can help solve the linker conflict issue with umbrella frameworks. I work with a team of developers who write libraries and can depend on each other's base libraries that provide versioned common APIs. We are required to package and deliver as few libraries as possible to a different organization that is building an app with our libraries and one of their key requirement is that we deliver a dynamic framework.

A: The best way to solve most problems is to put all the code in a project and compile it. When you have specialized problems that make that problematic, then you should look at other solutions, such as static libraries, and finally frameworks.
Static libraries can make sense if you have a code base that has pieces which require different build requirements. If all the pieces have the same build settings, then just "add files" them into your project from a "common" directory and build your project. Static libraries can be attractive if your build times are very significant and some pieces never change and you want to be able to "clean" without rebuilding those parts. But wait until you start having that problem before you go making complicated multi-package projects.
If you sell closed-source libraries, then frameworks are very attractive. You should strongly avoid adding third-party dependencies for the reasons you note. If you must, the best way is to help your customers package all the pieces as frameworks and have them link everything at the end. But that adds a lot of annoyance; so make sure you really need that third-party piece.
You might also consider frameworks if you have a very large piece of reusable code that has its own lifecycle separate from the main products. But again, keep it simple. Avoid third party stuff inside of it, and if you must have third party stuff, then have the consumers link it at the end.
(This isn't a new solution, BTW. When you use curl, if you want SSL, you need to also download and build OpenSSL and link them together yourself. Curl doesn't come with OpenSSL built in.)
But in the vast majority of cases, this is all overkill. Don't jump to frameworks. Don't jump to libraries. Just put all the code in the project and compile it. 90% of your problems will evaporate. iOS projects in particular just aren't that big usually. What problem is a framework solving?
If you have a lot of code that your organization uses repeatedly in lots of products, then I have heard many teams have good luck using internal CocoaPods to manage that. But that's just to simplify checking the code out. It still all goes into a project and you compile it together into one binary; no frameworks needed. Dynamic frameworks are a nice feature in for certain kinds of problems that were really painful before. But, for most situations, they're just complexity looking for a problem.
(If you have one of those specialized problems, edit your question and I'm happy to discuss further how you might approach it.)

EDIT: (You fall into that "specialized problem," so let's talk about it. I did, too, for many years inside of a large multi-team Mac and iOS dev environment. And we tried just about every different solution, including Frameworks. They're only new on iOS.)
Within an org like you describe, I would strongly recommend packaging each dependency as its own framework (AFNetworking, JSONKit, etc) and each of your pieces as a framework, and then have the app devs link all of them together at the end. In this way, it is identical to other dynamic libraries (libcurl, openssl, etc.) which require the app dev to link everything together.
In no case should dynamic frameworks include other frameworks that could otherwise be required (i.e. frameworks should never package "third party" stuff). That will explode. You cannot make that not explode. You'll either have bloat, build conflicts, or runtime conflicts. It's like merge conflicts. There's a point at which a developer has to make a choice. App-level linking is making that choice.
Making components over-dependent on other components is the source of decades of trouble, from Windows DLL Hell to iOS apps with competing crash handlers. All the best component systems look like Legos, where the end user assembles small pieces that have minimal dependencies. As much as possible, make your internal frameworks rely on nothing but Cocoa. This has some tangible design influences:

*

*Avoid directly requiring logging or analytic engines. Provide a delegate interface that can be adapted to the engines of the caller.

*Avoid trivial categories (methods that save just a few lines of code). Just write the code directly.

*Avoid adding framework dependencies that aren't buying you a lot. Don't add AFNetworking just to save a few lines of code over NSURLConnection. Of course if you're heavily relying on the features of another framework, that's different. But as a framework developer your threshold should be quite high before requiring another framework.

*Strongly avoid being clever in the build or version control. I've seen too many cases where people want to make everything "automatic" for the app-level developer, and so make the system really complicated. Just say "you need to link this and import this and put this in your app delegate startup." Don't create complicated build and version control systems to save 2 minutes on the first build or two lines of initialization logic. These things blow up and waste hours to work around. Don't get clever with +load magic. Just make it clear and consistent.

And of course, good luck. Supporting other devs is always an interesting challenge.


text:
Q: Designing UI in Flutter for Android Is it possible to design a Flutter UI via Android Studio by using a UI builder, like I would do when developing with Java/Kotlin?

A: Yes. You can try the Flutter UI Open-Source library. Try this GitHub repo for Flutter UI design https://github.com/ionicfirebaseapp/getflutter

A: Short answer, no.
But Flutter has something called Hot Reload, which allows you to see your chances within a second.
Flutter's hot reload feature helps you quickly and easily experiment, build UIs, add features, and fix bugs. Hot reload works by injecting updated source code files into the running Dart Virtual Machine (VM). After the VM updates classes with the new versions of fields and functions, the Flutter framework automatically rebuilds the widget tree, allowing you to quickly view the effects of your changes.
There's also something called Flutter Studio.

A: It's not supported right now. Flutter Studio doesn't look stable and have bugs in it. So the only preferable way up till now is to use Hot Reload. If you want to debug layout related issues, you can do the following:

*

*import this in the root file (e.g. main.dart)

import 'package:flutter/rendering.dart';

*in your main() function, add these lines to enable layout debugging before runApp() method:

debugPaintSizeEnabled = true;
debugPaintBaselinesEnabled = true;
debugPaintPointersEnabled = true;

A: yes offcourse ,mostly people using android studio - first install flutter and dart sdk .you also run in terminal flutter doctor.


text:
Q: What is deprecated_argument_run meant to do exactly? I found an odd hook in the WordPress documentation. deprecated_argument_run which has this "enlightening description".

Fires when a deprecated argument is called.

I pretty much figured that much out from the hook name.
What is this hook's intended use?

A: As @sally-cj already hinted at in his comment this is used for debugging purposes, helping developers by notifying them of the use of deprecated arguments in their codebase.
In core this is for example used to alert people of wrong arguments when using the REST API: https://core.trac.wordpress.org/browser/branches/5.2/src/wp-includes/rest-api.php#L177
But you could add your own function to that hook that does whatever you find useful - send a mail, log to a file,...

Core uses it inside the (private, so not intended for use by non core code) _deprecated_argument function.
And that function _deprecated_argument is actually used all over the place in core, for example inside get_the_author to give one random example.


text:
Q: Redefine a class to add new features or find a way around I would like to redefine a class of the core wpf API (UIElement), I don't want to inherit a class.
In have a project on the MS Kinect, I've re-implemented cursors mapped with the user's skeleton's hand. I've implemented similar event to those that the mouse raised (enter an elements, leave an element...). I want that all elements inheriting from UIElement to get some attached properties:
  KinectCursorEnter, KinectCursorMove...

and some Properties:
    public bool IsKinectLeftCursorOver { get; set; }
    public bool IsKinectLeftCursorDirectlyOver { get; set; }
    public bool IsKinectRightCursorOver { get; set; }
    public bool IsKinectRightCursorDirectlyOver { get; set; }
    public bool IsKinectLeftCursorCaptured { get; set; }
        ...

I know there's a lot ways to mess things up if I change such a class, but that's at this level that I want to add thoses properties. (UIElement already implement stuff such as MouseEnter, StylusEnter...). The Kinect is an input device as any other (mouse, stylus, keyboard...)
I've try:

*

*To inherit UIElement and add the feature , but then I would have to
reimplement all the Classes.

I've take a look:

*

*If there's such a thing as Ruby's open classes

*If I can use extension (link)

*If I can use in any way Adapter pattern

So far I'm using use:

*

*An interface and I redefine all element: I have a KinectButton that
inherit from Button and implements IKinectInputElement but I can't do that for some class which are sealed (Rectangle, Ellipse...)

I thing I a few months (years?) MSFT will implement those kind a Properties and method in Wpf API. But for now I need a way around.
PS: I don't want to control the mouse with one of the hand of the user. there is one mouse, I want to have two cursors. and I have events such as : KinectLeftCursorEnter, KinectRightCursorEnter and so on..

A: You can use Extension Methods to extend the class.


text:
Q: Running remote X11 applications with unity menu and look and feel How do I configure a server (12.10 - 13.10) to run remote X applications using the Unity menu and look and feel?
I can run applications fine by logging into the server from my desktop, like so:
# ssh -Y <servername>
# gedit
But the application doesn't run with the same look-and-feel as the rest of the applications on the screen.
All suggestions gratefully received!

A: Unity provides very limited ability to export it's desktop environment to remote machines.  CDE, it is not.
Instead, try using Unity Remote Desktop (VNC by any other name).  This is the 'Ubuntu approved' way to get the full Unity desktop running on your remote X server.  You will have the 'look and feel' because you are, in fact, actually using your Unity desktop for all your apps via (the VNC X client running on) your local X server.


text:
Q: How can I select everything between tags in Notepad++? I am doing some langauge translations of an old HTML website so I am just pasting the new translations from a Word document into the old files.
So I have to select everything between the tags (h2, p, li, etc.) and then paste the new text in – from a Word file. For selecting everything in between p tags I have to select one side of the inside tag, then hold Shift, then select the next side to highlight everything... my fingers are getting really tired, and I got 40 files (pages) total with 3 languages to do.
Is there a shortcut in Notepad++ to select everything between two tags (excluding the tags; like when you double click a word it selects the whole word).

This is some English that needs to be translated here.
I want to just click in this area to select all of this
text between these two paragraph tags.

This would be another block of translation to do

I want to click here and select everything between the li tags

A: if plugin install do not bother you, I highly recommend to install HTML Tag, especialy if you are an html eater.
Once setup, just ctrl+shift+t with cursor on the opening or closing tag

A: Direct answer:: No.
Can it be made?  Yes.
Simply?  Yes.
Into a single shortcut?  Yes
What's needed?  N++ PythonScript and HTML Tag plugins.
Why?  We are going to use the HTML Tag's Select Tag and Contents from a python script that will adjust the selection made by HTML Tag by moving the start to just after the first '>' and the end to just before the last '<'.
After installing the N++ PythonScript plugin create a new script with this code::
# Reduce selection to omit the outer most tags selected by the 'HTML Tag' plugin.

from Npp import *

def omit_tag( args ):
    editor.clearCallbacks()
    SelText = editor.getSelText()

    if SelText:
        orig_Start = editor.getSelectionStart()
        new_Start = orig_Start + SelText.find(">")

        orig_End = editor.getSelectionEnd()
        new_End = orig_Start + SelText.rfind("<")

        if new_Start > orig_Start and new_End < orig_End:
            editor.setSel( new_Start + 1, new_End )

def main():
    editor.callback( omit_tag, [SCINTILLANOTIFICATION.UPDATEUI] )
    notepad.runMenuCommand("HTML Tag", "Select Tag and Contents")

main()

After creating the script, use the PythonScript configuration dialog to add the script to the 'Menu Items' list (which will allow us to assign the shortcut).  Restart, then use the Settings->Shortcut Mapper::Plugins dialog, add a Shift+Alt+T shoftcut to the new entry for the script you just created.  Restart again to write out the new shortcut entry the N++ config.
So now (using your sample text), from the line where you wanted to click::
CTRL+T to jump to the other tag.
CTRL+Shift+T to select the whole tag block.
Shift+Alt+T to select the inner text.
If you attempt to select the 'content' portion of the  block you'll notice the line endings are captured too.  This could be seen as either a plus or minus depending on your viewpoint...
One recommendation, make use of SCI_SWAPMAINANCHORCARET to allow you to adjust either end of your selection using the normal movement and selection modifiers.  You can set it from the shortcut mapper on the Scintilla panel (near the bottom).  I've set mine to CTRL+Shift. which works great, since when already modifying a selection Shift is usually already pressed.
Hopefully that helps.  Have fun!

A: I would use the "Fold All" (Alt-0) feature so every paragraph is displayed as a seperate line. In Word I would add
 at the beginning of every line and
 at the end of every line and then overwrite complete lines using Shift-Down to select a line and Ctrl-V to paste the translated line from Word. Unfold All (Alt-Shift-0) unfolds everything once you are done.

A: This task of selecting text between tags can be accomplished without scripts, but not in Notepad++.
If you install SynWrite editor, just call command Search -- Select current token and text between tags is selected.

A: I know this post is 4 years old, but since I was in the very same situation, I thought it could be still useful.
You can also use a Macro, that will automaticaly underline text found between the symbol > and <.
To create the macro:
-Click before the tag
, so the flashing bar is on the left side the of the tag.
-In the menu, click on Macro - Start Recording
-Press CRTL+F. Find the symbol >, then close the window. This last part of the tag will be underlined.
-Press the right Arrow on your keyboard (one time).
-Hold Shift, then on the keyboard, press the End button twice (twice if the function Word wrap is activated; otherwise, press the button one time only).
-While holding Shift, press the left Arrow so the last tag is not underlined. Now, only the text between the tags will be underlined.
-Click Stop Recording, and click Save Current Recorded Macro.
I was using CTRL+SHIFT+NUMBPAD+ to activate the macro. It becomes pretty easy to go from one section to the other, and simply paste your new text.


text:
Q: Is decision boundary of penalized logistic regression linear? The decision boundary of SVM is a straight line. If we use e.g. RBF kernel, decision boundary is linear in hilbert space, but it the original space it is non-linear. I assume that the logistic regression has linear decision boundary. Is it linear also after using of penalty term, such as elastic net?

A: The penalty terms are regularisation terms that affect the training process and thus the decision boundary found (i.e. weights and/or bias). Once trained, the prediction is not affected by neither the regularisation method nor the loss function. So, any linear classifier/regressor is still linear after penalisation. That said, since logistic regression classifier has a linear decision boundary, it'll still have a linear decision boundary when penalised.


text:
Q: Pandas Can't Filter by Column Values I want to get only those rows in a dataframe where a particular coulmn value is less than some upper bound.
I used to do this:
final_data[final_data['Time']<30.000000]

It gives me the error:
IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match

I again tried with:
final_data.loc[:,final_data['Time']<30.000000]

and I get:
IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match

How can I implement the filter in pandas based on column value?

A: In my opinion first solution should working perfectly in pandas 0.23.0.
Another solutions are convert column to numpy array for avoid alignment of indexes between mask and DataFrame:
final_data[final_data['Time'].values < 30.000000]

final_data.loc[:,final_data['ResponseSLATime'].values < 30.000000]

Or use query:
final_data.query('Time < 30.000000')


text:
Q: Allocating values to specific csv columns in Powershell I'd like to ask if anybody can please advise a way how to allocate a value in variable to a column in csv.
For example:
TriggeredBy | TriggeredTime | Firstname | Lastname | Username | ....

Throughout my script I'm modifying input data and on the go I'd like it to fill in the row to the relevant column.
Then another script from a different server has to take over, read the calculated values and add its calculated results into its dedicated columns.
The output would be a row where I can see that all the results.
In the end it's supposed to serve as a sort of database.
Sample of script here would be:
$aduser = Get-ADUser -Filter {sAMAccountName -like $username} -Properties *
$Firstname = $aduser.GivenName
$Firstname | Export-CSV -Path $filepath | Select-Object "First Name"

$Lastname = $aduser.Surname
$Lastname | Export-CSV -Path $filepath | Select-Object "Last Name"

$TriggeredBy = $env:UserName
$TriggeredBy | Export-CSV - Path $filepath | Select-Object "TriggeredBy"

...
Throughout the process all saved in one relevant row. Next process does the same for the following row etc...
The "Export-CSV ...." part is obviously wrong, I would need some alternative
Many thanks!

A: Use Select-Object with calculated properties:
Get-ADUser -Properties * -Filter "sAMAccountName -eq `"$username`"" |                            #`
  Select-Object @{ n='FirstName'; e='GivenName' },
                @{ n='Last Name'; e='Surname' },
                @{ n='TriggeredBy'; e={ $env:UserName } } |
    Export-Csv -NoTypeInformation -Literalpath $filePath

Note that I've used a string as the -Filter argument, because that's what it ultimately becomes anyway. Using script-block literal syntax { ... } is tempting, but ultimately causes more problems than it solves - see this answer.
Note that in Windows PowerShell Export-Csv creates ASCII(!)-encoded files by default, which can result in loss of information; use the -Encoding parameter to change that.
PowerShell [Core] v6+, by contrast, commendably defaults to (BOM-less) UTF-8; also, the
-NoTypeInformation switch is no longer necessary there.
If you want to append to an existing CSV file (which needs to have the same column structure), use the -Append switch.


text:
Q: menu css menu display centre rather than left I have this html code:

header

LINK

LINK

SUB LINK

LINK

with this CSS for my menu:
#cssmenu *{
    z-index: 999;
}
#cssmenu ul { margin: 0; padding: 0; text-align: center; }
#cssmenu li { margin: 0; padding: 0;}
#cssmenu a { margin: 0; padding: 0;}
#cssmenu ul {list-style: none;}
#cssmenu a {text-decoration: none;}
#cssmenu {
    width:100%;
    max-width:1000px;
    height: 50px;
    background-color: #666666; /* main background color */
}
#cssmenu > ul > li {
    display: inline-block;
    margin-left: 15px;
    position: relative;
}
#cssmenu > ul > li > a {
    color: #FFFFFF; /* main link text color */
    font-weight:bold;
    font-size: 15px;
    line-height: 50px;
    padding: 16px 20px;
-webkit-transition: color .15s;
   -moz-transition: color .15s;
     -o-transition: color .15s;
        transition: color .15s;
}
#cssmenu > ul > li > a:hover {
    color: #ffffff; /* main link text hover color */
    background-color:#666666; /* main link background hover color */
}
#cssmenu > ul > li > ul {
    opacity: 0;
    visibility: hidden;
    padding: 16px 0 20px 0;
    background-color: #666666; /*submenu link background color */
    text-align: left;
    position: absolute;
    top: 30px;
    left: 50%;
    margin-left: -90px;
    width: 180px;
-webkit-transition: all .3s .1s;
   -moz-transition: all .3s .1s;
     -o-transition: all .3s .1s;
        transition: all .3s .1s;
-webkit-border-radius: 5px;
   -moz-border-radius: 5px;
        border-radius: 5px;
-webkit-box-shadow: 0px 1px 3px rgba(0,0,0,.4);
   -moz-box-shadow: 0px 1px 3px rgba(0,0,0,.4);
        box-shadow: 0px 1px 3px rgba(0,0,0,.4);
}
#cssmenu > ul > li:hover > ul {
    opacity: 1;
    top: 50px;
    visibility: visible;
}
#cssmenu > ul > li > ul:before{
    content: '';
    display: block;
    border-color: transparent transparent rgb(250,250,250) transparent;
    border-style: solid;
    border-width: 10px;
    position: absolute;
    top: -20px;
    left: 50%;
    margin-left: -10px;
}
#cssmenu > ul ul > li { position: relative;}
#cssmenu ul ul a{
    color: #FFFFFF; /* submenu link text color */
    font-size: 13px;
    background-color: #666666; /*submenu background color (behind links) */
    padding: 5px 8px 7px 16px;
    display: block;
-webkit-transition: background-color .1s;
   -moz-transition: background-color .1s;
     -o-transition: background-color .1s;
        transition: background-color .1s;
}
#cssmenu > ul > li:hover {
    background-color:#666666; /*background color that shows on the main menu link when hovering over the sub menu */
}
#cssmenu > ul > li:hover > a{
    color: #FFFFFF; /* main menu link hover text color */
}
#cssmenu ul ul ul {
    visibility: hidden;
    opacity: 0;
    position: absolute;
    top: -16px;
    left: 206px;
    background-color:#666666;
    padding: 16px 0 20px 0;
    text-align: left;
    width: 160px;
-webkit-transition: all .3s;
   -moz-transition: all .3s;
     -o-transition: all .3s;
        transition: all .3s;
-webkit-border-radius: 5px;
   -moz-border-radius: 5px;
        border-radius: 5px;
-webkit-box-shadow: 0px 1px 3px rgba(0,0,0,.4);
   -moz-box-shadow: 0px 1px 3px rgba(0,0,0,.4);
        box-shadow: 0px 1px 3px rgba(0,0,0,.4);
}
#cssmenu ul ul > li:hover > ul {
    opacity: 1; left: 196px;
    visibility: visible;
}

#cssmenu ul ul a:hover{
    background-color: #666666; /*submenu link hover color */
    /* color:#000000; */
}
#cssmenu > ul > li.active {
    background-color:#666666;
}

as the page width gets bigger, the menu displays more to the left. how can i make is always display center under the header?
here is a fiddle with my full code: http://jsfiddle.net/Nqxe9/

A: To your CSS add the styles:
#cssmenu {
margin:0px auto;
padding: 9px 9px 0;
}

Fiddle :http://jsfiddle.net/Nqxe9/5/
Perfect!!
Done ;)

A: Add below css for li.
#cssmenu > ul > li {
    display: inline-block;
    float: left;
    margin-left: 15px;
    position: relative;
}

you need to add float:left
Live Demo

A: I added a margin: 0 auto;
JSFiddle

A: I'd like to see the CSS for your header; however, if you're trying to make it stay under the header I'd make a div to surround the header and the menu and put properties to that div to center it.

header

LINK

LINK

SUB LINK

LINK


text:
Q: Fetch first location on android and stop updates I still have problem with fetching first location on android. I am using Criteria like
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        criteria.setSpeedRequired(true);
        String provider = lm.getBestProvider(criteria, true);

        if(provider!=null && provider.length()>0){
            lm.requestLocationUpdates(provider, 0, 0, this);
        }

I need to stop when first time get location like lm.removeUpdates(this);
Where to put that line of code ? In onLocationChanged ?

A: Yes. onLocationChanged will be called on each location update. If you want one only, you can remove it there.

A: public class GPSLocatorActivity extends Activity {
    double current_lat, current_lng;
    MapView mapView;
    boolean flag = true;

    /** Called when the activity is first created. */

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /* Use the LocationManager class to obtain GPS locations */

        LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        LocationListener mlocListener = new MyLocationListener();

        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1,
                mlocListener);

    }

    /* Class My Location Listener */

    public class MyLocationListener implements LocationListener

    {

        public void onLocationChanged(Location loc) {
            current_lat = loc.getLatitude();
            current_lng = loc.getLongitude();

            if (flag == true) {
                flag = false;
                go(current_lat, current_lng);

            }
        }

        public void onProviderDisabled(String provider) {
            Toast.makeText(getApplicationContext(), "Gps Disabled !!! Please Enable It.",
                    Toast.LENGTH_SHORT).show();

        }

        public void onProviderEnabled(String provider)

        {
            Toast.makeText(getApplicationContext(), "Gps Enabled",
                    Toast.LENGTH_SHORT).show();

        }

        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

    }/* End of Class MyLocationListener */

    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;

    public void go(double c_lat, double c_lng) {
              System.out.println("your current Lat :: " + c_lat);
              System.out.println("your current Lng :: " + c_lng);

             /*turn of gps now */
               turnGPSOff();
         }
    private void turnGPSOff() {
        String provider = Settings.Secure.getString(getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

        if (provider.contains("gps")) { // if gps is enabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings",
                    "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3"));
            sendBroadcast(poke);
        }
    }

}/* End of UseGps Activity */


text:
Q: classic asp calling an api using addheader for authorization I have a page that calls an api that in test mode has not required any authorization.
We are now moving to a live environment where a username and password will be required.
The api provider has sent the following message:

To access these services please send the requests by adding following HTTP header.
  Authorization: Basic Base64Encode("username: password")

I'm not sure of the correct syntax and wondered if someone could help me out.
The original call (and working perfectly) is:
Dim xmlobj, username, password
username="myusername"
password="mypassword"
Set xmlobj = server.CreateObject("MSXML2.DOMDocument.3.0")
xmlobj.async = false
xmlobj.setProperty "ServerHTTPRequest", True
xmlObj.AddHeader "Authorization", "Basic", Base64Encode(username & ":" & password)
xmlobj.load(sUrl)

The above code throws an error

/api-test.asp |20|800a000d|Type_mismatch:_'Base64Encode'

Any help would be greatly appreciated.

A: Like I've mentioned in the comments, the syntax for the Authorization header is incorrect.
The API example doesn't expect "Base64Encode('username','password')" this is an example supplied by the API to show you how to take the string "username:password" and Base64 encode it which is what the Authorization header is expecting.
But you still need to have the Base64Encode() function definition for the code to work.

Base64Encode() and MyASC() functions are taken from Base64 encode VBS function (vb encoder algorithm), source code

Something like this should work;
<%
Function Base64Encode(inData)
  'rfc1521
  '2001 Antonin Foller, Motobit Software, http://Motobit.cz
  Const Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
  Dim cOut, sOut, I

  'For each group of 3 bytes
  For I = 1 To Len(inData) Step 3
    Dim nGroup, pOut, sGroup

    'Create one long from this 3 bytes.
    nGroup = &H10000 * Asc(Mid(inData, I, 1)) + _
      &H100 * MyASC(Mid(inData, I + 1, 1)) + MyASC(Mid(inData, I + 2, 1))

    'Oct splits the long To 8 groups with 3 bits
    nGroup = Oct(nGroup)

    'Add leading zeros
    nGroup = String(8 - Len(nGroup), "0") & nGroup

    'Convert To base64
    pOut = Mid(Base64, CLng("&o" & Mid(nGroup, 1, 2)) + 1, 1) + _
      Mid(Base64, CLng("&o" & Mid(nGroup, 3, 2)) + 1, 1) + _
      Mid(Base64, CLng("&o" & Mid(nGroup, 5, 2)) + 1, 1) + _
      Mid(Base64, CLng("&o" & Mid(nGroup, 7, 2)) + 1, 1)

    'Add the part To OutPut string
    sOut = sOut + pOut

    'Add a new line For Each 76 chars In dest (76*3/4 = 57)
    'If (I + 2) Mod 57 = 0 Then sOut = sOut + vbCrLf
  Next
  Select Case Len(inData) Mod 3
    Case 1: '8 bit final
      sOut = Left(sOut, Len(sOut) - 2) + "=="
    Case 2: '16 bit final
      sOut = Left(sOut, Len(sOut) - 1) + "="
  End Select
  Base64Encode = sOut
End Function

Function MyASC(OneChar)
  If OneChar = "" Then MyASC = 0 Else MyASC = Asc(OneChar)
End Function

Dim xmlobj, username, password
username="myusername"
password="mypassword"
Set xmlobj = server.CreateObject("MSXML2.XMLHTTP.3.0")
xmlobj.Open "GET", sUrl, False
xmlobj.setRequestHeader "Authorization", "Basic " & Base64Encode(username & ":" & password)
xmlobj.Send

Dim xmldoc
If xmlobj.status = 200 Then
  Set xmldoc = Server.CreateObject("MSXML2.DOMDocument.3.0")
  xmldoc.Load xmlobj.ResponseXML
Else
  Response.Write "An error occurred!"
End If
%>


text:
Q: How can I use my own custom client classes when using JAX-WS? I'm using JAX-WS as a client and am generating classes from it.  The problem with the generated classes is that they are simple pojos without any convenience methods.  Is there a way I can use my own custom classes that I've written myself, instead?  They would have the same fields and name as the generated classes would, but they would allow me to create my own convenience methods.

A: if you are using JAX-WS you should be able to use the -keep option to keep the java source code when using wsimport. Then you should be able to modify it at your own convenience. E.g.
wsimport -keep -p stockquote http://stockquote.xyz/quote?wsdl

Reference for wsimport command


text:
Q: desktop notification I wanna build custom desktop notification for my desktop application. notifyicon seems to be not working may be i can fix that. Can we extend notifyicon class and develop my custom desktop notification control? or do we have any tutorial about the same

A: The class Notifyicon is sealed, this mean that you can not extend it.
You can create a separate window, that works like notification. But i am not aware about any tutorial for this.


text:
Q: Store in a variable the result of a shell as Int So I work with files, and I need to know the largest line in file X. Using Unix awk results in a Int that I'm looking for. But in Haskell how can I return that value and save it to a variable?
I tried define something with IO [Int] -> [Int]
maxline = do{system "awk ' { if ( length > x ) { x = length } }END{ print x }' filename";}

doesn't work cause:
Couldn't match expected type 'Int',against inferred type 'IO GHC.IO.Exception.ExitCode'

A: This is because the system action returns the exit status of the command you run which cannot be converted to Int. You should use the readProcess to get the commands output.
> readProcess "date" [] []
  "Thu Feb  7 10:03:39 PST 2008\n"

Note that readProcess does not pass the command to the system shell: it runs it directly. The second parameter is where the command's arguments should go. So your example should be
readProcess "awk" [" { if ( length > x ) { x = length } }END{ print x }", "/home/basic/Desktop/li11112mp/textv"] ""

A: You can use readProcess to get another program's output. You will not be able to convert the resulting IO String into a pure String; however, you can lift functions that expect Strings into functions that expect IO Strings. My two favorite references for mucking about with IO (and various other monads) are sigfpe's excellent blog posts, You Could Have Invented Monads! (And Maybe You Already Have.) and The IO Monad for People who Simply Don't Care.
For this particular problem, I would strongly suggest looking into finding a pure-Haskell solution (that is, not calling out to awk). You might like  readFile, lines, and maximumBy.