text:
Q: Can we run multiple fb apps using just 1 sub-domain with SSL? [I read all the similar questions previously answered, but the answers seemed rather conflicting. Please do only respond if you are 100% certain of the answer to prevent further confusion ;-) Thank you!]
We are planning to create facebook apps for clients.
Is it possible to use the same sub-domain for all apps in a way that requires a basic SSL certificate for all apps, so that a basic SSL certificate would suffice? (making it much more time and cost efficient for us)
If not, what would be the most time and cost efficient way to do it?
Using a wildcard SSL certificate?
Or a unified communication certificate?
And does anyone have a great recommendation where to best get the kind we need, obviously one acceptable by Facebook?
Thank you so much for your help!

A: You can point all of your applications to the same sub-domain and just have each application residing in a different folder.
As you said - you must ensure that this domain has an SSL certificate implemented on the server..


text:
Q: Mailcatcher Error: ~~> ERROR: Something's using port 1025. Are you already running MailCatcher? I have installed the gem mailcatcher. And when I want to run the mailcatcher I have this error message:
$ mailcatcher
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::BASE
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of BASE was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::EXCEPTION_ALL
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of EXCEPTION_ALL was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::EXCEPTION_NaN
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of EXCEPTION_NaN was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::EXCEPTION_INFINITY
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of EXCEPTION_INFINITY was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::EXCEPTION_UNDERFLOW
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of EXCEPTION_UNDERFLOW was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::EXCEPTION_OVERFLOW
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of EXCEPTION_OVERFLOW was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::EXCEPTION_ZERODIVIDE
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of EXCEPTION_ZERODIVIDE was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::ROUND_MODE
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of ROUND_MODE was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::ROUND_UP
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of ROUND_UP was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::ROUND_DOWN
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of ROUND_DOWN was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::ROUND_HALF_UP
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of ROUND_HALF_UP was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::ROUND_HALF_DOWN
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of ROUND_HALF_DOWN was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::ROUND_CEILING
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of ROUND_CEILING was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::ROUND_FLOOR
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of ROUND_FLOOR was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::ROUND_HALF_EVEN
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of ROUND_HALF_EVEN was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::SIGN_NaN
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of SIGN_NaN was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::SIGN_POSITIVE_ZERO
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of SIGN_POSITIVE_ZERO was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::SIGN_NEGATIVE_ZERO
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of SIGN_NEGATIVE_ZERO was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::SIGN_POSITIVE_FINITE
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of SIGN_POSITIVE_FINITE was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::SIGN_NEGATIVE_FINITE
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of SIGN_NEGATIVE_FINITE was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::SIGN_POSITIVE_INFINITE
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of SIGN_POSITIVE_INFINITE was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::SIGN_NEGATIVE_INFINITE
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of SIGN_NEGATIVE_INFINITE was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::INFINITY
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of INFINITY was here
/Users/romenigld/.rvm/gems/ruby-2.2.3@global/extensions/x86_64-darwin-14/2.2.0-static/bigdecimal-1.2.7/bigdecimal.bundle: warning: already initialized constant BigDecimal::NAN
/Users/romenigld/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121: warning: previous definition of NAN was here
Starting MailCatcher
~~> ERROR: Something's using port 1025. Are you already running MailCatcher?

Then when I try to use the http://localhost:1080/ shows me the app mailcatcher.
But what I need to do with the application for don't show anymore this error?

A: Something seems to be running on that port. It can be another instance of mailcatcher, or some other process.
On most *nix systems you can use the following command to search for a process occupying a particular port:
lsof -i :PORT

For example:
lsof -i :1025

The result will contain a PID (Process ID). You can use this to kill the offending process.
kill -9 SOME_PID

Example:
kill -9 32487

redpajama_set_name: RedPajamaStackExchange


text:
Q: A symplectic version of critical points According to the interesting comment of  Mohammad F Tehrani, I revise the  question as follows:
Assume $n>2$. For what type of compact n dimensional manifolds $M$ we can say:

For every smooth  embedding $f:M \to \mathbb{R}^{2n}$, there exist a point $p \in M$such  that  $Df_{p}(T_{p} M)$ is  a lagrangian subspace of $R^{2n}$?

Is there an example of  a  manifold with this property? For example: does $S^{3}$ satisfy this property?


text:
Q: What is the password after git push? after I typed git push I was asked to input password, which i did but it wasn't showing but still continued the i pressed enter but gave me invalid password. please is the password supposed to be our personal token access

A: I have trouble authenticate to GIT using the https protocol.
That's why i am using the SSH method which makes everything much easier.
type git remote -v
I bet you will use https.
anyway,
Configuring the git to use SSH :

*

*start the agent eval $(ssh-agent)

*Create a new ssh key ssh-keygen -t rsa -b 4096 -C "your-git-hub-mail@mail.com"
It will ask you to enter a passphrase. (you can press 'Enter' few times)

*copy the key cat ~/.ssh/id_rsa.pub

*Go to github, Click "Settings" => "SSH and GPG Keys" => "New Key"

*Give it a name and past you key.


text:
Q: Seeking Indian city points and village boundaries? I am looking for Indian city/village points and village/Taluk boundaries for India.
A perfect example what I am looking for is here for the State of Haryan, produce by
Haryana Space Applications Centre.
Till now I am little lost, can some body point me in right direction and share some sources from where I can get this data for commercial purpose.
Just for update for all who are following
I have found here that Survey of India has "Village Bdy.Database (#42)". This is exactly what i am looking but till today no response from them.
Any body have some idea how to purchase this layer from them.

A: For administrative boundaries, look at GADM database of Global Administrative Areas
Select India, and choose "level 3".
Edit: here's a screen grab of the resulting KML file, looks like it matches the link you provided, but GADM has it for the whole country.

A: You can go to the Census India web site which provides various admin boundary maps.
For some states it is down to the level of villages where as most states have it up to Taluka (Tehsil, subdistrict) level.


text:
Q: Why are not all library functions not system calls? So, from my basic OS class, I understood that kernel is the one who interacts with the hardware. So, if we want to interact with hardware, we need to call system calls. open() is a system call, while strlen() is not a system call. But any instruction or command has to interact with hardware, at least to increase program counter or modify the contents of memory. So, shouldn't all functions make a system call at some point ?

A: I would strongly suggest reading early papers on UNIX, the how and the why.  Ken Thompson was a strong advocate for the kernel consisting only of the things that could not be implemented outside of the kernel.
At that time; outside of the kernel corresponded to outside of the privileged mode of the computer.  This is a less interesting concept in modern systems; yet continues to drive architecture and design.
In short; open() is exported by the kernel because it has to be - it access data structures that are private to the kernel, thus is an interface;  strlen is not exported by the kernel because it doesn't have to be, it neither requires privilege nor access to other data structures.
Doesn't have to be is a trump card; because nobody wants needless functionality in the kernel.

A:
kernel is the one who interacts with the hardware.

That is a very inaccurate statement.
Even the following program, which may run on some microcontroller with no OS (and no optimizing compiler...), interacts with the hardware:
int array[8192];
void entry_point(void) {
    array[100] = 5+3;
}

That hardware in question being "CPU", "memory bus", and "memory".
While system calls are primarily used to access certain hardware (disk, network etc.), system calls are not defined as "calls to access hardware", but rather as just "calls to kernel APIs".
A kernel can export whatever API it wants, including strlen(), but for an OS designer, such as the aforementioned Ken Thompson, the APIs that the kernel should export are ones that facilitate the existence of multiple programs, processes, and/or users.
The main concern here is access to resources such as disk, network, timers, memory, etc., but also include e.g.:

*

*Scheduling / process management APIs (e.g. the fork(), exit(), nice(), and sched_yield() calls)

*Multiprocess management (e.g. sigaction(), kill(), wait(), futex() and semop())

*Performance & debugging (e.g. ptrace(), prlimit() and getrusage())

*Security (e.g. chmod(), chown(), setuid(), seccomp(), and chroot())

*Administration (e.g. init_module(), sethostname(), shutdown())


text:
Q: boost::bind does not compile I am new to boost spirit and I have the following problem:
#include <string>
#include <vector>
#include <boost/spirit/include/qi.hpp>

#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_statement.hpp>

#include <boost/bind.hpp>

using namespace boost::spirit;
using namespace std;

struct MyGrammar
    : qi::grammar<string::const_iterator, string(), ascii::space_type> {
    MyGrammar();

    void myFun(const string& s);

    private:
    qi::rule<string::const_iterator, string(), ascii::space_type> myRule;
};

using namespace boost::spirit;
using namespace std;

MyGrammar::MyGrammar() : MyGrammar::base_type(myRule) {
    using qi::_1;

    myRule = int_ [boost::bind(&MyGrammar::myFun, this, _1)]; // fails
    myRule = int_ [_val = _1];  // fine
}

void MyGrammar::myFun(const string& s){
    cout << "read: " << s << endl;
}

int
main(){
}

With the first assignment of myRule I get compile errors while the second assignment compiles fine.
In the first case the compiler outputs huge error messages that I don't understand.
At the end it says:
boost_1_49_0/include/boost/bind/bind.hpp:318:9: error: no match for call to '(const boost::_mfi::mf1<void, MyGrammar, const std::basic_string<char>&>) (MyGrammar* const&, const boost::phoenix::actor<boost::spirit::argument<0> >&)'
boost_1_49_0/include/boost/bind/mem_fn_template.hpp:163:7: note: candidates are: R boost::_mfi::mf1<R, T, A1>::operator()(T*, A1) const [with R = void, T = MyGrammar, A1 = const std::basic_string<char>&]
boost_1_49_0/include/boost/bind/mem_fn_template.hpp:184:7: note:                 R boost::_mfi::mf1<R, T, A1>::operator()(T&, A1) const [with R = void, T = MyGrammar, A1 = const std::basic_string<char>&]

Any ideas?
Thanks a lot for any help!

A: You can't use placeholders from different bind implementations. There are currently three bind functions in Boost:

*

*boost::bind, superseded by

*boost::lambda::bind, superseded by

*boost::phoenix::bind, which is what you should use for Boost.Spirit

The placeholders under boost::spirit::qi (and boost::spirit::karma) are the same as the ones used by boost::phoenix::bind, so just use that.
Oh, and pro tip: Stop your using namespace std; and preferrably any other using directive in global namespace.

A: The first problem is that you specifiy std::string as your synthesized attribute, but then define your rule in terms of qi::int_, which has a synthesized attribute of int.
The second problem is that, as the Spirit docs state directly, non-Phoenix functors take three arguments, not one:

You can use Boost.Bind to bind member functions. For function objects, the allowed signatures are:
void operator()(Attrib const&, unused_type, unused_type) const;
void operator()(Attrib const&, Context&, unused_type) const;
void operator()(Attrib const&, Context&, bool&) const;

The third problem is that you're using Spirit's Phoenix _1 placeholder rather than boost::bind's placeholder (which is effectively in the global namespace).
In summary, this should work:
#include <string>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_statement.hpp>

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;

struct MyGrammar :
    qi::grammar<std::string::const_iterator, int(), ascii::space_type>
{
    MyGrammar();
    void myFun(int i, qi::unused_type, qi::unused_type);

private:
    qi::rule<std::string::const_iterator, int(), ascii::space_type> myRule;
};

MyGrammar::MyGrammar() : MyGrammar::base_type(myRule)
{
    myRule = qi::int_[boost::bind(&MyGrammar::myFun, this, _1, _2, _3)];
}

void MyGrammar::myFun(int const i, qi::unused_type, qi::unused_type)
{
    std::cout << "read: " << i << '\n';
}

int main()
{
    std::string const input = "42";
    std::string::const_iterator first = input.begin(), last = input.end();
    qi::phrase_parse(first, last, MyGrammar(), ascii::space);
}

That being said, unless you have a very specific reason to use boost::bind here, you should be using boost::phoenix::bind instead:
#include <string>
#include <iostream>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_statement.hpp>
#include <boost/spirit/include/phoenix_bind.hpp>

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;

struct MyGrammar :
    qi::grammar<std::string::const_iterator, int(), ascii::space_type>
{
    MyGrammar();
    void myFun(int i);

private:
    qi::rule<std::string::const_iterator, int(), ascii::space_type> myRule;
};

MyGrammar::MyGrammar() : MyGrammar::base_type(myRule)
{
    myRule = qi::int_[boost::phoenix::bind(&MyGrammar::myFun, this, qi::_1)];
}

void MyGrammar::myFun(int const i)
{
    std::cout << "read: " << i << '\n';
}

int main()
{
    std::string const input = "42";
    std::string::const_iterator first = input.begin(), last = input.end();
    qi::phrase_parse(first, last, MyGrammar(), ascii::space);
}

This allows your bound member function to take only a single argument – the synthesized attribute – as you originally wanted.


text:
Q: VS2010 RC: Find In Files error: No files were found to look in I hit control + Scroll lock, control + break, and control + every other key on the keyboard.
I have a feeling I am going to see this error in Visual Studio 2050.
Does anyone know how to resolve it when it occurs?

A: I thought it was an occurence of an anoying erroring that I have been experiencing in VS for a decade. This time, it was user error. The vaue I had typed bad value for "Look In" should have been "Entire Solution"
http://vidmar.net/weblog/archive/2007/04/17/Strangest-error-No-files-were-found-to-look-in.-Find.aspx
My apologies


text:
Q: Expected value and the standard simple regression model Given the standard simple regression model:
$y_i = β_0 + β_1 x_i + u_i$
What is the expected value of the estimator $\hat\beta_1$in terms of $x_i, \beta_0$ and $\beta_1$ when $\hat\beta_1=\sum x_i y_i/\sum x_i^2$?

A: \begin{align}
\text{E} \left ( \frac{\sum_{i=1}^{n} x_i Y_i}{\sum_{j=1}^{n} x_j^2} \right ) &= \left ( \sum_{j=1}^{n} x_j^2 \right )^{-1} \sum_{i=1}^{n} x_i \text{E}(Y_i) \\
&= \left ( \sum_{j=1}^{n} x_j^2 \right )^{-1} \sum_{i=1}^{n} x_i (\beta_0 + \beta_1 x_i) \\
&= \beta_0 n\bar{x} \left ( \sum_{j=1}^{n} x_j^2 \right )^{-1} + \beta_1 .
\end{align}

A: Denote $x=(x_1,\dots,x_n)$. Assuming that $\mathbb{E}[u_i|x]=0$
$$\mathbb{E}[\hat\beta_1|x]=\mathbb{E}\left[\frac{\sum x_i y_i}{\sum x_i^2}\mid x\right]=\mathbb{E}\left[\frac{\sum x_i (\beta_0 + \beta_1 x_i + u_i)}{\sum x_i^2}\mid x\right]=\frac{\beta_0\sum x_i+\beta_1\sum x_i^2+\sum x_i\mathbb{E}[u_i|x]}{\sum x_i^2}=\beta_1+\beta_0\frac{\sum x_i}{\sum x_i^2}$$
and
$$\mathbb{E}[\hat\beta_1]=\beta_1+\beta_0\mathbb{E}\left[\frac{\sum x_i}{\sum x_i^2}\right]$$


text:
Q: Comparing two csv files using comm I am working on a script that verifies differences between two csv files (file_1.csv and file_2.csv).
file_1.csv = tasks to be processed
file_2.csv = tasks already processed

*

*If there is no difference, nothing should be done.

*If there is a difference, file_1.csv should replace file_2.csv, and file_1.csv sent by email. Finally, file_1.csv is deleted.

For that, I wrote the following but it seems it doesn't work.
Apparently the first "comm" command works but it is stuck at this stage.

if comm -3 file_1.csv file_2.csv;
then
mv file_1.csv file_2.csv
mutt -s "subject" -a file_1.csv -- somebody@domain.com < body_email.txt
rm file_1.csv

else
exit

fi

The output of "if comm -3" is displayed in the prompt but I don't get the prompt back.
Can anyone please advise me what's wrong ?
Thanks !

A: You might want to sort the files before comparing, try:
comm -23 <(sort -u file_1) <(sort -u file_2)
this would give you all tasks that have not been processed
For example, try the below code snippet:
diff=`comm -23 <(sort -u file_1) <(sort -u file_2)`
if [ $diff > 0 ]
then
    cp file_1 file_2
    mutt -s "subject" -a file_1.csv -- somebody@domain.com < body_email.txt
    rm file_1.csv
fi


text:
Q: Update a column in table with the calculations mede with other column in same table I have a situation where I need to update a row in a temp table with calculations made over some other columns data from same table.
I was able to do this for division and sum but not the complicated one like below
What I should do is
 UPDATE t
 SET    t.Value_Numeric = ((t.row9-((1-t.row28)*t.row26))/((1-t.row91))/(t.row33)-t.row85)
 FROM   #tempTable t
 where t.order = 93

 ** t.row9 means t.Value_Numeric  where t.order = 9

I was able to do a division like this
UPDATE #tempTable
 SET    #tempTable.Value_Numeric = reim.cmi
 FROM   #tempTable t
        INNER JOIN ( SELECT t1.Value_Numeric AS IPAllw ,
                            t2.Value_Numeric AS IPElig ,
                            t1.Value_Numeric / NULLIF(t2.Value_Numeric,0) AS cmi ,
                            t1.WorkingID
                     FROM   #tempTable t1
                            JOIN #tempTable t2 ON t1.WorkingID = t2.WorkingID
                                                  AND t1.order = 78
                                                  AND t2.order = 74
                     GROUP BY t1.WorkingID ,
                            t1.Value_Numeric ,
                            t2.Value_Numeric
                   ) reim ON reim.WorkingID = t.WorkingID
 WHERE  t.order = 79

help me to figure out the query to update the complex calculation.
Thanks

A: I assume Oracle in my answer based on the plsql tag given to the question.
One possible solution would be to create a helper function as follows:
create or replace function get_temptable_value(p_row in number) return temptable.value_numeric%type
is
  pragma AUTONOMOUS_TRANSACTION;
  v_val  temptable.value_numeric%type;
begin
  begin
    select value_numeric
    into v_val
    from temptable
    where row_order = p_row;
  exception
    when no_data_found then
      v_val := null;
  end;

  return v_val;
end;

The function returns null if the given row is not found, but it might be better to return 0 depending on your requirements. The autonomous pragma enables it to be called from an update statement (otherwise ORA-04091 is given):
update temptable t
SET    t.Value_Numeric = ((get_temptable_value(9)-((1-get_temptable_value(28))* get_temptable_value(26)))/((1- get_temptable_value(91)))/( get_temptable_value(33))- get_temptable_value(85))
where t.row_order = 93;

2. Another solution would be the use of model cluase:
create or replace view temptable_upd
as
select *
from temptable t
model dimension by (row_order)
      measures (value_numeric, value_numeric as new_value_numeric)
      rules (new_value_numeric[93] = ((value_numeric[9]-((1-value_numeric[28])* value_numeric[26]))/((1- value_numeric[91]))/( value_numeric[33])- value_numeric[85])
            );

In the rules section you can define any inter-row calculation.
Using the view, you can update the table:
update temptable t
set t.value_numeric = (select new_value_numeric from temptable_upd tupd where tupd.row_order = t.row_order)
where t.row_order = 93;

A:
Create or replace procedure abc
  Is
  V_count number;
  Begin
  Select ur_calculations o/p into v_count from table ;Update
  Ur_table set col1 = v_count
  Where col2 =value;

Commit;End;


text:
Q: I Don't Get ORM In MVC I'm creating authorization system on Kohana 3.1. It's for educational reasons.
Right now I try to learn ORM. I understand what I can do with ORM, but I don't get how can I implement it in MVC structure... Right now all works, but it seems terribly wrong!
Here is my controller's action:
public function action_signUp() {

  if ( !$this->request->post() ) {

    $view = new View_SignUp;

    $view->title = 'Sign Up';

    $this->response->body( $view->render() );

  } else {

    $validation =
      Validation::factory( $this->request->post() )
        ->rule( 'token', 'not_empty' )
        ->rule( 'token', 'Security::check' )
        ->rule( 'username', 'not_empty' )
        ->rule( 'username', 'max_length', array( ':value', 32 ) )
        ->rule( 'username', 'alpha_dash', array( ':value', true ) ) // Alpha chars (from UTF-8), numbers, underscores and dashes...
        ->rule( 'password', 'not_empty' )
        ->rule( 'password', 'min_length', array( ':value', 6 ) )
        ->rule( 'password', 'max_length', array( ':value', 255 ) )
        ->rule( 'passwordRepeatedly', 'not_empty' )
        ->rule( 'passwordRepeatedly', 'matches', array( ':validation', 'passwordRepeatedly', 'password' ) )
        ->rule( 'email', 'not_empty' )
        ->rule( 'email', 'email' );

    if ( $validation->check() ) {

      $user = ORM::factory( 'User' );

      $user->username = $this->request->post( 'username' );
      $user->password = sha1( $this->request->post( 'password' ) ); // To add salt or something...
      $user->email = $this->request->post( 'email' );

      $user->save();

      $this->request->redirect( 'sign-in' );

    } else {

      $view = new View_SignUp;

      $view->title = 'Sign Up';

      $view->haveErrors = true;

      forEach ( $validation->errors( 'errorMessages' ) as $error ) {

        $view->errors[] = array( 'error' => $error );

      }

      $this->response->body( $view->render() );

    }

  }

}

And here is my ORM model...
class Model_User extends ORM {

  //

}

It is really awful, huh? I know that controllers must be tiny, buy models can be as fat as they want... but. Help me, or, better, show me an example!

A: Model-level validation should be in your models, not controllers. And your view-related stuff should be isolated in your view model, still not controller :)
So your action should look something like:
public function action_signup()
{
    $errors = array();
    $user = new Model_User;

    if ($post = $this->request->post())
    {
        try
        {
            $user->values($post)
                ->create();

            $this->request->redirect('somewhere_over_the_rainbow');
        }
        catch (ORM_Validation_Exception $e)
        {
            $errors += $e->errors();
        }
    }

    $this->view->errors = $errors;
    $this->view->user = $user;
}


text:
Q: how to make sync automatically directory on centos linux I created directory in:
/home/a & /home/b
I would like to sync between folder a & b. Assume when I create directory or file in /home/a of cource in /home/b will be created automatically, and also when I delete /home/b/* in /home/a/* will be deleted.
I did this:
# cd /home
# mkdir a && mkdir b
# rsync -r a b && rsync -r b a
but not working.
I will appreciate who can help. Big Thanks


text:
Q: Java keyListener with multiple JPanel I'm having a problem with Java KeyListener when adding adding another JPanel with 5 JLabels, I've searched around this website, and most solutions to this problem involve switching from KeyListener to KeyBindings. This wont work for me because I need to know exactly when a key is pressed, released and held down. To my knowledge, KeyBindings does not provide all those.
I've tried to use
this.requestFocus();

after creating the new JPanel, but it didn't work, however when I use the same line inside the paintComponent(), it works. Which brings me to my questions: How does this reflect on performance? My paintComponent() is called about 60 times/sec. Is  there a way to call it once and still have this working? I see that requestDefaultFocus() from the type JComponent is deprecated...
I've also tried adding same KeyListener to the second JPanel, but that didn't help. Im guessing one of the JLabels is the one that gets focus?

A:
This wont work for me because I need to know exactly when a key is pressed, released and held down. To my knowledge, KeyBindings does not provide all those.

Yes it does. You have an Action for "pressed" and "released". There is no such Action as "held down" (even for a KeyListener), you just get multiple events generated.
this.requestFocus();

That is not the proper method to use for requestion focus on a component. Read the API for that method and it will tell you the proper method to use.

however when I use the same line inside the paintComponent(), it works.

This is because you can't request focus on a component until the frame has been realized, which means you've invoked pack() or setVisible() on the frame.

Is there a way to call it once and still have this working?

See the RequestFocusListener class in Dialog Focus.
The proper solution is to use Key Bindings so you don't need to use these work arounds.


text:
Q: Radio Mobile on Ubuntu Does anyone have experience setting up Radio Mobile, on Wine, in Ubuntu? There is such little data online, I am really hoping some could help me with the installation on Wine.
I tried to use the Radio Mobile installer but I get the following error:
root@x-K56CB:/home/x# wine Downloads/Radio_Mobile_Setup.exe
err:module:import_dll Library MSVBVM60.DLL (which is needed by L"C:\\Radio Mobile\\rmweng.exe") not found
err:module:LdrInitializeThunk Main exe initialization for L"C:\\Radio Mobile\\rmweng.exe" failed, status c0000135

The solution is to install VB6run, which I did using winetricks, but I still keep getting the same error... is it perhaps because I am installing it in a directory outside of  .wine?
thanks


text:
Q: Best way to get push notifications to server from MS SQL Server I partially found a solution to my question, but I'm not really satisfied with the result.
My application consists of ASP.NET MVC + MS SQL Server.
The case is as follows:

*

*An external application saves data periodically to the SQL Database. In one tenth of a second, 20 to 100 records can be saved.

*SQL should be polled from the back-end, or there should be push notifications after each save, in order to update (for example) a running total of saved items.

*The back-end will push notifications to the UI (this will be done using SignalR)

I followed this tutorial http://venkatbaggu.com/signalr-database-update-notifications-asp-net-mvc-usiing-sql-dependency/ to set it up.
SqlDependency with broker service is used to get push notifications from SQL firing the OnChange Event. The problem is that this solution is very slow. There is only one record saved every second for a small database, and the events fire with pretty big delays.
Is there another technology to get data changes from SQL? Or maybe the solution I'm using requires some kind of optimization?

A: Have a look at http://sqltabledependency.somee.com/. You can receive notification from SQL Server containing info about the inserted deleted or updated records.

A: You're trying to fix a conceptual problem with a technological one, in that you need to know when the database has been written to in order to update your program, and you're depending on this SqlDependency to achieve that.  Don't get me wrong, SqlDependency is an excellent fit in some circumstances no doubt, but almost certainly in no such circumstance would it work well when mass inserts are being performed on the server.
Either the library has a feature that disables triggering the event after the first (or even better, after the last with some small delay), or you're going to have a solution that doesn't scale well.
I offer an alternative solution:  When your backend task begins writing, when it finishes writing, and for every second while writing, it updates a record indicating that the database has been written to by that task.
Your application polls the database for that value every so often (say every 5 seconds), and if it has the indicator that it has been written to, you perform an update and you reset the flag.  The next check performed happens only one second after the last in this case, and so in the case of database changes, it will update more frequently.
If you need to be more accurate with your checks, you may check more frequently as desired.  What is important is that your program only performs checks and updates only as fast as you need, and not for every single record added.  This means that when 100 records are added, you're not having to update your program data 100 times. If it indeed takes 0.1 seconds per 20-100 records, then you'll likely be updating 100 records at most 5 times.


text:
Q: What is the purpose of the cursed art gallery? Spoilers!! Be warned
I've ended the game Ib and got all the endings, but seems that the game doesn't clarify some things within the story. The main question that I had was, what is the purpose of Guerterna's cursed art gallery? And, why was Ib called to come to this place?
I thought it could be Mary's doing, as like her diary said, she wanted to go outside and had a real life, but needed to take the place of another person. But, in A Painting's Demise ending, we learnt that even Mary isn't allowed to leave. So, I'm out of options.
If someone could clarify, I'll be grateful
P.S. Also, why Ib was called a "thief" when she got her first key? As I read in vgperson's translation notes, the original word was "kaese" (give it back), but still it doesn't make much sense to me. Is it supposed to say to Ib to return the key? Or the rose? Or what would be?


text:
Q: Laminas-mail. send as UFT8 I work with Laminas (former Zendframework 3). I want to send a mail with Laminas-Mail. I dont know how to change the Content-Type. Currently it is Content-Type: text/html but I want to send UTF8 mails, so therefore I want to use Content-Type: text/html; charset=utf-8.
I tried to change $html->type but I failed.
use Laminas\Mail;
use Laminas\Mail\Transport\Smtp as SmtpTransport;
use Laminas\Mail\Transport\SmtpOptions;
use Laminas\Mime\Message as MimeMessage;
use Laminas\Mime\Part as MimePart;

# ...
# much code
# ...

// Produce HTML
$bodyHtml = $this->viewRenderer->render('mymodule/email/email1');
$html = new MimePart($bodyHtml);
$html->type = "text/html; charset=utf-8"; #Seems not to work
$body = new MimeMessage();
$body->addPart($html);
$mail = new Mail\Message();
$mail->setEncoding('UTF-8');
$mail->setBody($body);
$mail->setFrom('bobafit@example.com','Boba Fit');
$mail->addTo('bobafit@example.com','Boba Fit');
$mail->setSubject('Thank you for reading my Question');
// Setup SMTP transport
$transport = new SmtpTransport();
$options   = new SmtpOptions($this->config['smtp']);
$transport->setOptions($options);
$transport->send($mail);

A: Please check the official Dok:
https://docs.laminas.dev/laminas-mail/message/attachments/
Type and charset are defined separatly.
You are probably looking for something like that:
$html = new MimePart($htmlMarkup);
$html->type = Mime::TYPE_HTML;
$html->charset = 'utf-8';


text:
Q: Display a message on weekends only (PHP) (Wordpress) I can't seem to find the answer to this.
Basically I want to echo a message on a Saturday and Sunday only.
But have no idea how to identify Saturday and Sunday with php.
EDIT: Found the simple answer using javascript:
<script>
var date = new Date();
switch(date.getDay()){
    case 0: document.write("sunday!"); break;
    case 6: document.write("saturday!"); break;
    default: document.write("any other week day");
}
</script>

Works brilliantly.

A: What you're looking for is the date() function in PHP to get the current day.
$currentDay = date('w'); // Get current weekday

That returns an integer from 0 - 6 where 0 is Sunday and 6 Saturday (Depending on your servers timezone).


text:
Q: Date object in a MongoDB collection In a collection in my MondoDB database i have a collection like follows:
{ "_id" : ObjectId("4d0d3945e69a56cf504375b7"), "action" : "Click", "dt" : "Sun Dec 19 2010 03:44:21 GMT+0000 (UTC)"}

dt is a Date object. If i do db.mycollection.find({action:"Click"})the record comes up. But db.mycollection.find({dt:'Sun Dec 19 2010 03:44:21 GMT+0000 (UTC)'})does not show any records, since i guess dt is a Date object.
How to query by dt in the above case ?
Please Help
Thank You

A: db.mycollection.find({dt:ISODate('Sun Dec 19 2010 03:44:21 GMT+0000 (UTC)')})


text:
Q: Price indexing timeseries data I'm new to the R coding community and as I am learning I ran into an issue I haven't been able to crack. I'm sure this is a walk in the park for most of you so I hope someone could find the time to help me out.
I have a set of currency pairs downloaded from FRED using the R getSymbols function. Then I combined three of these pairs into one dataframe ("data")
What I would like to do is create an index of these three variables in order to be able to directly compare their performance over the period of time. For example, this is my original dataset;
               EXJPUS    EXCHUS  EXCAUS
1981-01-01     202.3667  1.5518  1.1909

1981-02-01     205.7167  1.6131  1.1984

1981-03-01     208.7918  1.6314  1.1914

From this original dataset, I'd like to create a dataset that contains the values of (current value/first value)*100 = index value for example with EXJPUS: (208.7918/202.3667)*100 = 103.175
If I could implement this calculation for all three variables, I'm hoping to get a result table that looks something like this;
               EXJPUS    EXCHUS  EXCAUS
1981-01-01     100.000   100.000 100.000

1981-02-01     101.655   103.950 100.630

1981-03-01     103.175   105.130 100.042

If there is only one variable, I'm able to use the as.numeric function to extract the first value and then divide all other values by the value given from the as.numeric function. However, with multiple variables this doesn't seem work.
Can someone please give me some guidance or a suggestion on this problem?
Thank you!

A: There are many ways to perform your task, one is to use the apply function:
apply(data, 2, function(x) x / x[1] * 100)
            EXJOUS   EXCHUS   EXCAUS
1981-01-01 100.0000 100.0000 100.0000
1981-02-01 101.6554 103.9503 100.6298
1981-03-01 103.1750 105.1295 100.0420

We could also use the dplyr package, this approach allows you to retain the base value and the indexed value:
library(dplyr)
data %>% mutate_all(funs(pindex = . / .[1]))

    EXJOUS EXCHUS EXCAUS EXJOUS_pindex EXCHUS_pindex EXCAUS_pindex
1 202.3667 1.5518 1.1909      100.0000      100.0000      100.0000
2 205.7167 1.6131 1.1984      101.6554      103.9503      100.6298
3 208.7918 1.6314 1.1914      103.1750      105.1295      100.0420

A: Assuming that this is an xts or zoo object, the sweep operator can be used to divide all rows by the first row thusly (and then multiply by 100):
zoo.mat <-
structure(c(202.3667, 205.7167, 208.7918, 1.5518, 1.6131, 1.6314,
1.1909, 1.1984, 1.1914), .Dim = c(3L, 3L), .Dimnames = list(c("1981-01-01",
"1981-02-01", "1981-03-01"), c("EXJPUS", "EXCHUS", "EXCAUS")), index = 1:3, class = "zoo")

 100*sweep(zoo.mat, 2,  zoo.mat[1,] , "/")

    EXJPUS   EXCHUS   EXCAUS
1 100.0000 100.0000 100.0000
2 101.6554 103.9503 100.6298
3 103.1750 105.1295 100.0420

I think the apply solution requires less fiddling if you want the row indices. After further exploration the sweep and the apply methods seem to do equally well with a proper zoo object:
library(zoo)
zoo.mat <- zoo(cbind(EXJPUS = c(202.3667, 205.7167, 208.7918), EXCHUS = c(1.5518, 1.6131, 1.6314), EXCAUS = c(1.5518, 1.6131, 1.6314)), as.Date(c("1981-01-01", "1981-02-01", "1981-03-01")))
100*sweep(zoo.mat, 2,  zoo.mat[1,] , "/")
#-----
             EXJPUS   EXCHUS   EXCAUS
1981-01-01 100.0000 100.0000 100.0000
1981-02-01 101.6554 103.9503 103.9503
1981-03-01 103.1750 105.1295 105.1295

A: EXJOUS <- c(202.3667, 205.7167, 208.7918)
EXCHUS <- c(1.5518,1.6131,1.6314)
EXCAUS <- c(1.1909,1.1984,1.1914)

z<-data.frame (EXJOUS, EXCHUS, EXCAUS)
rownames(z) <- c('1981-01-01', '1981-02-01', '1981-03-01')

x<-z[1,]/z[1,]*100
for (i in 2:nrow(z))
 {x<-rbind(x,
 z[i,]/z[1,]*100)
 }
x


text:
Q: Giving window.open popup a title I'm trying to give the popup window in window.open a title. However i'm failing to do so. Any help or suggestions please?
function view() {
    window.open(url,"_self");
}

A: You can change the title after opening the window.
var myWindow = window.open("", "", "width=200, height=100");
myWindow.document.writeln('<html><head><title>Your new title here</title></head>');


text:
Q: Is there an XML schema for description net flow data? I am working on a program that imports and exports net flow data. Because of our general architecture, it would make sense to describe this information in XML. Does there exist an XML for describing net flow data?
A good description of NetFlow data can be found in this Usenix paper http://www.usenix.org/events/lisa00/full_papers/navarro/navarro_html/
According to the paper, an SQL schema for describing net flow data is:
create table netflows (
   router_id  char(1)            not null,
   src_ipn    bigint    unsigned not null,
   dst_ipn    bigint    unsigned not null,
   nxt_ipn    bigint    unsigned not null,
   ifin       smallint  unsigned not null,
   ifout      smallint  unsigned not null,
   packets    integer   unsigned not null,
   octets     integer   unsigned not null,
   starttime  timestamp          not null,
   endtime    timestamp          not null,
   srcport    smallint  unsigned not null,
   dstport    smallint  unsigned not null,
   tcp        tinyint   unsigned not null,
   prot       tinyint   unsigned not null,
   tos        tinyint   unsigned not null,
   srcas      smallint  unsigned not null,
   dstas      smallint  unsigned not null,
   srcmask    tinyint   unsigned not null,
   dstmask    tinyint   unsigned not null
)

It's pretty easy to turn this into an XML schema. My interest is in knowing if someone has already done this, as I would rather not create a new, incompatible schema.
Thanks.

A: I was looking for the same thing and I ended up using the Parse CVS Perl plugin which is included in the NFDump package if I remember well. This particular script converts the NetFlow cvs output into a readable format but if you make some modify it can create an XML as well (you can do it with very few line of codes). I suggest you that because it already offers some kind of official name for each field. However it does not describe the type of those fields nor the actual XML structure.

A: No, there is no standard schema. However, we have created one and put it in the open source tcpflow program. When tcpflow runs it can create an XML file that has all of the netflow data. However, it also decodes embedded objects, such as data sent by HTTP, reports each of those, decompresses what was compressed, and even calculates the MD5 of everything. All in one easy-to-use command-line program.


text:
Q: ¿Cómo graficar en una interfaz gráfica usando MatplotLib los valores recibidos de un sensor? Estoy desarrollando una interfaz gráfica que te pida el nombre del archivo nuevo que se va a generar de tipo txt y que te pregunte el puerto serial en el que se encuentra tu Arduino, al iniciar el programa python se conecta a Arduino con el puerto específico y recibe 25 datos del sensor(use un potenciometro para realizar las pruebas) y estos datos recibidos se escriben en el archivo de texto, además de esto para mostrar en la interfaz gráfica los resultados los pondría en una gráfica. Los problemas que he encontrado para cumplir mi objetivo son los siguientes
ACTUALIZACIÓN
(Solucionado) Lee los datos como bytes así que cuando los guarda en el archivo de texto los almacena de este modo
b'NUMERO\r\n'

y esto ocasiona que cuando quiera usar replace('b\r\n','') me de un
TypeError: a bytes-like object is required, not 'str'

al usar lectura_str=lectura.decode("utf8")al guardar ese valor en la variable texto ya no eran bytes

(Al parecer son son dos sucesos correlacionados)
Esto a su vez ocasiona que cuando grafica los datos no se pongan en orden ascendente sino por aparición(me imagino que es porque tengo que definir cómo se debería de comportar Y <de manera ascendente de 0 a 1024> y es por eso que se ponen así)

De momento no se como plasmar esta gráfica que se genera en la interfaz cuando termina pero si no soluciono esto primero no servirá de nada.(solucionado)
Dejo la parte donde intento remplazar comentada para que sepan en que parte la puse, aquí mi código de python
import matplotlib.pyplot as plt

from tkinter import*
import serial, time
def crearTEXTO(lectura):
    texto=''
    for i in range(len(lectura)):
        lectura_str=lectura[i].decode("utf8")
        texto += str(lectura_str)
    return texto

def graficar(lectura):
    y=[]
    for i in range(len(lectura)):
        y.append(lectura[i])
    return y

def ENVIAR():
    NAME=str(NOMBRE.get())
    PORT=str(PUERTO.get())
    PORT=str(PUERTO.get())
    try:
        arduino = serial.Serial(PORT,9600)
        time.sleep(4)#Estabilizar la conección
        for i in range(25):
            arduino.write(b'1')#Aquí se envían bits
        lectura=[]

        for i in range(25):
            lectura.append(arduino.readline())
        arduino.close()

        # for i in range(len(lectura)):
        #     lectura[i][len(lectura[i])-1] = lectura[i][len(lectura[i])-1].replace('b\r\n','')
    except:
        messagebox.showinfo(message="Por favor verifica que el Puerto que pusiste sea el correcto", title="ERROR")

    archivo = open(NAME+".txt","w") #Abrimos el archivo en modalidad escritura "write"
    text=crearTEXTO(lectura)

    archivo.write(text)
    archivo.close()
    print(text)
    y=graficar(lectura)
    plt.plot(y)

    # plt.show

POTENCIOMETRO = Tk()
marco = Frame(POTENCIOMETRO)

#Objetos a utilizar
ASKNAME = Label(marco,text= "Bienvenido, ¿Qué nombre tendrá este archivo nuevo?")
NOMBRE = Entry(marco)
ASKPORT = Label(marco,text= "¿En qué puerto está conectado tu ARDUINO UNO?")
PUERTO = Entry(marco)
ENVIAR= Button(marco, text = "ENVIAR", command = ENVIAR)

#Contenido
ASKNAME.pack()
NOMBRE.pack()
ASKPORT.pack()
PUERTO.pack()
ENVIAR.pack()
marco.pack(padx = 200, pady=150)#Tamaño márco
POTENCIOMETRO.mainloop()

Y aquí está mi código de Arduino, el que estoy usando es Arduino Uno y así está conectado todo

int s = 0;
void setup() {
  Serial.begin(9600);
  pinMode(A2, INPUT);

}

void loop() {
  if (Serial.read() == '1') {
    delay(1000);
    for (int i = 0; i < 25; i++) {
      s = analogRead(A2);
      delay(500);
      Serial.println(s);

    }
  }
}

como habrán visto puse  un print(text) para visualizar desde la consola de python sin abrir el archivo.txt lo que se guardaba, aquí les dejo que es lo que se imprimía
b'1016\r\n' b'1019\r\n' b'1016\r\n' b'1018\r\n' b'1016\r\n' b'1017\r\n' b'1019\r\n' b'1018\r\n' b'1016\r\n' b'1018\r\n' b'1018\r\n' b'965\r\n' b'1016\r\n' b'1002\r\n' b'1018\r\n' b'781\r\n' b'1019\r\n' b'1018\r\n' b'1019\r\n' b'1019\r\n' b'1019\r\n' b'1019\r\n' b'811\r\n' b'418\r\n' b'369\r\n'

(y lo que se imprime ahora)
195
217
242
275
359
424
459
383
428
575
763
1018
884
559
488
418
350
333
283
340
413
462
685
839
518

el programa esta hecho para que de igual forma la gráfica se muestre en la consola de python hasta que se cierra el programa (pero desearía que aparezca la gráfica en la misma interfaz)

A: Lo que recibes desde Arduino son bytes.
A diferencia de C, en Python las secuencias de bytes y strings son dos tipos diferentes de datos. Para transformar el primero en el segundo, usa decode:
valor = b'NUMERO\r\n'
valor_str = valor.decode("utf8")
print(valor, type(valor))
print(valor_str, type(valor_str))
valor_str = valor_str.strip()
print("Valor simplificado: >%s<" % valor_str)

Nota: el valor original no contiene una "b" al principio. Eso lo agrega Python al desplegarlo para señalar que el tipo de la variable es bytes, no str. Por tanto, sólo queda eliminar los espacios en blanco (whitespace) alrededor usando strip(), que es más general que simplemente replace("\r\n","").
Produce:
b'NUMERO\r\n' <class 'bytes'>
NUMERO
 <class 'str'>
Valor simplificado: >NUMERO<

Nota: Existe microPython para ESP8266 y ESP32. He estado trabajando con ESP32 + microPython ultimamente y es una maravilla, 100 veces más poderoso y fácil. Te recomiendo el upgrade.

A: Sobre la integración con Arduino, te recomiendo que le des un vistazo a la libreria pyFirmata. Instalar Firmata en Arduino y no tienes que hacer nada más por ese lado. El control de este módulo se hará desde Python y tendrás todo el código uniforme en un solo script.
Por otro lado, para esta aplicación lo conveniente es utilizar un deque (cola), que es una especie de lista especial que tiene un tamaño fijo y que cuando se alimenta un valor con append este se inserta al final de la cola y hace que el primer valor salga de la cola. De esta manera siempre tienes una estructura con la misma cantidad de valores y hará que tu gráfico en matplotlib muestre la variación. Esto esta disponible en from collections import deque.
Luego, si quieres insertar un gráfico de matplotlib en tkinter lo pueds hacer con un widget especial de figura, FigureCanvasTkAgg.
Te dejo un programa que hace algo parecido a lo que estas haciendo, solo que lee valores del estado de la PC con la librería psutil (lee el uso del CPU). Adaptarlo a los valores leídos por el puerto serial es sencillo. Estos valores se utilizan para actualizar la cola de valores y se actualiza constantemente la gráfica (cada segundo) por medio del método after sobre la ventana principal y eliminando el axes gráfico (ax.cla()).
import psutil
import tkinter as tk
import tkinter.ttk as ttk
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from collections import deque

class App:
    def __init__(self, master):
        self.master = master
        self.master.title("CPU Data Dashboard")
        self.master.resizable(0, 0)
        self.master.config(background='black')

        self.var_usage_CPU = tk.DoubleVar()
        self.var_usage_MEM = tk.DoubleVar()
        self.var_battery_percent = tk.IntVar(value=50)

        self.plot_line = deque(maxlen=10)

        frm = tk.Frame(background='black')
        frm.pack(padx=10, pady=10)

        self.lblCPU_Usage = tk.Label(frm, text="", bg='black', fg='white')
        self.barCPU_Usage = ttk.Progressbar(frm, length=200, variable=self.var_usage_CPU)
        self.lblMEM_Usage = tk.Label(frm, text="", bg='black', fg='white')
        self.barMEM_Usage = ttk.Progressbar(frm, length=200, variable=self.var_usage_MEM,
                                            maximum=psutil.virtual_memory().total)
        self.lblBAT_Usage = tk.Label(frm, text="", bg='black', fg='white')
        self.barBAT_Usage = ttk.Progressbar(frm, length=200, variable=self.var_battery_percent)

        self.lblCPU_Usage.grid(row=0, column=0, padx=5, pady=5, sticky=tk.W)
        self.barCPU_Usage.grid(row=1, column=0, padx=5, pady=5, sticky=tk.W)
        self.lblMEM_Usage.grid(row=2, column=0, padx=5, pady=5, sticky=tk.W)
        self.barMEM_Usage.grid(row=3, column=0, padx=5, pady=5, sticky=tk.W)
        self.lblBAT_Usage.grid(row=4, column=0, padx=5, pady=5, sticky=tk.W)
        self.barBAT_Usage.grid(row=5, column=0, padx=5, pady=5, sticky=tk.W)

        self.fig, self.ax = plt.subplots(figsize=(3, 2))
        self.fig.set_facecolor('black')

        self.graph = FigureCanvasTkAgg(self.fig, master=frm)
        self.graph.get_tk_widget().grid(row=6, column=0, padx=5, pady=5)
        self.ax.set_title("CPU Usage Percent")
        self.ax.set_ylabel("%")
        self.ax.set_yticklabels(self.ax.get_yticks(), fontsize=8)
        self.ax.set_xticks([])
        self.ax.set_xlim(0, 100)

        self.read_psutil_data()

    def read_psutil_data(self):
        self.var_usage_CPU.set(psutil.cpu_percent())
        self.var_usage_MEM.set(psutil.virtual_memory().used)
        self.var_battery_percent.set(psutil.sensors_battery().percent)
        self.update_dashboard_data()

    def update_dashboard_data(self):
        self.lblCPU_Usage.config(text=f"CPU Usage: {self.var_usage_CPU.get()}%")
        self.lblMEM_Usage.config(text=f"Virtual Memory Usage: {self.var_usage_MEM.get()/1e6:,.1f} Mb")
        self.lblBAT_Usage.config(text=f"Battery Available: {self.var_battery_percent.get()}%")

        self.ax.cla()

        self.plot_line.append(self.var_usage_CPU.get())
        self.ax.plot(self.plot_line)
        self.ax.set_title("CPU Usage Percent", color='white')
        self.ax.set_yticklabels([0, 20, 40, 60, 80, 100], color='white')
        self.ax.set_xlim(0, 10)
        self.ax.set_ylim(0, 100)
        self.ax.set_xticks([])
        self.ax.grid(linestyle='--')
        self.ax.set_facecolor('black')

        self.graph.draw()

        self.master.after(1000, self.read_psutil_data)

root = tk.Tk()
app = App(root)
root.mainloop()


text:
Q: iPhone/iPad simulator not lauching in Titanium studio 2.1.2 I have following s/w configuration-
Mac- 10.6.8 with 2 GB ram installed over VMWare.
xcode- 4.2
Titanium studio- 2.1.2
Titanium sdk version - 3.0.0 GA and 2.1.2GA.
My problem is that when create a project with either 3.0.0 GA or 2.1.2GA, for android everything is fine. But iPhone or iPad simulator not lauching, if same code open in xcode and run then it working. We get following log info when run project for iPhone -
[INFO] One moment, building ...
[INFO] Titanium SDK version: 2.1.2 (08/24/12 14:46 ed7f777)
[INFO] iPhone Device family: universal
[INFO] iPhone SDK version: 5.0
[INFO] iPhone simulated device: iphone
[INFO] Minimum iOS version: 4.0
[INFO] Compiling localization files

After that nothing happened.
Please give me solution.
Thank you....


text:
Q: jose4j JWT's claims set's attribute type other than string object I have been using jose4j version 0.6.0 for Json Web Token(JWT) generation. All is good up-till token generation,  token verification . JWT's claims payload can have number of elements like version, tokenId, issuer,permissions etc. I'm passing TokenPermissions object which is standard object in oneM2M release 2  specification i.e.
JwtClaims claims = new JwtClaims();
claims.setIssuer("DAS@ServiceProvider");
claims.setAudience("CSE001"); //
.....
.........
TokenPermissions tokenPerms = new TokenPermissions();
TokenPermission tokenPerm = new TokenPermission();
tokenPerm.getResourceIDs().add("RXYZ");
tokenPerm.setPrivileges(setOfAcr);// setOfACr is another object on oneM2M
tokenPerms.getPermission().add(tokenPerm);
claims.setClaim("permissions",tokenPerms);

Above snippet of code generates following JWT Claim Set
{iss=DAS@ServiceProvider, aud=CSE001, exp=1508999613, jti=H1wm_yaOe61Co-wND7wBAw@DAS@CDOT-SP, iat=1508996013, nbf=1508995953, sub=subject, email=mail@example.com, groups=[group-one, other-group, group-three], version=1.0.0, permissions=cdot.onem2m.resource.xsd.TokenPermissions@7f3b97fd}
Whole to the token passes the signature and claims validation but when is I try of typecast permission attribute to TokenPermissions it through error.
tokenPermsObject =     jwtClaims.getClaimValue("permissions",TokenPermissions.class);

It through below error :
org.jose4j.jwt.MalformedClaimException: The value of the 'permissions' claim is not the expected type (xyz.xsd.TokenPermissions@7f3b97fd - Cannot cast java.lang.String to xyz.xsd.TokenPermissions.TokenPermissions)
What type of claims object could be passed in jose4j JWT, does I have to mandatorily pass text in claims set. Any help would be highly appreciated.

A: jose4j's JSON processing was derived from the JSON.simple toolkit and is fairly basic in how it converts between JSON and Java objects. It will do strings, numbers, booleans, maps and lists.
If you want/need to use a more sophisticated JSON library you can use setPayload(...) on JsonWebSignature when creating the JWT and give it the the JSON string you've produced elsewhere. And when consuming a JWT, String getRawJson() on JwtClaims will give you the JSON string payload that you can hand off to some other lib.


text:
Q: How to get response of accelerometer sensor in background in wear os? I am doing fall detection in wear-os having fossil watch and getting fall detection in foreground and also used intent service to get fall detection in background but my watch app gets background service only for 1.30 mins. how to get continuous background service for fall detection in wear-os ?
currently I am  using this link for background service
this below code for background service and called intent service in main activity
public class FallDetectService extends Intent Service implements SensorEventListener
{
    public static final boolean SERVERTRACE = false;

    protected static final String TAG = "BackgroundLocationService";
    private SensorManager sensorManager;
    private Sensor accelerometer;

    private Button button;
    final static long TIME = 15000;
    private FallDetectAlgo fallDetectAlgo;
    // private Handler h0;
    private boolean flag_fall = false;
    private boolean flag_buffer_ready = false;
    private ImageView image;
    private boolean f_send_msg = true;
    SharedPreferences sharedPreferences;
    String watch_id;
    SensorEvent event;
  // private Intent mIntentService;
    private PendingIntent mPendingIntent;

    IBinder mBinder = new FallDetectService.LocalBinder();

    public FallDetectService(){
        super("Fall Service");
    }
    public FallDetectService(String name) {
        super(name);
    }

    @SuppressLint("LongLogTag")
    @Override
    public void onCreate() {
        Log.i(TAG, "onCreate()");
        if (SERVERTRACE) enableStrictMode(); // for socket handling in main loop
        super.onCreate();

        sharedPreferences = getApplicationContext().getSharedPreferences("USER", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("isUserLogin", true);
        editor.commit();

        watch_id = sharedPreferences.getString("key_watch_id", "");
        // start sample and analyze
        fallDetectAlgo = new FallDetectAlgo();
        fallDetectAlgo.setDaemon(true);
        fallDetectAlgo.start();
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
            accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            sensorManager.registerListener((SensorEventListener) this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        } else {
            Toast.makeText(this, "No Accelerometer Found!!",
                    Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        fallDetectAlgo = new FallDetectAlgo();
        System.out.println("Service started");
        fallDetectAlgo.setDaemon(true);
        fallDetectAlgo.start();

        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
            accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            sensorManager.registerListener((SensorEventListener) this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        } else {
            Toast.makeText(this, "No Accelerometer Found!!",
                    Toast.LENGTH_LONG).show();
        }
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

     @Override
        protected void onHandleIntent(@Nullable Intent intent) {
            flag_buffer_ready = fallDetectAlgo.get_buffer_ready();
            if (flag_buffer_ready) {

            } else {

            }
            // store values in buffer and visualize fall
            System.out.println("FallEvent flag " + fallDetectAlgo.set_data(event));
            flag_fall = fallDetectAlgo.set_data(event); // event has values minus gravity
            if (flag_fall) {
                if (f_send_msg) {
                    f_send_msg = false;

                }
                System.out.println("Fall Event Fall detected success");
            } else {
                f_send_msg = true;
                fallEventOccured();
            }
        }

   public class LocalBinder extends Binder {
       public FallDetectService getServerInstance() {
           return FallDetectService.this;
       }
   }

    private void fallEventOccured() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, FALL_EVENT,
                new Response.Listener<String>() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onResponse(String response) {

                        Log.e("fallEventOccured response", "" + response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("save_heart_rate error", "" + error);
                        Toast.makeText(getApplicationContext(), "Please try latter", Toast.LENGTH_SHORT).show();
                    }

                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("watch_id", "" + watch_id);
                return params;
            }
        };

        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                0,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {

        // display if buffer is ready
        flag_buffer_ready = fallDetectAlgo.get_buffer_ready();
        if (flag_buffer_ready) {

        } else {

        }
        // store values in buffer and visualize fall
        System.out.println("FallEvent flag " + fallDetectAlgo.set_data(event));
        flag_fall = fallDetectAlgo.set_data(event); // event has values minus gravity
        if (flag_fall) {
            if (f_send_msg) {
                f_send_msg = false;

            }
            System.out.println("Fall Event Fall detected success");
            fallEventOccured();
        } else {
            f_send_msg = true;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    public void enableStrictMode() {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    @SuppressLint("LongLogTag")
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "Service Stoped");
    }

}

https://github.com/alessandror/AndroidFallDetectionApp


text:
Q: Regex / DOM Parsing to replace YouTube iframes with thumbnails while keeping the String I don't know if it's best to use a DOM parser or regex for this, but I want to replace all the YouTube iframes in my blogposts with the thumbnails. I've found methods of returning all the thumbs indeed, but not while still in the string. I want to keep the string as it is, but replace the Iframes with the thumbnails.
This code returns all YouTube videos:
$data = get_the_content();

// Find all unique YouTube videos
$re_youtube = '%youtube\.com/(?:v/|watch\?v=|embed/)(\w{10,12})\b%';
$count = preg_match_all($re_youtube, $data, $matches);

for ($i = 0; $i < $count; ++$i) {
$videos[$matches[1][$i]] = 'yt';
}

foreach ( $videos as $video => $v) {
    if ( $v == 'yt' ) {
    echo '

';
    }
}

I'm sure I could use preg_replace to achieve what I'm looking for? I'm super happy for any help!
I've been doing some dome parsing to clean up the paragraphs in my HTML. It looks like this:
// Set the right encoding of string
$content = mb_convert_encoding($content, 'html-entities', 'utf-8');

$DOM = new DOMDocument('1.0', 'UTF-8');
$DOM->substituteEntities = TRUE;
$DOM->loadHTML($content);
foreach($DOM->getElementsByTagName("iframe") as $iframe)
{
    foreach($p->attributes as $attr)

        $p->parentNode->removeChild($p);
}

$content = $DOM->saveHTML();

So now I kind of need some help to combine the two of them-ish.
(Here is an example to the page where this is going to work:
http://2famous.tv/2013/11/17/middle-eastern-artists-donate-more-than-1-1-million-of-art-to-help-syrian-refugee-children/)

A: I would use DOM and XPath for that:
$doc = new DOMDocument();
$doc->loadHTML($your_html_string);
$selector = new DOMXPath($doc);

// use the starts-with function to select iframes of interest
foreach($selector->query('//iframe[starts-with(@src, "//www.youtube.com")]')
    as $iframe
) {
    $iframe->parentNode->removeChild($iframe);
}
echo $doc->saveHTML();


text:
Q: How to stop scroll top on clicking next or prev btn of Carousel? Following is the simple carousel in use, even it looks fine here in coding, however on browser whenever tried to click next or prev button, page is  scrolled to top of HTML.

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

SAMPLE CONTENT HERE

SAMPLE CONTENT HERE

SAMPLE CONTENT HERE

SAMPLE CONTENT HERE

      Previous

      Next

Found the reason somewhere with data-target, however, unable to figure it out, and how to stop scrolling top...
Looking for simplest solution to understand, as new to HTML..
Thanks in advance
Cheers..

A: Just change href="#myCarousel" to data-target="#myCarousel" .

A: Tip #1:
You can add event.preventDefault() to prevent default behaviour with hashbang:
$('a[class^=carousel-control-]').click(function (event) {
    event.preventDefault();
});

Tip #2:
If you have plugins like SmoothScroll, you can unbind it by:
$('a[class^=carousel-control-]').unbind('click.SmoothScroll');

To look for all the click events bind to the element, use:
jQuery._data($('a[class^=carousel-control-]')[0], "events")


text:
Q: Django Validate an Email Foreign Key I have this profile resource:
class ProfileResource(resources.ModelResource):
    email = fields.Field(attribute='email',
        widget=CharWidget(),
        column_name='email')

    class Meta:
        model = Profile
        clean_model_instances = True
        import_id_fields = ('email',)

which validates the email when the profile is created. It works fine but when I use it as a foreign key like:
class InvestmentResource(resources.ModelResource):
    email = fields.Field(attribute='email',
        widget=ForeignKeyWidget(Profile, field='email'),
        column_name='email')

    class Meta:
        model = Investment
        clean_model_instances = True
        import_id_fields = ('id',)

    def before_import_row(self, row, row_number=None, **kwargs):
        self.email = row["email"]
        self.profile__firstname = row["firstname"]
        self.profile__lastname = row["lastname"]

    def after_import_instance(self, instance, new, row_number=None, **kwargs):
        """
        Create any missing Profile entries prior to importing rows.
        """
        try:
            profile, created = Profile.objects.get_or_create(email=self.email)

            profile.firstname = self.profile__firstname
            profile.lastname = self.profile__lastname
            profile.save()

            instance.profile = profile

        except Exception as e:
            print(e, file=sys.stderr)

It doesn't validate the email anymore. I tried adding two widgets, ForeignKeyWidget and CharWidget for the email on InvestmentResource, but it didn't work.
How do I then validate the email inside the InvestmentResource?

A: The issue is that your 'email' field is being treated as a lookup key and not an email address.  This can be resolved by customizing ForeignKeyWidget to add email validation.
What is happening is that you are importing an investment resource, which might be something like:
email,firstname,lastname
bob@example.com,bob,smith

You have configured InvestmentResource to use the email as a lookup key for Profile.  This means that django-import-export is not going to process it as an email address, but instead as lookup key for Profile, so in the code (ForeignKeyWidget) it will be doing something like:
Profile.objects.get(email='bob@example.com')

If this is successful, your Investment instance will now have the correct profile as a foreign key reference.
This will raise a DoesNotExist exception if the associated Profile is not present.  Therefore you can argue that an email address sent in the csv must be valid, because it if is not then no lookup will be possible.
However, if you want to check that an email is syntactically valid before you attempt to load the Profile, then this is easy to do, you need to override ForeignKeyWidget to perform validation first:
from django.core.exceptions import ValidationError
from django.core.validators import validate_email

class ValidatingForeignKeyWidget(widgets.ForeignKeyWidget):

    def clean(self, value, row=None, *args, **kwargs):

        try:
            validate_email(value)
        except ValidationError as e:
            # a quirk of import-export means that the ValidationError
            # should be re-raised
            raise ValueError(f"invalid email {e}")

        try:
            val = super().clean(value)
        except self.model.DoesNotExist:
            raise ValueError(f"{self.model.__name__} with value={value} does not exist")
        return val


text:
Q: Compare two datafarmes in two columns and get the difference Lets say i have a dataframe like this one:
df1:
     col1          col2
0    data1         math
1    data1         math2
2    data2         math
3    data3         math
4    data4         math2

df2:
     col1          col2
0    data1         math
1    data1         math2
2    data1         math3
3    data2         math2
4    data3         math
5    data4         math2
6    data4         math3

how can i compare these two dataframes based on col1 and col2 and get the difference (remove all the rows that match with df1) and have a dataframe like this one:
     col1          col2
0    data1         math3
1    data2         math2
2    data4         math3

I tried this one but it is not working:
df3 = df2[~(df2['col2'].isin(df1['col2']))].reset_index(drop=True)

A: Your solution should be changed with compare MultiIndex or tuples:
df3 = df2[~df2.set_index(['col1','col2']).index.isin(df1.set_index(['col1','col2']).index)].reset_index(drop=True)

df3 = df2[~df2[['col1','col2']].apply(tuple, 1).isin(df1[['col1','col2']].apply(tuple, 1))].reset_index(drop=True)

A: You can perform a merge with indicator=True and keep only the right_only rows:
(df1.merge(df2, on=['col1', 'col2'], how='outer', indicator=True)
    .query('_merge == "right_only"')
    .drop(columns='_merge').reset_index(drop=True)
)

output:
    col1   col2
0  data1  math3
1  data2  math2
2  data4  math3


text:
Q: Using time component in dataframe as a condition I have a pandas dataframe column that contains a str of time as follows:
Time
17:24:00
17:25:00
17:26:00

and I have already cast the column to datetime as follows:
new_data['Time'] = pd.to_datetime(new_data['Time'],
                                  format='%H:%M:%S').apply(pd.Timestamp)

Now the column is in datetime64 as needed and shows:
0         1900-01-01 17:24:00
1         1900-01-01 17:25:00
2         1900-01-01 17:26:00

My question is as follows: I need to use the different time components of time as selection criteria for filtering. For example:
filtered_df = data.loc[(new_data['Time'].Hour == 17 )]

or
filtered_df = data.loc[(new_data['Time'].Minutes == 24 )]

But I cannot figure out how to select the individual components (Hour, Minutes, Seconds) now that I have it converted to datetime.


text:
Q: How Do I Install Specific Git Branch Using NPM? I am using Angular 2 Google Maps in my project. Someone created a branch that has the functionality I need. I would like to npm i that branch instead of master. I found a question telling me how to do it here (Install specific branch from github using Npm), which recommends the following format:
npm install git://github.com/shakacode/bootstrap-loader.git#v1 --save

So I tried:
npm i git://github.com/SebastianM/angular-google-maps.git#add-clustered-markers --save
npm i git://github.com/SebastianM/angular-google-maps.git#inovex:add-clustered-markers --save

I get the following error:
npm ERR! Command failed: git -c core.longpaths=true rev-list -n1 add-clustered-markers
npm ERR! fatal: ambiguous argument 'add-clustered-markers': unknown revision or path not in the working tree.
npm ERR! Use '--' to separate paths from revisions, like this:
npm ERR! 'git <command> [<revision>...] -- [<file>...]'

The docs don't seem to cover installing branches. From the error, it seems that I need to specify the revision number somehow, I can't find information on how to do that.
TL;DR: How do I npm i a specific repo branch.

A: Maybe because that branch does not exist in the specified project.


text:
Q: Access In memory Database with 2 difference DbContext in EntityFrameworkCore I have 2 different DbContext in EntityFramework core 6. But they refer to same In Memory database:
builder.Services.AddDbContext<FirstDbContext>(op => { op.UseInMemoryDatabase("TestDb"); });
builder.Services.AddDbContext<SecondDbContext>(op => { op.UseInMemoryDatabase("TestDb"); });

I want use one of the context for writing in Database and another for reading. (CQRS)
For writing in database I use Set for inserting and it writes in database successfully.
but when I want to retrieve from second dbcontext it doesn't return any data (Empty Master).
    private readonly FirstDbContext firstDb;
    private readonly SecondDbContext secondDb;

    public TestController(FirstDbContext firstDb, SecondDbContext secondDb)
    {
        this.firstDb = firstDb;
        this.secondDb = secondDb;
    }
    [HttpPost]
    public void Set()
    {
        var master = new First.Master
        {
            Id = 1,
            Name = "Master"
        };
        var detail = new First.Detail
        {
            DetailName = "DetailName",
            MasterId = 1
        };
        var detail2 = new First.Detail
        {
            DetailName = "Detail2Name",
            MasterId = 1
        };
        firstDb.Masters.Add(master);
        firstDb.Details.Add(detail);
        firstDb.Details.Add(detail2);
        firstDb.SaveChanges();
    }

    [HttpGet]
    public void Get()
    {
        var masters = secondDb.Masters.Include(x => x.Details).ToList(); //Empty means count equals 0
    }

Just I want to know why it doesn't read data from database while their name are same?


text:
Q: How to set a string from a previously defined string in Android? I have the following code:
public void onClickV(View view){
 String title = "Go To...";
}

public void showDialog (View arg0) {
dialog.setTitle(this.String.title);
}

But the "this.String.title" isn't working at all. How could I set the title of the dialog depending on what the string is set to by an onClick method?
Thanks
EDIT: How would I do something similar for images?

A: Declare a variable outside the function.
String title;

public void onClickV(View view){
  title = "Go To...";
}

public void showDialog (View arg0) {
dialog.setTitle(title);
}

A: Don't use harcoded String. Use a string ressource.
In strings.xml
<string name="title">Go to...</string>

In Activity.java
public void showDialog(View arg0) {
    dialog.setTitle(getString(R.string.title));
}


text:
Q: Why does a USB Adapter set to monitor mode on Linux not capture non-WiFi traffic send on the same frequency (2.4GHz) as WiFi ? I have a WiFi Adapter from Alfa that can function in Monitor mode on Linux. Once I set it up and run Wireshark, I am able to see traffic across other routers and devices. If there is a new protocol that uses the same 2.4GHz to transfer data, but it is not following the traditional tcp/ip protocol (like the 3-way handshake), can I still monitor it on my Alfa Adapter?

A: If it's not TCP, but it is Wi-Fi, you should be able to capture it; the capturing is done at the link layer, so it should see all Wi-Fi traffic that it can receive.  It can capture UDP traffic (which has no 3-way handshake), and it can even capture non-IP traffic.
If it's not Wi-Fi traffic - i.e., some other form of networking that happens to use a 2.4 GHz radio, but that doesn't conform to any of the PHYs from the IEEE 802.11 standard - you won't be able to monitor it with a Wi-Fi adapter, because it's not Wi-Fi.

A: @Guy Harris is largely correct, except the answer ignores extensions to the WIFI protocol in future - So, hypothetically, if your USB card was an 802.11g card, but other people were using 802.11n, the USB card would not be able to pick up perfectly valid WIFI tranmissions from the faster device, because it can't see the data flow.
So, if there is a new software protocol the hardware should be able to handle it, but if there is a newer version of the 802.11 standard which requires hardware upgrades then no.


text:
Q: Vue 3 include local static files into index.html <!DOCTYPE html>
<html lang="">
  <head>
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link rel="stylesheet" href="semantic/dist/semantic.min.css">

I have a basic Vue 3 project and within my public/index.html file I want to include files from root directory (e.g. node_modules or my semantic folder)
I've tried various configurations within vue.config.js file but seems like none of them works.
module.exports = {
  publicPath: '',
}

What's the proper way of including custom local css/js files into index.hmtl without moving them directly into public directory?

A: I was with a similar problem a time ago, I asked here too but I found the solution myself, here is the link, how I was using my own webpack configuration, it may differ from what you need to do, but I think the core is the same, the esModule option on file-loader was messing with the path of local files I wanted to load.


text:
Q: React Native Hot Reloading not working on IOS Simulator I'm making a React Native app. And debugging or working with it, it get very tedious day by day due to the time it takes to reload the app every single time with Command+R to refresh and see my changes.
I found that is possible to do Live Reload/Hot Reload. But is not working for me.
Every time I do a change on my code, shows up the "Hot Loading..." above, but you can wait 20 minutes and it won't reload anything.
What could be wrong here? Let me know what to check and I can edit this post.

A: I was having a similar problem. Solved running:
rm -rf /usr/local/var/run/watchman && brew uninstall watchman && brew install watchman

From this comment.


text:
Q: re2: extracting multiple fields between paired delimiters I have a log file. Each line (or record) in the log file retains the following format:
tsB{{2020-08-18 15:02:29,793}}tsE,fnB{{standard_task_runner.py}}fnE,lnB{{53}}lnE,lvlB{{INFO}}lvlE

Here is what I want to do:
1] Extract 2020-08-18 15:02:29,793 with timestamp as key
2] Extract standard_task_runner.py with module as key
3] Extract 53 with line as key
4] Extract INFO with loglvl as key
Using re2 tools, how can I do this?
The regular expression I have tried:
"(*tsB{{<timestamp>}}tsE) (*fnA{{<module>}}fnB) (*lnB{{<line>}}lnE) (*lvlB<loglvl>lvlE)"

A: the following regular expression will match

*

*the timestamp

*the name of the script

*the line

*loglevel

{{.+?}}

explanations

*

*{{ and }} match literal {{ and }}

*.+? will match any character untill it will find }} i.e it will stop on the first }}


text:
Q: Training Perceptrons with Backprop Is it possible to train a simple perceptron with a threshold activation function such as this one: https://en.wikipedia.org/wiki/Perceptron with Backpropagation instead of the perceptron rule?
is it a problem that threshold functions are not defined around 0?

A: No, it is not possible. In order to use backprop you have to have non-zero derivatives of the function. Derivative of the step function is zero everywhere.


text:
Q: Client side routing with Page.js and bootstrap tabs I'm trying to get the Page.js client side routing library to work with Bootstrap 3 built in tabs, so that my back and forward buttons in the browser navigates between routes and show the corresponding tab.
With my current code setup it works sometimes, but it behaves inconsistently. Sometimes with navigates to a visited tab, and sometimes it does not (nothing happens). My tabs are built with the Bootstrap tabs with data-toggle, so it is only using the built in Bootstrap javascript for it's default behaviour.
If someone would be able to help me make the back and forward buttons working between routes, also showing the appropriate tabs, I would be grateful!
Javascript
var page = page;

/**
 * Define routes and callbacks
 */
page('/profile', function(ctx) {
    showTab(ctx.pathname);
    console.log(ctx.pathname);

});

page('/search', function(ctx) {
   showTab(ctx);
    console.log(ctx.pathname)

});

page('/account',  function(ctx) {
    showTab(ctx.pathname);
    console.log(ctx.pathname);
});

/**
 * Visit route corresponding to the current clicked tab
 */

$(document).ready(function () {
    $(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
        console.log("Hello again")
        var targetView = $(e.target).attr('href')
        targetView = targetView.replace("#", "");
        page('/'+ targetView)
    })
});

/**
 * Show tab corresponding to current route/path
 */

function showTab(path) {
        path = path.toString().replace('/', '');
        var selector = '.nav-tabs a[href="#' + path + '"]'
        $(selector).tab("show");
}

//start route
page();

A: I got stuck in the exact same situation recently! Here's how I solved it.
The Problem
Assume you were on /account then navigated to /search and pressed back button, which leads you to /account.
Following happens:

*

*Page.js receives url (which is /account) and calls its handler, for this case:
page('/account',  function(ctx) {
    showTab(ctx.pathname);
    console.log(ctx.pathname);
});

*in showTab following code gets executed:
...
$(selector).tab("show");
...

which shows the corresponding tab. So far so good...

*on('shown.bs.tab', ... event gets triggered and makes this happen:
page('/'+ targetView)

which effectively redirects you to the same page you're on already and makes your browser move one step forward so it removes all 'forward' history.
The Solution
... is very simple: just check if you are already on the desired url before calling page() once again in on('shown.bs.tab', ...), something like this:
if (window.location.pathname != '/' + targetView)
    page('/' + targetView)


text:
Q: Magento - Downloadable product link empty We have a problem with our Magento CE 1.7.0.2 Shop before going live, We do not exactly know when did this one happen. We want to offer digital goods (pictures) as download links from an external host.
Everything worked fine - we did not test the checkout for a month.
Now we have a problem, if a customer buys a digital good, his download link for his picture does not work. It is empty. The hash key in the DB seems ok. In Backend, the purchase was triggered. We suppose the connection between the hash key and the external URL is wrong.
We did 2 things since that but already applied a rollback. We installed SSL certificate and a delete old orders extension.
Can one of these things cause our problem?

A: Its fault of Google Cloud. Every other hosting company works...


text:
Q: How to handle file upload element in Selenium WebDriver? I am writing a script in Selenium using WebDriver and JUnit to upload files on server. But unable to do it because I don't know how to handle file explorer window of Windows(OS) shows on the click of choose file button of file upload element.
I have tried it by enter the file path directly in the text box and then click upload button. But still it shows please choose a file to upload.
Below is the HTML of element:

  File to upload
          <input type="file"  name="image" required />
  <input type="hidden" class="form-control" placeholder=""  name="failure" value="/error"/>
  <input type="hidden" class="form-control" placeholder=""  name="success" value="/success" />
          <input type="hidden" class="form-control" placeholder=""  name="keyword" value=""/>
          <input type="hidden" class="form-control" placeholder=""  name="category" value="" />

  <input type="submit" value="upload" class="btn btn-primary btn-lg" disabled />
</fieldset>

A: You can use this

//Actions act= new Actions(driver);
WebElement choose=driver.findElement(By.xpath("//input[@id='choose_file']"));

//act.moveToElement(choose).perform();
Thread.sleep(2000);
choose.sendKeys("D:\\DocLib\\Aadhaar\\1 Aamir.jpg");


text:
Q: 'Home' menu item in Joomla displays an empty drop down? Alternatively, how do I even create a new 'Home' menu item that links to the home page? Joomla is very frustrating. It seems so complicated to do either of the following:

*

*Remove the drop down behavior of the 'Home' menu item in my nav bar is creating. It is just an empty drop down when all I want it to do is just be a simple link that goes back to the home page.

*Say I remove the 'Home' menu item and create a new one, it gives no options in the menu manager to set this up as it only gives me options to link to articles? I have done some research and people say to link it as an external/internal URL however i keep getting an error saying the menu item must be a component.
At the moment, my 'Home' menu item is linking to Featured Articles which displays my home page.
Anyone know how to fix this simple issue?
Here are some more screenshots of the backend:


text:
Q: iOS equivalent of Android external/public storage Is there any equivalent of Android's external/public storage concept in IOS
https://developer.android.com/guide/topics/data/data-storage.html#filesExternal
I don't want the physical external storage in iOS but at least a common public folder where multiple apps can read/write from.
Also i want to check if there is any way to share a file between two applications on a same device. My file can get huge
AFAIK with air drop i can share files between applications in different devices.
Best Regards,
Saurav

A: App groups can be a possible solution for your case if you are going to share data among your apps.
Otherwise creating an extension & allow user to store data in cloud storage could be a possible solution.
https://www.centerdevice.de/document-and-share-extensions-in-ios/